I'm trying to send a PDF to browser throught a JSF response, a very simple document, see:
public void gerarPDF() throws IOException{
try {
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
// step 1
Document document = new Document();
// step 2
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baos);
// step 3
document.open();
// step 4
document.add(new Paragraph("HELLO WORLD"));
document.add(new Paragraph("ANOTHER LINE"));
// step 5
document.close();
response.addHeader("Content-Type", "application/force-download");
response.addHeader("Content-Disposition", "attachment; filename=report.pdf");
response.setContentLength(baos.size());
response.getOutputStream().write(baos.toByteArray());
response.getOutputStream().flush();
baos.flush();
baos.close();
FacesContext.getCurrentInstance().responseComplete();
}
catch(DocumentException e) {
throw new IOException(e.getMessage());
}
}
This method is called from a commandButton, the problem browser shows that:
%PDF-1.4 %2 0 obj <>stream x+S00SI
If i change my code to save in a file, everything works fine, see:
FileOutputStream fos = new FileOutputStream("C:\\"+UUID.randomUUID().toString()+".pdf");
fos.write(baos.toByteArray());
fos.close();
But i need show the PDF in browser. Someone can helpe me ?