-2

Hello i'm working with flutter desktop project. How can i attached assets images with the format of jpg/png in Flutter pdf pages.

static Future<File> generate(Invoice invoice) async {
    final pdf = Document();

    pdf.addPage(MultiPage(
      build: (context) => [
        buildHeader(invoice),
        dashLine(),
        SizedBox(height: 20.0),
        buildTitle(invoice),
        buildInvoice(invoice),
        dashLine(),
        priceDetails(invoice.total),
      ],
    ));

    return PdfApi.saveDocument(
        name:
            '${DateTime.now().day}_${DateTime.now().month}_${DateTime.now().year}.pdf',
        pdf: pdf);
  }
CbL
  • 734
  • 5
  • 22
Dren
  • 21
  • 9
  • i think the package's example in readme shows the way to load image? https://pub.dev/packages/pdf – CbL Oct 04 '21 at 07:11

1 Answers1

3

According to the document for local assets:

final image = pw.MemoryImage(
  File('test.webp').readAsBytesSync(),
);

pdf.addPage(pw.Page(build: (pw.Context context) {
  return pw.Center(
    child: pw.Image(image),
  ); // Center
})); // Page

for online images:

 Future<Uint8List> _generatePdf(PdfPageFormat format) async {
    final pdf = pw.Document();

    final img = await networkImage(
        'https://upload.wikimedia.org/wikipedia/commons/5/57/Cumulus_Clouds_over_Yellow_Prairie2.jpg');

    pdf.addPage(
      pw.Page(
        pageFormat: format,
        build: (context) {
          return pw.Center(
            child: pw.ClipRRect(
              horizontalRadius: 10,
              verticalRadius: 10,
              child: pw.Image(img),
            ),
          );
        },
      ),
    );

    return pdf.save();
  }