Superimposing content from one PDF into another PDF

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

8th November 2015
admin-marketing

Switch code for this example

SuperImpose.java
  1. /*
  2.  * Example written in answer to:
  3.  * http://stackoverflow.com/questions/33582245/extract-pdf-page-and-insert-into-existing-pdf
  4.  */
  5. package sandbox.stamper;
  6.  
  7. import com.itextpdf.text.DocumentException;
  8. import com.itextpdf.text.pdf.PdfContentByte;
  9. import com.itextpdf.text.pdf.PdfImportedPage;
  10. import com.itextpdf.text.pdf.PdfReader;
  11. import com.itextpdf.text.pdf.PdfStamper;
  12. import java.io.File;
  13. import java.io.FileOutputStream;
  14. import java.io.IOException;
  15.  
  16. /**
  17.  * @author Bruno Lowagie (iText Software)
  18.  */
  19. public class SuperImpose {
  20.     public static final String SRC = "resources/pdfs/primes.pdf";
  21.     public static final String[] EXTRA =
  22.         {"resources/pdfs/hello.pdf", "resources/pdfs/base_url.pdf", "resources/pdfs/state.pdf"};
  23.     public static final String DEST = "results/stamper/primes_superimpose.pdf";
  24.  
  25.     public static void main(String[] args) throws IOException, DocumentException {
  26.         File file = new File(DEST);
  27.         file.getParentFile().mkdirs();
  28.         new SuperImpose().manipulatePdf(SRC, DEST);
  29.     }
  30.    
  31.     public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
  32.         PdfReader reader = new PdfReader(src);
  33.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  34.         PdfContentByte canvas = stamper.getUnderContent(1);
  35.         PdfReader r;
  36.         PdfImportedPage page;
  37.         for (String path : EXTRA) {
  38.             r = new PdfReader(path);
  39.             page = stamper.getImportedPage(r, 1);
  40.             canvas.addTemplate(page, 0, 0);
  41.             stamper.getWriter().freeReader(r);
  42.             r.close();
  43.         }
  44.         stamper.close();
  45.     }
  46. }
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