Skip to main content
Skip table of contents

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 How to superimpose pages from existing documents into another document? if you want to see how to answer this question in iText 5.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.