How to superimpose pages from existing documents into another document?

Tags: insert pagesuperimposeiText 7The best questions on stack overflow

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

Please take a look at the SuperImpose example. In iText 7 your code should look like this:

public static final String DEST =
        "./target/test/resources/sandbox/stamper/super_impose.pdf";
public static final String[] EXTRA = {
        "./src/test/resources/pdfs/hello.pdf",
        "./src/test/resources/pdfs/base_url.pdf",
        "./src/test/resources/pdfs/state.pdf"
};
public static final String SRC =
        "./src/test/resources/pdfs/primes.pdf";
public void manipulatePdf(String src, String[] extra, String dest) throws IOException {
    PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
    PdfDocument srcDoc;
    PdfFormXObject page;
    PdfCanvas canvas = new PdfCanvas(pdfDoc.getFirstPage().newContentStreamBefore(),
            pdfDoc.getFirstPage().getResources(), pdfDoc);
    for (String path : extra) {
        srcDoc = new PdfDocument(new PdfReader(path));
        page = srcDoc.getFirstPage().copyAsFormXObject(pdfDoc);
        canvas.addXObject(page, 0, 0);
        srcDoc.close();
    }
    pdfDoc.close();
}

Take a note that there are no PdfContentByte and PdfImportedPage classes anymore. We use PdfCanvas to get the content stream and PdfFormXObject to extract a page using copyAsFormXObject() method. I always add new pages to page 1 of the main document. If you want to add them to different pages, you need to create the canvas object inside the loop.

Click this link if you want to see how to answer this question in iText 5.