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

小编典典

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

servlet响应ExternalContext#getResponse()。然后,您至少需要将HTTP

Content-Type标头设置为application/pdf,并将HTTP Content-

Disposition标头设置为attachment(当您要弹出 另存为 对话框时)或将HTTP

标头设置为(当您想让inlineWeb浏览器处理显示本身时)。最后,您需要确保FacesContext#responseComplete()稍后再打电话以避免IllegalStateExceptions飞来飞去。

开球示例:

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方法即可。

2020-09-16

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值