如何在java web应用程序中将byte []作为pdf发送到浏览器?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (94)

在行动方法(JSF)我有如下所示:

public String getFile() {
  byte[] pdfData = ...
  // how to return byte[] as file to web browser user ?
}

如何将pdf发送给浏览器?

提问于
用户回答回答于

在action方法中,您可以从JSF引擎中获取HTTP servlet响应ExternalContext#getResponse()。然后,您需要至少设置HTTP Content-Type标头application/pdf和HTTP Content-Disposition标头attachment(当您想弹出另存为对话框时)或inline(当您想让webbrowser自己处理显示时)。最后,你需要确保你打电话FacesContext#responseComplete()后避免IllegalStateException飞来飞去。

示例:

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

也就是说,如果您有可能将PDF内容作为一个InputStream而不是一个byte[],我建议使用它来保存内存中的web应用程序。然后你只是把它写在著名的InputStream- OutputStream环通常的Java IO方式。

用户回答回答于

您只需将MIME类型设置application/x-pdf为您的回复。您可以使用setContentType(String contentType)方法在servlet案例中执行此操作。 在编写响应之前,您可以在JSF / JSP中使用它:

<%@ page contentType="application/x-pdf" %>

response.write(yourPDFDataAsBytes());编写你的数据。 但我真的建议你在这种情况下使用servlets。JSF用于呈现HTML视图,而不是PDF或二进制文件。

有了servlet,你可以使用这个:

public MyPdfServlet extends HttpServlet {
    protected doGet(HttpServletRequest req, HttpServletResponse resp){
         OutputStream os = resp.getOutputStream();
         resp.setContentType("Application/x-pdf");
         os.write(yourMethodToGetPdfAsByteArray());
    } 
}

资源:

扫码关注云+社区