How to superimpose pages from existing documents into another document?

Tags: PdfStamperinsert pagesuperimposefree readerPdfReaderiText 5

I need to add existing pages from different PDFs under an existing page in another PDF. This is the code I have so far:

PdfReader reader = new PdfReader(SRC);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(DEST));
PdfContentByte canvas = stamper.getUnderContent(1);
PdfReader r;
PdfImportedPage page;
for (String path : EXTRA) {
    r = new PdfReader(path);
    page = stamper.getImportedPage(r, 1);
    canvas.addTemplate(page, 0, 0);
    stamper.close();
    r.close();
}
However, I always get the following error:

Exception in thread "main" java.io.IOException: RandomAccessSource not opened

How can I solve this problem?

Posted on StackOverflow on Nov 7, 2015 by Nitesh Virani

I see two problems in your code:

  1. You close the stamper inside the loop. Once the stamper is closed, it is closed: you can't add any more content to it. You need to move stamper.close() outside the loop.

  2. You close the reader inside the loop, but stamper hasn't released the reader yet. You should free the reader first.

Please take a look at the SuperImpose example:

public static final String SRC = "resources/pdfs/primes.pdf";
public static final String[] EXTRA =
    {"resources/pdfs/hello.pdf", "resources/pdfs/base_url.pdf", "resources/pdfs/state.pdf"};
public static final String DEST = "results/stamper/primes_superimpose.pdf";

PdfReader reader = new PdfReader(SRC);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(DEST));
PdfContentByte canvas = stamper.getUnderContent(1);
PdfReader r;
PdfImportedPage page;
for (String path : EXTRA) {
    r = new PdfReader(path);
    page = stamper.getImportedPage(r, 1);
    canvas.addTemplate(page, 0, 0);
    stamper.getWriter().freeReader(r);
    r.close();
}
stamper.close();

In this case, I always add the imported pages to page 1 of the main document. If you want to add the imported pages to different pages, you need to create the canvas object inside the loop.