How to send byte[] as pdf to browser in java web application?

In the action method you can obtain the HTTP servlet response from under the JSF hoods by ExternalContext#getResponse(). Then you need to set at least the HTTP Content-Type header to application/pdf and the HTTP Content-Disposition header to attachment (when you want to pop a Save As dialogue) or to inline (when you want to let the webbrowser handle the display itself). Finally, you need to ensure that you call FacesContext#responseComplete() afterwards to avoid IllegalStateExceptions flying around.

Kickoff example:

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.
}

That said, if you have the possibility to get the PDF content as an InputStream rather than a byte[], I would recommend to use that instead to save the webapp from memory hogs. You then just write it in the well-known InputStreamOutputStream loop the usual Java IO way.

Leave a Comment