How to superimpose pages from existing documents into another document?

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);
However, I always get the following error:

Exception in thread "main" 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 =
public static final String[] EXTRA = {
public static final String SRC =
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);

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.

Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial

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