问题描述
我正在使用 camera package 从我的手机拍摄图像。现在我想通过单击按钮将这些图像转换为单个 pdf 文件。为此,我正在使用 pdf package。问题是,当我拍摄一个/多个图像并单击按钮时,我总是收到此异常:
例外:此小部件创建了 20 多个页面。这可能是小部件或文档中的问题
我在此处阅读了许多建议:#145、#146 和此处 stack,但对我的情况没有任何帮助。
只有当我将图像裁剪为非常小的尺寸时,才能创建 pdf。仅供参考,这是我用来裁剪 image_cropper
按钮:
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),),
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
//PdfImage _image;
final _pdf = pw.Document();
final _image = <PdfImage>[];
final _imageFit = <pw.BoxFit>[];
Future<void> _addImagesToPdf() async {
// for (var i = 0; i < _model.imageFilePaths.length; i++) {
// _image = PdfImage.file(
// _pdf.document,// bytes: File(_model.imageFilePaths[i]).readAsBytesSync(),// );
// }
//trying with list of pdf images => Best solution for Now. It uploads
//multiple images but only when they are cropped by a lot
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>[
//If you wrap everything inside a column,the framework cannot
//create new pages: a Column is seen as one object
//that cannot be split. You can try Wrap instead.(Comment from author)
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)
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),);
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)