How to add a cover page to an existing PDF document?

Tags: copyPagesToiText 7

I need to add an existing cover page (a single-page PDF) to another existing PDF document. How can this be done?

Posted on StackOverflow on Apr 10, 2015 by Doug LN

Suppose that we have a document named pages.pdf and that we want to add the cover hero.pdf as the cover of this document.

Approach 1: Use PdfMerger

Take a look at the AddCover1 example:

public void manipulatePdf(String cov, String src, String dest) throws IOException {
    PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
    PdfMerger merger = new PdfMerger(pdfDoc);
    PdfDocument cover = new PdfDocument(new PdfReader(cov));
    PdfDocument resource = new PdfDocument(new PdfReader(src));
    merger.merge(cover, 1, 1);
    merger.merge(resource, 1, resource.getNumberOfPages());
    cover.close();
    resource.close();
    pdfDoc.close();
}

The result is a document where you first have the cover and then the rest of the document: pages_with_cover.pdf

Approach 2: Use copyPagesTo()

Take a look at the AddCover2 example:

public void manipulatePdf(String cov, String src, String dest) throws IOException {
    PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
    PdfDocument cover = new PdfDocument(new PdfReader(cov));
    cover.copyPagesTo(1, 1, pdfDoc, 1, new PdfPageFormCopier());
    cover.close();
    pdfDoc.close();
}

In this case, we create a new PdfDocument instance from the source pages.pdf and copy the first page of the hero.pdf to it. As you see, the third parameter in copyPagesTo() method (insertBeforePage) is equal to 1, which means that the cover will be added in the beginning of the document.

With copyPagesTo(), you may lose some of the properties that are defined at the document level (e.g. the page layout setting, tags, outlines), but for simple PDFs, you don't need all of that. In case if you need to preserve these properties, it would be better to use PdfMerger class.

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