Tutorial: iText by Example

Page numbering

Page Numbering:
Since RTF is rendered by the viewer and not on creation, the RtfWriter2 cannot calculate which page is currently being written. The RtfPageNumber provides the functionality to overcome this with one limitation:
  • It can only be used within the header or footer. In the main document it will not update correctly.

The RtfPageNumber should not be used alone, but always wrapped in for example a Paragraph or Table (see the example in the header/footers section). This can then set as the header/footer via a RtfHeaderFooter.
// Create a new Paragraph for the footer
Paragraph par = new Paragraph("Page ");
par.setAlignment(Element.ALIGN_RIGHT);

// Add the RtfPageNumber to the Paragraph
par.add(new RtfPageNumber());
            
// Create an RtfHeaderFooter with the Paragraph and set it
// as a footer for the document
RtfHeaderFooter footer = new RtfHeaderFooter(par);
document.setFooter(footer);
    	  
Example: java com.lowagie.examples.rtf.features.pagenumber.PageNumber
Generates a document with page numbers in the footer: see PageNumber.rtf
Extra jars needed in your CLASSPATH: itext-rtf.jar
Go to top of the page
Total Number of Pages:
If the total number of pages should also be displayed, then a RtfTotalPageNumber can be added to the Paragraph.
// Add the RtfTotalPageNumber to the Paragraph
par.add(" of ");
par.add(new RtfTotalPageNumber());

// Create an RtfHeaderFooter with the Paragraph and set it
// as a header for the document
RtfHeaderFooter header = new RtfHeaderFooter(par);
document.setHeader(header);
    	  
One caveat here though:
  • The total number of pages is not always updated immediately. This is because Word uses a lazy approach to counting the total number of pages. Only if you scroll down the document, will the total page number be calculated correctly.
Example: java com.lowagie.examples.rtf.features.pagenumber.TotalPageNumber
Generates a document with page numbers and total number of pages in the header: see TotalPageNumber.rtf
Extra jars needed in your CLASSPATH: itext-rtf.jar
Go to top of the page

iText, the #1 Java-PDF library




Amazon books:
amazon.co.uk-link