Search code examples
flutterdart-pdf

Margins are missing in PNGs generated from a PDF


I'm using the pdf library to generate PDFs in my flutter app. And I have to convert the PDF pages to images for a feature. When I try to do that using the printing package, there are no margins on the page sides like in the PDF.

Like below: Screenshot of the pdf The image generated by the package

This is the code I use to convert the pages to PNGs:

var pageNo = 0;
await for (var page in Printing.raster(widget.pdf, dpi: 100)) {
  pageNo++;
  final image = await page.toPng();
  await File('/storage/emulated/0/Download/Invoice-${widget.invoiceNo}-page$pageNo.png')
              .writeAsBytes(image);
}

This is the pageTheme I use to create the PDF:

pw.PageTheme(
      margin: const pw.EdgeInsets.all(40),
      theme: pw.ThemeData(defaultTextStyle: pw.TextStyle(font: font)),
      pageFormat: PdfPageFormat.a4.copyWith(
        marginRight: 40,
        marginLeft: 40,
        marginBottom: 40,
        marginTop: 40,
      ),
      buildBackground: (_) => pw.FullPage(
        ignoreMargins: false,
        child: pw.Container(color: PdfColors.white),
      ),
    )

Solution

  • In your above code Set ignoreMargins: true read more about FullPage and ignoreMargins

    buildBackground: (_) => pw.FullPage(
        ignoreMargins: true,
        child: pw.Container(color: PdfColors.white),
      ),