简体   繁体   中英

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.

iText by default tries to flush pages (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM