This question already has an answer here:
I use iText/Pdfbox to create a PDF document. Everything works when I create the PDF using a standalone Java class like this:
public static void main(String[] args){
...
...
...
}
The document is created correctly.
But I need create a PDF document from a Servlet. I paste the code into the get or post method, run that servlet on the server, but the PDF document isn't created!
This code works as a standalone application:
This code doesn't work:
Please read the documentation. For instance the answer to the question How can I serve a PDF to a browser without storing a file on the server side?
You are currently creating a file on your file system. You aren't using the
response
object, meaning you aren't sending any bytes to the browser. This explains why nothing happens in the browser.This is a simple example:
However, some browsers experience problems when you send bytes directly like this. It's safer to create the file in memory using a
ByteArrayOutputStream
and to tell the browser how many bytes it can expect in the content header:For the full source code, see PdfServlet. You can try the code here: http://demo.itextsupport.com/book/
You wrote in a comment
This question could be interpreted in two different ways:
response.setHeader("Content-disposition","attachment;filename="+ "testPDF.pdf");
You can set theContent-disposition
toinline
if you want the PDF to open in the browser, but in the question, theContent-disposition
is set toattachment
which triggers a dialog box to open.See also How to show a Save As dialog for a iText generated PDF?