【问题标题】:How to insert the total pages number in the footer of each page of an iTextSharp document? [duplicate]如何在 iTextSharp 文档的每一页的页脚中插入总页数? [复制]
【发布时间】:2014-05-23 15:08:41
【问题描述】:

我需要使用 iTextSharp 处理以下情况:我正在创建 PDF 报告,但我以前不知道页数。

在每页的页脚中,我将页码插入为:“1/x”,其中 x 是我的报告的总页数。

此时我有一个名为 PdfHeaderFooter 的类,它扩展了 PdfPageEventHelper,我在其中实现了 OnEndPage() 以将页脚创建到我的PDF。

    // write on end of each page
    public override void OnEndPage(PdfWriter writer, Document document)
    {
        base.OnEndPage(writer, document);
        PdfPTable tabFoot = new PdfPTable(new float[] { 1F });
        tabFoot.TotalWidth = document.Right - document.Left;

        tabFoot.DefaultCell.Border = PdfPCell.NO_BORDER;
        tabFoot.DefaultCell.CellEvent = new RoundedBorder();

        PdfPTable innerTable = new PdfPTable(2);
        innerTable.SetWidths(new int[] { 247, 246 });
        innerTable.TotalWidth = document.Right - document.Left;  
        innerTable.DefaultCell.Border = PdfPCell.NO_BORDER;
        PdfPCell innerCellLeft = new PdfPCell(new Phrase("Early Warning - Bollettino")) { Border = PdfPCell.NO_BORDER, Padding = 5, MinimumHeight = 20, HorizontalAlignment = Element.ALIGN_LEFT };
        PdfPCell innerCellRight = new PdfPCell(new Phrase("Pag. " + numPagina + "/5")) { Border = PdfPCell.NO_BORDER, Padding = 5, MinimumHeight = 20, HorizontalAlignment = Element.ALIGN_RIGHT };
        innerTable.AddCell(innerCellLeft);
        innerTable.AddCell(innerCellRight);

        tabFoot.AddCell(innerTable);

        tabFoot.WriteSelectedRows(0, -1, document.Left, document.Bottom, writer.DirectContent);

        numPagina++;
    }

正如你现在所看到的,我使用以下方法处理这种情况:

 PdfPCell innerCellRight = new PdfPCell(new Phrase("Pag. " + numPagina + "/5")) 

但是通过这种方式,总页码是固定的 (/5),但我以前不知道页面是 5 还是不同的数字。

所以我认为我可以通过以下方式处理这种情况:

1) 我可以计算生成类中的 NewPage() 调用

2)然后我可以尝试修改每页页脚中总页的值

但我不知道这是否是一个聪明的解决方案,或者是否可行

【问题讨论】:

    标签: c# pdf pdf-generation itextsharp itext


    【解决方案1】:

    在您添加页码的那一刻(例如 Y 的第 X 页),您知道 X 的值,但无法知道 Y 的值。

    有两种方法可以解决这个问题。当您查看Page X of Y关键字页面时,您可以在官方文档中找到它。

    一种选择是引入一个空的PdfTemplate,您通常会在其中获得 Y 值。然后您可以实现onCloseDocument() 事件。此事件在文档关闭之前触发。此时,Y的值是已知的,可以画到PdfTemplate

    另一种选择是分两次创建 PDF。您首先在没有“Y 页 X”的情况下在内存中创建它。然后您使用PdfStamper 添加正确的 Page X of Y 值(因为您知道第一遍的总页数)。

    P.S.如果您需要代码示例,可以找到Java示例的C#端口here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-20
      • 2015-10-18
      • 1970-01-01
      • 2014-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多