In action method (JSF) i have something like below:
public String getFile() {
byte[] pdfData = ...
// how to return byte[] as file to web browser user ?
}
How to send byte[] as pdf to browser ?
Convert byte[] array to File using Java In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file.
Arrays. fill(). This method assigns the required byte value to the byte array in Java. The two parameters required for java.
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 IllegalStateException
s 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 InputStream
-OutputStream
loop the usual Java IO way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With