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

如何在Java Web应用程序中将byte []作为pdf发送到浏览器?,第1张

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

在action方法中,您可以通过JSF幕后获得HTTP
servlet响应

ExternalContext#getResponse()
。然后,您至少需要将HTTP
Content-Type
标头设置为
application/pdf
,并将HTTP
Content-Disposition
标头设置为
attachment
(当您要d出 另存为 对话框时)或将HTTP
标头设置为(当您想让
inline
Web浏览器处理显示本身时)。最后,您需要确保
FacesContext#responseComplete()
稍后再打电话以避免
IllegalStateException
s飞来飞去。


开球示例:

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[]
,我建议您使用它代替从内存中保存webapp。然后,您只需以众所周知的方式编写它
InputStream
-
OutputStream
循环使用通常的Java IO方法即可。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5478815.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存