Adding page numbers to an existing PDF

This is a code example of iText PDF, discover more.

30th October 2015
admin-marketing

Switch code for this example

In this example, we use ColumnText to add page numbers to an existing PDF document.



StampPageXofY.java
  1. package sandbox.stamper;
  2.  
  3. import com.itextpdf.text.DocumentException;
  4. import com.itextpdf.text.Element;
  5. import com.itextpdf.text.Phrase;
  6. import com.itextpdf.text.pdf.ColumnText;
  7. import com.itextpdf.text.pdf.PdfContentByte;
  8. import com.itextpdf.text.pdf.PdfReader;
  9. import com.itextpdf.text.pdf.PdfStamper;
  10.  
  11. import java.io.File;
  12. import java.io.FileOutputStream;
  13. import java.io.IOException;
  14.  
  15. import sandbox.WrapToTest;
  16.  
  17. @WrapToTest
  18. public class StampPageXofY {
  19.  
  20.     public static final String SRC = "resources/pdfs/nameddestinations.pdf";
  21.     public static final String DEST = "results/stamper/pagenumbers.pdf";
  22.  
  23.     public static void main(String[] args) throws IOException, DocumentException {
  24.         File file = new File(DEST);
  25.         file.getParentFile().mkdirs();
  26.         new StampPageXofY().manipulatePdf(SRC, DEST);
  27.     }
  28.  
  29.     public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
  30.         PdfReader reader = new PdfReader(src);
  31.         int n = reader.getNumberOfPages();
  32.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  33.         PdfContentByte pagecontent;
  34.         for (int i = 0; i < n; ) {
  35.             pagecontent = stamper.getOverContent(++i);
  36.             ColumnText.showTextAligned(pagecontent, Element.ALIGN_RIGHT,
  37.                     new Phrase(String.format("page %s of %s", i, n)), 559, 806, 0);
  38.         }
  39.         stamper.close();
  40.         reader.close();
  41.     }
  42. }
Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now