I'm using jdbc to fetch data from database and then using iText I 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.
The problem is that now, I cannot insert an image in this document as it gives me and error that
getOutputStream() has already been called for this response
I understand that I'm calling Outputstream
again while inserting the image and therefore the error
How can I insert an image in the document and still generate a dynamic PDF file which can be downloaded by client machine?
The relevant code:
response.setContentType("application/pdf");
response.setHeader("Content-Disposition","attachment; filename=\"LicenseInfo.pdf\""); // Code 1
Document document = new Document();
PdfWriter.getInstance(document, response.getOutputStream()); // Code 2
Image image = Image.getInstance("logo.jpg");
document.open();
document.add(image);
I'm sorry, but you aren't showing any relevant code, as the code you copy/pasted isn't responsible for the exception you mention.
The relevant part is that you're using JSP, and that you didn't read the important warnings concerning JSP listed in chapter 9 of my book.
When you write JSP, you probably like white space and indentation, for instance:
<% //a line of code %>
<%
// some more code
%>
<% // another line of code %>
<%
response.getOutputStream();
%>
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:
<% //a line of code %><%
// some more code
%><% // another line of code %><%
response.getOutputStream();
%>
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!