iText pdf library
Website search

How to convert PdfStamper to a byte array?

In my application, I need to read the existing PDF and add barcodes to this PDF and pass it to output stream. Here the existing pdf is like a template. I am using iText jar for adding barcode.

I want to know the possibilities of converting PdfStamper object to byte array or PdfContentByte to byte array. Can anyone help on this?

Posted on StackOverflow on Oct 27, 2014 by user1636102

I assume that you want to write to a ByteArrayOutputStream instead of to a FileOutputStream. There are different examples on how to do that on the iText web site.

See for instance the FormServlet example where it says:

// We create an OutputStream for the new PDF
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Now we create the PDF
PdfStamper stamper = new PdfStamper(reader, baos);

Then later in the example, we do this:

// We write the PDF bytes to the OutputStream
OutputStream os = response.getOutputStream();

If you want a byte[], you can simply do this:

byte[] pdfBytes = baos.toByteArray();

I hope your question wasn't about writing a PdfContentByte stream to a byte[] because that wouldn't make sense: a content stream doesn't contain any resources such as fonts, images, form XObjects, etc...

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

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