我如何在生成iText7 Pdf后将页码添加到它

  • 本文关键字:添加 Pdf iText7 c# pdf itext itext7
  • 更新时间 :
  • 英文 :

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:"无法在已刷新的上绘制元素页面">

我需要在最后添加页码,因为在生成pdf内容后,我会生成一个目录,并将其移动到文档的开头。因此,我只知道生成所有页面后的页码。

iText默认情况下会尝试提前刷新页面(即将其内容写入PdfWriter目标流并在内存中释放(,即在您启动下一个页面后不久。对于这样一个刷新的页面,您显然无法再添加第x页(共y页(标题。

有一些方法可以解决这个问题。例如,如果您有足够的可用资源,并且不需要激进的早期刷新,则可以通过使用不同的Document构造函数来切换它,该构造函数具有额外的布尔参数immediateFlush,并将该参数设置为false

因此,代替

new Document(pdfDoc)

new Document(pdfDoc, pageSize)

使用

new Document(pdfDoc, pageSize, false)

这是一个相关的答案

最新更新