Tuesday, 7 May 2013

How to download PDF file with JSF? | JSF Interview Questions

This is an code example how it can be done with action listener of the backing bean.
Add the following method to the backing bean:
public void viewPdf(ActionEvent event) {
String filename = "filename.pdf";
// use your own method that reads file to the byte array
byte[] pdf = getTheContentOfTheFile(filename);
FacesContext faces = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) faces.getExternalContext().response.setContentType("application/pdf");
response.setContentLength(pdf.length);
response.setHeader( "Content-disposition", "inline; filename=\""+fileName+"\"");
try {
ServletOutputStream out;
out = response.getOutputStream();
out.write(pdf);
} catch (IOException e) {
e.printStackTrace();
}
faces.responseComplete();
}

This is a jsp file snippet:
<h:commandButton immediate="true" actionListener="#{backingBean.viewPdf}" value="Read


No comments: