生成 iText7 Pdf 后如何添加页码?

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();
}

这是我试过的代码,但出现以下异常:

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

我需要在最后添加页码,因为在生成 pdf 内容后,我生成了 table 内容并将其移至文档的开头。所以我只有在生成所有页面后才知道页码。

iText 默认尝试刷新页面(即将页面内容写入 PdfWriter 目标流并在内存中释放它们),即在您开始下一页后不久。对于这样一个刷新的页面,你显然不能再添加你的 page x of y header。

有一些解决方法。例如,如果您有足够的可用资源并且不需要那种激进的早期刷新,则可以使用不同的 Document 构造函数将其关闭,该构造函数具有额外的布尔参数 immediateFlush,并且将此参数设置为 false.

因此,而不是

new Document(pdfDoc)

new Document(pdfDoc, pageSize)

使用

new Document(pdfDoc, pageSize, false)

是一个相关的答案。