如何在颤振中将照片添加到 PDF

时间:2021-03-03 09:30:09

标签: flutter dart pdf

我使用这个库 https://pub.dev/packages/pdf 来生成 PDF。问题是我无法将照片添加到我的 PDF 中。每张照片的路径都保存在 List 的对象中。这就是我尝试实现的方式:

import 'package:pdf/widgets.dart' as pw;
​
​
Future<void> generatePDF() async {
​
pdf = pw.Document();
​
    pdf.addPage(
      pw.MultiPage(
        pageFormat: PdfPageFormat.a4,
        build: (pw.Context context) => [
          pw.Partitions(
            children: [
              pw.Partition(
                child: pw.Column(
                  crossAxisAlignment: pw.CrossAxisAlignment.start,
                  children: <pw.Widget>[
​
                  /// Photos list
                    pw.ListView.builder(
                      itemCount: 1,
                      itemBuilder: (pw.Context context, int index) {
                        return pw.Column(
                          children: _photosList
                                  ?.map(
                                    (photo) async => pw.Column(
                                      children: <pw.Widget>[
                                        pw.Text(
                                            "Photo id: ${photo.photoId} - Photo type: ${photo.photoType}"), // This is displayed correctly for each photo
                                        pw.Image(
                                          pw.MemoryImage(
                                            (await rootBundle
                                                    .load('${photo.photoPath}')) // This is not working because the photos are not in rootBundle and I can't find a solution to replace this line
                                                .buffer
                                                .asUint8List(),
                                          ),
                                        ),
                                      ],
                                    ),
                                  )
                                  ?.toList() ??
                              [],
                        );
                      },
                    ),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
    print('PDF Generated');
  }

输出:

enter image description here

1 个答案:

答案 0 :(得分:1)

导入 dart:io

import 'dart:io';

如果你有一个路径,你可以用它制作一个文件

File photo1 = File(photo.photoPath);

然后,您可以使用以下语句将该文件加载到 PDF 中:

MemoryImage memoryImage = pw.MemoryImage(photo1.readAsBytesSync()); //you could use async as well

这会给您留下一个来自 photoPath 的 MemoryImage。然后你可以简单地添加它:

pw.Image(memoryImage)