You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#使用iTextSharp生成PDF获取总页数实现页脚页码遇doc.PageCount报错

iTextSharp实现「当前页码/总页数」页脚的正确方案

报错原因

OnEndPage 是单页内容生成完成时触发的事件,此时整个PDF文档还没有完全生成,iTextSharp无法提前获取到最终的总页数,所以直接调用doc.PageCount会出现报错或者返回错误值的问题。

实现思路

  • 单页生成时,用PdfTemplate在页脚预留总页数的显示占位区域
  • 等待所有页面内容全部生成完毕、文档即将关闭时,再把最终确定的总页数回填到所有页的预留占位区域中

完整实现代码

自定义页脚事件类

public class Footer : PdfPageEventHelper
{
    // 总页数占位模板
    private PdfTemplate _totalPageTemplate;
    // 页脚字体,提前创建避免重复实例化
    private readonly Font _footerFont = FontFactory.GetFont(FontFactory.HELVETICA_OBLIQUE, 8, BaseColor.Gray);

    // 文档打开时初始化占位模板
    public override void OnOpenDocument(PdfWriter writer, Document doc)
    {
        // 模板尺寸可根据实际显示需求调整
        _totalPageTemplate = writer.DirectContent.CreateTemplate(30, 12);
    }

    public override void OnEndPage(PdfWriter writer, Document doc)
    {
        PdfPTable footerTbl = new PdfPTable(2);
        // 页脚宽度适配文档可编辑区域宽度
        footerTbl.TotalWidth = doc.PageSize.Width - doc.LeftMargin - doc.RightMargin;
        footerTbl.DefaultCell.Border = Rectangle.NO_BORDER;
        footerTbl.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;

        // 第一列放当前页码文本
        Phrase currentPageText = new Phrase($"Page {doc.PageNumber} of ", _footerFont);
        footerTbl.AddCell(currentPageText);

        // 第二列放总页数占位模板
        PdfPCell totalPageCell = new PdfPCell(Image.GetInstance(_totalPageTemplate));
        totalPageCell.Border = Rectangle.NO_BORDER;
        totalPageCell.HorizontalAlignment = Element.ALIGN_LEFT;
        footerTbl.AddCell(totalPageCell);

        // 将页脚写入页面指定位置
        footerTbl.WriteSelectedRows(0, -1, doc.LeftMargin, doc.BottomMargin + 10, writer.DirectContent);
    }

    // 文档关闭前回填总页数
    public override void OnCloseDocument(PdfWriter writer, Document doc)
    {
        // doc.PageNumber此时为总页数+1,减1得到真实总页数
        ColumnText.ShowTextAligned(
            _totalPageTemplate, 
            Element.ALIGN_LEFT, 
            new Phrase((doc.PageNumber - 1).ToString(), _footerFont), 
            2, 2, 0
        );
    }
}

调用示例

// 初始化文档和Writer
Document doc = new Document();
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream("你的输出文件路径.pdf", FileMode.Create));
// 绑定自定义页脚事件
writer.PageEvent = new Footer();

// 后续正常打开文档、写入内容、关闭文档即可
doc.Open();
// 此处写你自己的PDF内容生成逻辑
doc.Close();

内容的提问来源于stack exchange,提问作者mINI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 09:36:03