How can I add page numbers to my iText7 Pdf after im done generating it?

private void addPageNumbers(Document doc)
{
    var totalPages = doc.GetPdfDocument().GetNumberOfPages();
    for (int i = 1; i <= totalPages; i++)
    {
        // Write aligned text to the specified by parameters point
        doc.ShowTextAligned(new Paragraph(string.Format("page %s of %s", i, totalPages)),
                        559, 806, i, TextAlignment.RIGHT, VerticalAlignment.TOP, 0);
    }
    doc.Close();
}

this is the code i tried, but I get the following exception:

iText.Kernel.PdfException: "Cannot draw elements on already flushed pages."

I need to add the page numbers in the end because after generating the content of the pdf I generate a table of contents and move it to the beginning of the document. Therefore i only know the page numbers after generating all the pages.

1 answer

  • answered 2020-09-24 09:33 mkl

    iText by default tries to flush pages (i.e. write their contents to the PdfWriter target stream and free them in memory) early which is shortly after you started the next page. To such a flushed page you obviously cannot add your page x of y header anymore.

    There are some ways around this. For example, if you have enough resources available and don't need that aggressive, early flushing, you can switch it of by using a different Document constructor, the one with an extra boolean parameter immediateFlush, and setting this parameter to false.

    Thus, instead of

    new Document(pdfDoc)
    

    or

    new Document(pdfDoc, pageSize)
    

    use

    new Document(pdfDoc, pageSize, false)
    

    This is a related answer.