Reputation: 164
Using iText 5.5.5.
I have an open com.itextpdf.text.Document
through a PdfWriter
instance. At various points during construction of the document, I need to add in static PDF pages. The static pages are coming in the form of a byte[]
.
After following various examples on itextpdf.com, I am unable to mesh their examples with my use case. Here is the code:
Document trunk = new Document();
PdfWriter writer = PdfWriter.getInstance(trunk, getTrunkStream());
writer.setPageEvent(geTrunkPageEvent());
trunk.open();
....
PdfReader reader = new PdfReader(bytes);
// graft == my static content
Document graft = new Document(reader.getPageSizeWithRotation(1));
PdfCopy copy = new PdfCopy(graft, getTrunkStream());
graft.open();
int count = reader.getNumberOfPages();
for(int page = 0; page < count;) {
copy.addPage(copy.getImportedPage(reader, ++page));
}
copy.freeReader(reader);
reader.close();
The code compiles and runs error free. But the graft pages fail to appear with the trunk pages.
Upvotes: 2
Views: 2718
Reputation: 9915
Read the answer to this question Read BLOB (PDF Content) from database and edit and output PDF , for more detailed description
Use PdfContentByte
to hold the PDF content to be added
PdfContentByte cb = writer.getDirectContent();
Create a PdfImportedPage
page object for each page you want to import from another document using getImportedPage()
and add the page using to writer
using addTemplate()
:
trunk.newPage();
page = writer.getImportedPage(pdfReader, pagenumber);
cb.addTemplate(page, 0, 0);
Make sure to close the document
and the pdfReader
.
Note: do not use this code snippet if you merely want to merge a bunch of files. The reason why you shouldn't do this, is explained in the answer to the question How to merge documents correctly?
Upvotes: 3