Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

itextsharp

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);
like image 684
androidpol Avatar asked Apr 21 '16 06:04

androidpol


1 Answers

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.

like image 161
Bruno Lowagie Avatar answered Nov 12 '22 10:11

Bruno Lowagie