2
votes

I am working through some more examples from the new itextpdf website...(good job by the way) I normally add page numbers in headers and footers as a second pass over the document once it is completed.

Is there a way to add the page number dynamically in a header or footer as an onendpage event?

Clearly this could be done by using a counter with document.addPage(), but text may create new pages all by itself when given a large text block so this would then not work.

1

1 Answers

3
votes

Thank you very much for your comment on the new web site!

You can indeed get the current page number in the onEndPage() method and add it to the document. Please take a look at the MovieHistory2 example, or better yet: the MovieCountries1 example.

Allow me to simplify the onEndPage() method of these examples:

public void onEndPage(PdfWriter writer, Document document) {
    Rectangle rect = writer.getPageSize();
    ColumnText.showTextAligned(writer.getDirectContent(),
        Element.ALIGN_CENTER, new Phrase(
            String.format("page %d", writer.getPageNumber())),
            (rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 18, 0);
}

In this snippet, writer.getPageNumber() will give you the current page number. I add it to the page at the bottom-middle.