Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In the action method you can obtain the HTTP servlet response from under the JSF hoods by <a href="http://java.sun.com/javaee/5/docs/api/javax/faces/context/ExternalContext.html#getResponse%28%29" rel="noreferrer"><code>ExternalContext#getResponse()</code></a>. Then you need to set at least the HTTP <code>Content-Type</code> header to <code>application/pdf</code> and the HTTP <code>Content-Disposition</code> header to <code>attachment</code> (when you want to pop a <em>Save As</em> dialogue) or to <code>inline</code> (when you want to let the webbrowser handle the display itself). Finally, you need to ensure that you call <a href="http://java.sun.com/javaee/5/docs/api/javax/faces/context/FacesContext.html#responseComplete()" rel="noreferrer"><code>FacesContext#responseComplete()</code></a> afterwards to avoid <code>IllegalStateException</code>s flying around.</p> <p>Kickoff example:</p> <pre><code>public void download() throws IOException { // Prepare. byte[] pdfData = getItSomehow(); FacesContext facesContext = FacesContext.getCurrentInstance(); ExternalContext externalContext = facesContext.getExternalContext(); HttpServletResponse response = (HttpServletResponse) externalContext.getResponse(); // Initialize response. response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide. response.setContentType("application/pdf"); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename. response.setHeader("Content-disposition", "attachment; filename=\"name.pdf\""); // The Save As popup magic is done here. You can give it any filename you want, this only won't work in MSIE, it will use current request URL as filename instead. // Write file to response. OutputStream output = response.getOutputStream(); output.write(pdfData); output.close(); // Inform JSF to not take the response in hands. facesContext.responseComplete(); // Important! Else JSF will attempt to render the response which obviously will fail since it's already written with a file and closed. } </code></pre> <p>That said, if you have the possibility to get the PDF content as an <code>InputStream</code> rather than a <code>byte[]</code>, I would recommend to use that instead to save the webapp from memory hogs. You then just write it in the well-known <code>InputStream</code>-<code>OutputStream</code> loop the usual Java IO way.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload