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

iTextSharp 5:如何将页脚格式为“x/x”的页码右对齐

解决iTextSharp 5中页码CurrentPage/TotalPages的右对齐问题

嘿,我完全懂你现在的困扰——想让页脚的CurrentPage/TotalPages整体右对齐,但现在只有CurrentPage/乖乖待在右边,总页数却跑到左边去了。咱们一步步把这个问题搞定。

先看你代码里的核心问题:在OnCloseDocument方法中,你错误地用了document.Add(new Paragraph(...)),这时候文档已经处于关闭状态,根本没法添加新内容;而且你给模板设置的文本矩阵位置不对,导致总页数没和当前页码的/衔接上,自然就跑偏了。

下面是修正后的完整代码,我标注了关键修改点:

// 先在类里定义类级别的变量,用来存页码模板和总页数
private PdfTemplate pageNumberTemplate;
private int totalPages;

public override void OnEndPage(PdfWriter writer, Document document)
{
    double capitalsocial;
    CultureInfo culture;
    string specifier = "N";
    iTextSharp.text.Font pfontfooter = FontFactory.GetFont(iTextSharp.text.Font.FontFamily.UNDEFINED.ToString(), 9f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
    iTextSharp.text.Font pfontNumbrePage = FontFactory.GetFont(iTextSharp.text.Font.FontFamily.UNDEFINED.ToString(), 13f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.LIGHT_GRAY);

    base.OnEndPage(writer, document);
    var tableContainerFooter = new PdfPTable(new[] { 9F, 1f }) { TotalWidth = 550f, PaddingTop = -51f, SpacingAfter = -50f, SpacingBefore = -50f, DefaultCell = { BorderWidth = 0 } };
    var tableFooter = new PdfPTable(new[] { 9F }) { DefaultCell = { BorderWidth = 0, HorizontalAlignment = 1 }, TotalWidth = 500f, PaddingTop = -51f, };
    tableFooter.HorizontalAlignment = 1;
    tableFooter.DefaultCell.BorderWidth = 0;
    tableFooter.DefaultCell.HorizontalAlignment = 1;

    var cb = writer.DirectContentUnder;
    // 只需要创建一个模板,不用为每一页都创建
    if (pageNumberTemplate == null)
    {
        pageNumberTemplate = cb.CreateTemplate(50, 50);
    }

    int currentPage = writer.CurrentPageNumber;
    string currentPageText = currentPage.ToString() + "/";
    BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    float currentPageTextWidth = bf.GetWidthPoint(currentPageText, 10); // 字体大小和后面保持一致

    // 计算整体右对齐的起始X位置:页面右边界减去边距,再预留足够的页码宽度(这里按三位数页码预估,可按需调整)
    float rightAlignedX = document.PageSize.Right - document.RightMargin - bf.GetWidthPoint("999/999", 10);
    float yPosition = document.PageSize.GetBottom(document.BottomMargin);

    // 绘制当前页码和/
    cb.BeginText();
    cb.SetFontAndSize(bf, 10);
    cb.SetTextMatrix(rightAlignedX, yPosition);
    cb.ShowText(currentPageText);
    cb.EndText();

    // 把模板放在当前文本的右侧,也就是/的后面
    cb.AddTemplate(pageNumberTemplate, rightAlignedX + currentPageTextWidth, yPosition);

    // 你的页脚其他内容保持不变
    tableFooter.AddCell(new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(-0.2F, 131F, BaseColor.LIGHT_GRAY, Element.ALIGN_CENTER, 9))));
    tableFooter.AddCell(new Paragraph(raison_sociale + " " + forme_juridique + " au capital de " + capital + "" + devise, pfontfooter));
    tableFooter.AddCell(new Paragraph("I.F: " + idfscal + " - R.C.: " + rc + " - Patente: " + patente + " - C.N.S.S: " + cnss + " - I.C.E: " + ice, pfontfooter));
    tableFooter.AddCell(new Paragraph("Tél.: " + tel1 + " - Fax: " + fax + " - Mail: " + email, pfontfooter));
    tableContainerFooter.AddCell(new PdfPCell(tableFooter) { BorderWidth = 0f, });
    tableContainerFooter.WriteSelectedRows(0, -1, 45f, document.Bottom + 55f, writer.DirectContent);
}

public override void OnCloseDocument(PdfWriter writer, Document document)
{
    base.OnCloseDocument(writer, document);
    totalPages = writer.PageNumber;
    BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

    // 在模板里绘制总页数,位置从(0,0)开始就行,因为模板已经被定位到正确的位置了
    pageNumberTemplate.BeginText();
    pageNumberTemplate.SetFontAndSize(bf, 10);
    pageNumberTemplate.SetTextMatrix(0, 0);
    pageNumberTemplate.ShowText(totalPages.ToString());
    pageNumberTemplate.EndText();
}

关键修改说明:

  • 简化模板创建:只需要一个模板来绘制总页数,不用给每一页都创建模板列表。
  • 重新计算对齐位置:通过document.PageSize.Right - document.RightMargin拿到页脚区域的右边界,再减去预估的最大页码宽度,确保整个CurrentPage/TotalPages块都能右对齐。
  • 修正模板定位:在OnCloseDocument中,直接在模板的(0,0)位置绘制总页数,因为模板已经通过AddTemplate精准定位到了CurrentPage/的右侧,这样两者就能完美衔接。
  • 移除错误的document.Add:文档关闭后不能再添加内容,所有页码内容都通过DirectContent和模板来绘制才是正确的方式。

这样修改后,整个CurrentPage/TotalPages就会整体右对齐,总页数也会乖乖显示在/的后面啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:20:58