Superimposing content from one PDF into another PDF

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

31st May 2016
iText PDF

Switch code for this example

SuperImpose.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. /**
  9.  * Example written in answer to:
  10.  * http://stackoverflow.com/questions/33582245/extract-pdf-page-and-insert-into-existing-pdf
  11.  */
  12. package com.itextpdf.samples.sandbox.stamper;
  13.  
  14. import com.itextpdf.kernel.pdf.PdfDocument;
  15. import com.itextpdf.kernel.pdf.PdfReader;
  16. import com.itextpdf.kernel.pdf.PdfWriter;
  17. import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
  18. import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
  19. import com.itextpdf.samples.GenericTest;
  20. import com.itextpdf.test.annotations.type.SampleTest;
  21.  
  22. import org.junit.experimental.categories.Category;
  23.  
  24. import java.io.File;
  25.  
  26. @Category(SampleTest.class)
  27. public class SuperImpose extends GenericTest {
  28.     public static final String DEST =
  29.             "./target/test/resources/sandbox/stamper/super_impose.pdf";
  30.     public static final String[] EXTRA = {
  31.             "./src/test/resources/pdfs/hello.pdf",
  32.             "./src/test/resources/pdfs/base_url.pdf",
  33.             "./src/test/resources/pdfs/state.pdf"
  34.     };
  35.     public static final String SRC =
  36.             "./src/test/resources/pdfs/primes.pdf";
  37.  
  38.     public static void main(String[] args) throws Exception {
  39.         File file = new File(DEST);
  40.         file.getParentFile().mkdirs();
  41.         new SuperImpose().manipulatePdf(DEST);
  42.     }
  43.  
  44.     @Override
  45.     protected void manipulatePdf(String dest) throws Exception {
  46.         PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
  47.         PdfDocument srcDoc;
  48.         PdfFormXObject page;
  49.         PdfCanvas canvas = new PdfCanvas(pdfDoc.getFirstPage().newContentStreamBefore(),
  50.                 pdfDoc.getFirstPage().getResources(), pdfDoc);
  51.         for (String path : EXTRA) {
  52.             srcDoc = new PdfDocument(new PdfReader(path));
  53.             page = srcDoc.getFirstPage().copyAsFormXObject(pdfDoc);
  54.             canvas.addXObject(page, 0, 0);
  55.             srcDoc.close();
  56.         }
  57.         pdfDoc.close();
  58.     }
  59. }
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