繁体   English   中英

如何获取PDF文件的总页数-iTextSharp,C#

[英]How to get the total amount of pages of a PDF file - iTextSharp, c#

我需要帮助。 我花了最后4个小时来获取我的PDF文件的总页数。 我希望页脚中有类似“ 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。 现在可以了:)

请阅读文档 如果您不知道从哪里开始,请检查关键字 ,更具体地说: Y的第X页

这里有两个示例:

  • MovieCountries1可以一次性创建PDF,并在onDocumentClose()方法中添加总页数,因为您已经发现,您或任何类型的软件都无法知道总页数在关闭文件之前。
  • TwoPasses分两步创建PDF,这比您似乎选择的解决方案要可靠得多。

我敢肯定您对技术有足够的了解,可以理解Java并将其转换为C#,但是如果SO上的其他人没有,他们可以在这里这里找到这些示例的C#版本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM