I have two PDF files, each one in a ByteArrayOutputStream. I want to merge the two PDFs, and I want to use iText, but I don't understand how to do this because it seems that I need an InputStream (and I only have ByteArrayOutputStreams).


Posted on StackOverflow on Jan 13, 2014 by 3vi

The ByteArrayOutputStream object has a toByteArray() method that returns a byte[] which can be used in the InputStream constructor. In iText 7 the PdfReader class has a constructor that takes an InputStream as parameter.

PdfReader reader = new PdfReader(new ByteArrayInputStream(baos.toByteArray()));

Once you have a PdfReader instance of both files, you can create PdfDocument objects and use copyPagesTo() method.

PdfDocument pdfDoc = new PdfDocument(reader);
pdfDoc.copyPagesTo(1, pdfDoc.getNumberOfPages(), pdfDocResult);

The last parameter is the resulting PDF (PdfDocument instance).

Have a look at the Concatenate example for inspiration.

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