Adding page numbers to an existing PDF

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

31st May 2016
iText PDF

Switch code for this example

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



StampPageXofY.java
  1. /*
  2.  
  3.     This file is part of the iText (R) project.
  4.     Copyright (c) 1998-2016 iText Group NV
  5.  
  6. */
  7.  
  8. package com.itextpdf.samples.sandbox.stamper;
  9.  
  10. import com.itextpdf.kernel.pdf.PdfDocument;
  11. import com.itextpdf.kernel.pdf.PdfReader;
  12. import com.itextpdf.kernel.pdf.PdfWriter;
  13. import com.itextpdf.layout.Document;
  14. import com.itextpdf.layout.element.Paragraph;
  15. import com.itextpdf.layout.property.TextAlignment;
  16. import com.itextpdf.layout.property.VerticalAlignment;
  17. import com.itextpdf.samples.GenericTest;
  18. import com.itextpdf.test.annotations.type.SampleTest;
  19.  
  20. import org.junit.experimental.categories.Category;
  21.  
  22. import java.io.File;
  23.  
  24. @Category(SampleTest.class)
  25. public class StampPageXofY extends GenericTest {
  26.     public static final String DEST = "./target/test/resources/sandbox/stamper/stamp_page_x_of_y.pdf";
  27.     public static final String SRC = "./src/test/resources/pdfs/nameddestinations.pdf";
  28.  
  29.     public static void main(String[] args) throws Exception {
  30.         File file = new File(DEST);
  31.         file.getParentFile().mkdirs();
  32.         new StampPageXofY().manipulatePdf(DEST);
  33.     }
  34.  
  35.     @Override
  36.     protected void manipulatePdf(String dest) throws Exception {
  37.         PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(DEST));
  38.         Document doc = new Document(pdfDoc);
  39.         int n = pdfDoc.getNumberOfPages();
  40.         for (int i = 1; i
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