Why do I get a "getOutputStream() has already been called for this response" error in JSP?

I'm using JDBC to fetch data from database and then I use iText to create a PDF file which can be downloaded on client machine. The application is coded in HTML/JSP and runs on Apache Tomcat.

I use the response.getOutputStream to create an output PDF file immediately. However, I get the following error:

getOutputStream() has already been called for this response

How can I generate a dynamic PDF file which can be downloaded by client machine?

Posted on StackOverflow on Jun 13, 2013 by Sahil Sharma

When you write JSP, you probably like white space and indentation, for instance:

This will always cause the exception "getOutputStream() has already been called for this response" regardless if you're using iText or not. The getOutputStream() method was called the moment you introduced your first white space character in your JSP script.

To fix this, you need to remove all white space:

Not a single character is accepted outside the and %> markers. As explained in the better JSP manuals, you shouldn't use JSP to create binary files. Why not? Because JSP introduces white space characters at arbitrary places in your binary file. That results in corrupt files. Use Servlets instead!

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