I have two methods. One that generates a PDF at the server side and another that downloads the PDF at the client side.
How can i do this without storing it in the Server side and allow the client side to directly download this.
The Following are the two methods:
public void downloadPDF(HttpServletRequest request, HttpServletResponse response) throws IOException{
response.setContentType("application/pdf");
response.setHeader("Content-disposition","attachment;filename="+ "testPDF.pdf");
FileInputStream fis = null;
DataOutputStream os = null;
try {
File f = new File("C://New folder//itext3.pdf");
response.setHeader("Content-Length",String.valueOf(f.length()));
fis = new FileInputStream(f);
os = new DataOutputStream(response.getOutputStream());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) >= 0) {
os.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
fis.close();
os.flush();
os.close();
}
response.setHeader("X-Frame-Options", "SAMEORIGIN");
}
And:
public Document generatePDF() {
Document doc = new Document();
try {
File file = new File("C://New folder//itext_Test2.pdf");
FileOutputStream pdfFileout = new FileOutputStream(file);
PdfWriter.getInstance(doc, pdfFileout);
doc.addAuthor("TestABC");
doc.addTitle("Aircraft Details");
doc.open();
Anchor anchor = new Anchor("Aircraft Report");
anchor.setName("Aircraft Report");
Chapter catPart = new Chapter(new Paragraph(anchor), 1);
Paragraph para1 = new Paragraph();
Section subCatPart = catPart.addSection(para1);
para1.add("This is paragraph 1");
Paragraph para2 = new Paragraph();
para2.add("This is paragraph 2");
doc.add(catPart);
doc.close();
} catch (Exception e) {
e.printStackTrace();
}
return doc;
}
You are creating a FileOutputStream to generate pdf. But what you can do is to use the stream that is present in HttpServletResponse on server side method and write the file directly to it.
You can receive an
OutputStream
in yourgeneratePDF
method. If you pass theresponse.getOutputStream()
to the generate method then the PDF will be written to the response directly.Just call this method appropriately from
downloadPDF()
; e.g.:that calls this method:
The people who advise you to use
response.getOutputStream()
instead of creating aFileOutputStream
are right. See for instance the Hello Servlet from Chapter 9 of my book: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/