How to merge PDFs from ByteArayOutputStreams?

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.

Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now