You need to enable JavaScript to run this app. Flutter集成camera包拍图转PDF时报组件生成超20页异常的解决
优惠活动
大模型
产品
解决方案
定价
更多

Flutter集成camera包拍图转PDF时报组件生成超20页异常的解决

Flutter 拍照生成多图PDF时触发20页超限异常的解决记录

在项目中集成camera插件实现移动端拍照功能,需求是点击按钮将拍摄得到的多张图片整合为单个PDF文件,因此引入pdf插件实现PDF生成能力。实际使用时遇到固定报错:

拍摄完成图片后点击生成按钮,始终抛出异常:Exception: This widget created more than 20 pages. This may be an issue in the widget or the document

排查过程中查阅了dart_pdf仓库下的#145、#146 issue以及StackOverflow上的相关解决方案,所有公开方案都没能解决问题,仅当使用image_cropper将图片裁剪到极小时,才能成功生成PDF文件。

触发问题的原始实现代码

按钮交互逻辑

Expanded(
  child: RaisedButton(
    color: _appTheme.blueGrey,
    onPressed: () async {
      await _addImagesToPdf();

      final _filePath = await _savePdf();

      model.navigateToUploadImagePage(_filePath);
    },
    child: Text(model.nextOrUploadLabel.toUpperCase(),
        style: Theme.of(context).textTheme.headline1),
  ),
),

旧版PDF生成与保存逻辑

import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;

final _pdf = pw.Document();
final _image = <PdfImage>[];
final _imageFit = <pw.BoxFit>[];

Future<void> _addImagesToPdf() async {
  // 逐张加载图片为PdfImage的实现,仅在图片被大幅裁剪时可正常工作
  for (var i = 0; i < _model.imageFilePaths.length; i++) {
    _image.add(
      PdfImage.file(
        _pdf.document,
        bytes: File(_model.imageFilePaths[i]).readAsBytesSync(),
      ),
    );
    _imageFit.add(pw.BoxFit.values[i]);
  }

  _pdf.addPage(
    pw.MultiPage(
      // maxPages: _model.imageFilePaths.length,
      pageFormat: PdfPageFormat.a4,
      //margin: const pw.EdgeInsets.all(32),
      build: (context) => <pw.Widget>[
        // 若将组件包裹在Column中,框架无法拆分Column跨页渲染
        pw.Wrap(
          children: <pw.Widget>[
            for (var i = 0; i < _image.length; i++)
              pw.ClipRect(
                child: pw.Image(
                  _image[i],
                  fit: _imageFit[i],
                ),
              ),
          ],
        ),
      ],
    ),
  );
}

Future<String> _savePdf() async {
  final tempDir = await getTemporaryDirectory();
  _file = File('${tempDir.path}/${DateTime.now()}.pdf')
    ..writeAsBytesSync(_pdf.save());

  return _file.path;
}

可正常运行的解决实现

将pdf插件升级到最新稳定版(验证可正常运行的版本为1.13),调整图片加载与PDF页面生成的逻辑,即可生成包含多张原图的PDF文件,参考实现代码如下:

final _image = <pw.Image>[];

Future<void> _addImagesToPdf() async {
  for (final imgPath in _model.imageFilePaths) {
    final bytes = File(imgPath).readAsBytesSync();
    _image.add(pw.Image.provider(
      pw.MemoryImage(bytes),
    ));
  }

  for (final img in _image) {
    _pdf.addPage(
      pw.Page(
        pageFormat: PdfPageFormat.a4,
        build: (context) => pw.Center(
          child: pw.Container(child: img),
        ),
      ),
    );
  }
}

内容的提问来源于stack exchange,提问作者kmtz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.12 06:36:05