Approach 1: Use
Take a look at the AddCover1 example:
PdfReader cover = new PdfReader("hero.pdf"); PdfReader reader = new PdfReader("pages.pdf"); Document document = new Document(); PdfCopy copy = new PdfCopy(document, new FileOutputStream("pages_with_cover.pdf")); document.open(); copy.addDocument(cover); copy.addDocument(reader); document.close(); cover.close(); reader.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
Take a look at the AddCover2 example:
PdfReader cover = new PdfReader("hero.pdf"); PdfReader reader = new PdfReader("pages.pdf"); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("cover_with_pages.pdf")); stamper.insertPage(1, cover.getPageSizeWithRotation(1)); PdfContentByte page1 = stamper.getOverContent(1); PdfImportedPage page = stamper.getImportedPage(cover, 1); page1.addTemplate(page, 0, 0); stamper.close(); cover.close(); reader.close();
In this case, we take the original document
pages.pdf and we insert a new page 1
with the same page size as the cover. We then get this
page1 and we add the first page of
to this first page. The result is cover_with_pages.pdf
What is the difference between the two approaches?
PdfCopy, you may lose some of the properties that are defined at the document level
(e.g. the page layout setting), but you keep the interactive features of both files.
You may need to set some parameters in case you want to preserve tagging, form fields, etc...
but for simple PDFs, you don't need all of that.
PdfStamper, you preserve the properties that are defined at the document level of
but you lose all the interactive features of the cover page (if any).
You may need to tweak the example if you want to define the cover as an artifact and if the original cover page
has odd page boundaries, but it would lead us too far to discuss this in this simple answer.