Reputation: 976
I am creating a system that dynamically creates a PDF using iText for Java from within a servlet using a ByteArrayOutputStream, and PdfWriter, to prevent filesystem usage.
I would like to be able to append some existing PDF file pages to the end of the dynamically created PDF once the dynamic content is complete.
I've looked at the example code to concatenate PDFs using iText, and they use PdfCopy to accomplish this. The big assumption for PdfCopy is that all files being concatenated exist on the file system.
Is it possible to concatenate the existing files to the end of the in memory PDF, that exists as a ByteArrayOutputStream?
In the meantime, I have used a temporary file for the initial dynamic document, but would like to remove that dependency if possible.
Thanks,
Allen
Upvotes: 3
Views: 3333
Reputation: 31649
Having a list of InputStream
(different documents) you can append them in an OutputStream
in this way (based in this):
private void doMerge(List<InputStream> list, OutputStream outputStream)
throws DocumentException, IOException {
Document document = new Document();
PdfCopy copy = new PdfCopy(document, outputStream);
document.open();
int n;
for (InputStream in : list) {
PdfReader reader = new PdfReader(in);
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
n = reader.getNumberOfPages();
// loop over the pages in that document
for (int page = 0; page < n; ) {
copy.addPage(copy.getImportedPage(reader, ++page));
}
copy.freeReader(reader);
reader.close();
}
}
outputStream.flush();
document.close();
outputStream.close();
}
Upvotes: 1
Reputation: 77528
You are assuming that you can only create a PdfReader
instance using a path to a file. This assumption is wrong. See the API documentation. If baos
is your ByteArrayOutputStream
, you could easily create your reader instance like this:
PdfReader reader = new PdfReader(baos.toByteArray());
Upvotes: 4