How to superimpose pages from existing documents into another document?
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(); }
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:
-
You close the
stamper
inside the loop. Once thestamper
is closed, it is closed: you can't add any more content to it. You need to movestamper.close()
outside the loop. -
You close the
reader
inside the loop, butstamper
hasn't released thereader
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.