put page number when create PDF with iTextSharp

Basically, you have two options: either you create the document in one go, or you create the document in two passes.

If you create the document in one go, you don’t know the value of Y (the total number of pages) in advance, so you need to create a PdfTemplate object as a place holder. This is demonstrated in the MovieCountries1 example.

In this example, we create a TableHeader class that extends PdfPageEventHelper. We create an instance of the PdfTemplate class for the total in the OnOpenDocument() method, we use this total placeholder in the OnEndPage() method where we add the header or footer, and we fill out the total number of pages in the OnCloseDocument() method.

The disadvantage of this approach is that it’s something hard to predict the dimensions needed for total. The advantage is that you can create the document in one go (you don’t need to create the document in memory first).

If you create the document in two passes, you create the document without header/footer first, and then you examine the document to find out how many pages it contains. Then you use PdfStamper to add the page numbers to each page. This is shown in the TwoPasses example.

These examples are taken from my book “iText in Action – Second Edition”. You can download chapter 6 for free from this URL: http://manning.com/lowagie2/samplechapter6.pdf

Please consult the [official documentation][4] when you are in doubt about specific functionality.

Update: I don’t understand why you prefer looking at unofficial examples. The example I gave you looks like this:

using (PdfStamper stamper = new PdfStamper(reader, ms2)) {
    // Loop over the pages and add a header to each page
    int n = reader.NumberOfPages;
    for (int i = 1; i <= n; i++) {
        // Add content
    }
}

Yet for some reason you Googled an example that is much more complex (and overkill for what you need).

Just replace the // Add content part with:

ColumnText.ShowTextAligned(stamper.GetUnderContent(), Element.ALIGN_CENTER, new Phrase((i + 1) + "https://stackoverflow.com/" + totalPages, fontetexto), 297f, 15f, 0);

Note that I adapted the x value in the ShowTextAligned() method. You’re creating a page with size A4, which means your page is 595 user units wide. If you add page numbers at position x = 820, the footer will be added, but it will be outside the visible area of the page. Please don’t copy/paste code without knowing the parameters of each method.

Leave a Comment