how to add the current page number and total number of pages in Itextsharp [duplicate]

跟風遠走 提交于 2019-11-30 15:57:16

问题


how the current page number and the total number of pages in the pdf file as Page : 3/10

My code is as follows

        //PdfPTable saleTable = SaleTable();
        FileStream fileStream = new FileStream(Customer + "Invoice.pdf",
        FileMode.Create,
                                               FileAccess.Write,
                                               FileShare.None);
        Document doc = new Document(PageSize.A4);

        PdfWriter writer = PdfWriter.GetInstance(doc, fileStream);
        doc.Open();

        glue = new Chunk(new VerticalPositionMark());
        _phrase1.Add(new Chunk(glue));
        _phrase1.Add(new Chunk("Page Number: "));

        _para.Add(_phrase1);
         doc.Add(_para);

回答1:


Getting the current page number is easy. You have a PdfWriter instance named writer. You can ask that instance for the current page number:

int pageNo = writer.PageNumber

In Java:

int pageNo = writer.getPageNumber();

Getting the total number of pages is impossible unless you can look into the future. When you're on page 1, there is no way for iText to know how many pages you will add. Maybe you're going to invoke the Close() method immediately, in which case the total number of pages is 1. Maybe you're planning to add a hundred pages.

There are two ways to work around this problem.

#1: create the PDF in two passes

You first create the PDF in memory without page numbers. Afterwards, you use PdfStamper to add page numbers. This is explain in the following Q&A items and examples:

  • Example: Adding page numbers to an existing PDF (Java)
  • Example: TwoPasses (Java) / TwoPasses (C#)
  • iText - add content to the bottom of an existing page (StackOverflow Q&A)
  • iText Java - add header to an existing pdf (StackOverflow Q&A)
  • put page number when create PDF with iTextSharp (StackOverflow Q&A)
  • ...

#2: Use a placeholder for the total number of pages

You can create a PdfTemplate as a place holder for the total number of pages. Then, right before you Close() the document, you can fill out the total number of pages on that place holder.

This also has been explained many times before:

  • Example: MovieCountries1 (Java) / MovieCountries1 (C#)
  • Q&A section: page events
  • put page number when create PDF with iTextSharp (StackOverflow Q&A)
  • Page X of Y issue (StackOverflow Q&A)
  • ...

Please browse the official documentation before posting a question.



来源:https://stackoverflow.com/questions/36761429/how-to-add-the-current-page-number-and-total-number-of-pages-in-itextsharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!