【问题标题】:How to get the total amount of pages of a PDF file - iTextSharp, c#如何获取 PDF 文件的总页数 - iTextSharp, c#
【发布时间】:2013-05-31 01:08:41
【问题描述】:

我需要帮助。我花了 4 个小时试图获取我的 PDF 文件的总页数。我想在页脚中有类似“Page X/Y”的内容。有人可以告诉我如何处理这段代码吗?

public class pdfPage : PdfPageEventHelper
{              
    public override void OnEndPage(PdfWriter writer, Document doc)
    {

        iTextSharp.text.Rectangle page = doc.PageSize;
        //PdfPTable EndTable = new PdfPTable(2);
        PdfPTable EndTable = new PdfPTable(2);
        EndTable.DefaultCell.Padding = 2f;
        EndTable.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
        iTextSharp.text.Font smallfont2 = FontFactory.GetFont(FontFactory.HELVETICA, "CP1250", 10);
        PdfPCell stopka1 = new PdfPCell(new Phrase("Left column - not important", smallfont2));
        stopka1.BorderWidthLeft = 0;
        stopka1.BorderWidthBottom = 0;
        stopka1.BorderWidthRight = 0;
        stopka1.HorizontalAlignment = Element.ALIGN_LEFT;
        stopka1.VerticalAlignment = Element.ALIGN_MIDDLE;
        PdfPCell stopka2 = new PdfPCell(new Phrase("Page " + doc.PageNumber + "/", smallfont2));
        stopka2.BorderWidthLeft = 0;
        stopka2.BorderWidthBottom = 0;
        stopka2.BorderWidthRight = 0;
        stopka2.HorizontalAlignment = Element.ALIGN_RIGHT;
        stopka2.VerticalAlignment = Element.ALIGN_MIDDLE;
        EndTable.AddCell(stopka1);
        EndTable.AddCell(stopka2);
        EndTable.TotalWidth = page.Width - doc.LeftMargin - doc.RightMargin;
        EndTable.WriteSelectedRows(0, -1, doc.LeftMargin, EndTable.TotalHeight + doc.BottomMargin - 45, writer.DirectContent);

    }
   } 

编辑

好的,我整理好了。我只是关闭了正在处理的 PDF 文件,然后将其复制为临时文件。然后在“OnEndPage”方法中,我计算了这个临时文档中的页数。后来,我打开了一个新文档,复制了这个临时文件中的所有内容,创建了一个 pdfPage 类的对象并将其连接到 writer2.PageEvent。现在可以了:)

【问题讨论】:

  • 你给了我们你的代码(这很好)。但是您还没有解释您的代码在什么意义上让您失望(不太好)。请详细说明您现有的代码究竟是如何让您失望的。
  • 我现在不知道该怎么办。我不知道如何获取这个“我的 PDF 文件的总页数”并将其放在这里 - PdfPCell stopka2 = new PdfPCell(new Phrase("Page " + doc.PageNumber + "/", smallfont2));

标签: c# itextsharp


【解决方案1】:

请阅读documentation。如果您不知道从哪里开始查找,请查看keywords,更具体地说:Page X of Y

这里有两个例子:

  • MovieCountries1 一次性创建 PDF,并在 onDocumentClose() 方法中添加总页数,因为正如您已经发现的那样,您或任何类型的软件都不知道总页数是多少将在文档关闭之前。
  • TwoPasses 分两次创建 PDF,这是一个比您似乎选择的解决方案更强大的解决方案。

我相信你足够精通技术,可以理解 Java 并将其翻译成 C#,但如果 SO 上还有其他人不懂,他们可以找到这些示例的 C# 版本herehere

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2015-05-29
    相关资源
    最近更新 更多