Embed raw bytes as a PDF in JSP

丶灬走出姿态 提交于 2019-12-23 04:35:18

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!