问题
I have a bean with the raw bytes of a PDF that is generated at the user's request. I want to display this PDF to the user without really persisting the PDF file on my server.
In my jsp I have tried tags like
<object data="#{bean.pdfBytes}" type="application/pdf" ></object>
<object type="application/pdf" width="600" height="400">
<h:outputFormat value="#{bean.pdfBytes}" escape="false"/>
</object>
but this fails terribly. Any help would be appreciated. Thanks in advance.
回答1:
I want to display this PDF to the user without really persisting the PDF file on my server.
Write it to the output stream of the response. Let's assume that you're using iText to generate the PDF, pass the response's output stream to PdfWrter#getInstance().
public void download() throws IOException {
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "inline; filename=\"" + filename + "\"");
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
document.open();
// Build document.
context.responseComplete();
}
This will however display the PDF in its entirety in the browser. If you want a Save As dialogue, just change the inline part in the header to attachment. Or if you really want to have it embedded in an <object>, then you'd need to create a servlet and do the above response job inside the doGet() method and finally let <object>'s URL point to that servlet.
来源:https://stackoverflow.com/questions/9437234/embed-raw-bytes-as-a-pdf-in-jsp