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 ?
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 ?
When sending raw data to the browser using JSF, you need to extract the
HttpServletResponse
from theFacesContext
.Using the
HttpServletResponse
, you can send raw data to the browser using the standard IO API.Here is a code sample:
Also, here are some other things you might want to consider:
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 HTTPContent-Type
header toapplication/pdf
and the HTTPContent-Disposition
header toattachment
(when you want to pop a Save As dialogue) or toinline
(when you want to let the webbrowser handle the display itself). Finally, you need to ensure that you callFacesContext#responseComplete()
afterwards to avoidIllegalStateException
s flying around.Kickoff example:
That said, if you have the possibility to get the PDF content as an
InputStream
rather than abyte[]
, I would recommend to use that instead to save the webapp from memory hogs. You then just write it in the well-knownInputStream
-OutputStream
loop the usual Java IO way.You just have to set the mime type to
application/x-pdf
into your response. You can use the setContentType(String contentType) method to do this in the servlet case.In JSF/JSP you could use this, before writing your response:
and
response.write(yourPDFDataAsBytes());
to write your data.But I really advise you to use servlets in this case. JSF is used to render HTML views, not PDF or binary files.
With servlets you can use this :
Resources :