flutterdartpdfdart-pdf

How to dynamically add new pages to a PDF in Flutter when content overflows?


I'm working on a Flutter project where I need to generate a PDF document and automatically add new pages when the content overflows the current page. I'm using the pdf package to generate the PDF.

I've tried adding content to pages and checking for overflow, but I'm facing some challenges with the implementation. How can I efficiently add new pages when the content exceeds the available space on the current page?

Here's a simplified version of my code:

Future<void> generate() async {
    final logo = await _logo();
    final pdf = pw.Document(); 
    pdf.addPage(pw.Page(
      pageFormat: PdfPageFormat.a4,     
      build: (pw.Context context) {
        return pw.Column(
          children: [
            pw.Row(
              crossAxisAlignment: pw.CrossAxisAlignment.center,
              children: [
                logo,
                pw.Text(
                  Texts.title.toUpperCase(),
                  textAlign: pw.TextAlign.center,
                  style: pw.TextStyle(
                    fontSize: 18,
                    fontWeight: pw.FontWeight.bold,
                  ),
                ),
              ],
            ),
            _buildTableDadosTransformador(),
            _buildTablePotencia(),
            _buildTableNucleo(),
            _buildTablePrimario(),
          ],
        );
      },
    ));
    savePDF(pdf);
  }

Solution

  • You can use MultiPage instead of Page This will increase the page when it overflows.

    pdf.addPage(
      pw.MultiPage(
        build: (context) {
          return [.....];
        }
       ),
    )