Java 将字节数组转换为PDF并在JSP页面中显示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18999134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting byte array to PDF and display in JSP page
提问by abhi
I am doing a JSP site, where I need to display PDF files. I have byte array of PDF file by webservice and I need to display that byte array as PDF file in HTML. My question is how to covert that byte array as PDF and display that PDF in new tab.
我正在做一个 JSP 站点,我需要在其中显示 PDF 文件。我有 webservice 的 PDF 文件字节数组,我需要将该字节数组显示为 HTML 中的 PDF 文件。我的问题是如何将该字节数组转换为 PDF 并在新选项卡中显示该 PDF。
回答by Michael Piefel
Sadly, you do not tell us what technology you use.
遗憾的是,您没有告诉我们您使用的是什么技术。
With Spring MVC, use @ResponseBody
as an annotation for your controller method and simply return the bytes like so:
使用 Spring MVC,@ResponseBody
用作控制器方法的注释并简单地返回字节,如下所示:
@ResponseBody
@RequestMapping(value = "/pdf/shopping-list.pdf", produces = "application/pdf", method=RequestMethod.POST)
public byte[] downloadShoppingListPdf() {
return new byte[0];
}
Opening in a new tab is an unrelated matter that has to be handled in the HTML.
在新选项卡中打开是必须在 HTML 中处理的无关问题。
回答by faisalbhagat
save these bytes on the disk by using output stream.
使用输出流将这些字节保存在磁盘上。
FileOutputStream fos = new FileOutputStream(new File(latest.pdf));
//create an object of BufferedOutputStream
bos = new BufferedOutputStream(fos);
byte[] pdfContent = //your bytes[]
bos.write(pdfContent);
Then send its link to client side to be opened from there. like http://myexamply.com/files/latest.pdf
然后将其链接发送到客户端以从那里打开。像http://myexamply.com/files/latest.pdf
回答by Manuel Manhart
better is to use a servlet for this, since you do not want to present some html, but you want to stream an byte[]:
更好的是为此使用 servlet,因为您不想呈现一些 html,但您想流式传输一个字节 []:
public class PdfStreamingServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(final HttpServletRequest request,
final HttpServletResponse response) throws ServletException,
IOException {
processRequest(request, response);
}
public void processRequest(final HttpServletRequest request,
final HttpServletResponse response) throws ServletException,
IOException {
// fetch pdf
byte[] pdf = new byte[] {}; // Load PDF byte[] into here
if (pdf != null) {
String contentType = "application/pdf";
byte[] ba1 = new byte[1024];
String fileName = "pdffile.pdf";
// set pdf content
response.setContentType("application/pdf");
// if you want to download instead of opening inline
// response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
// write the content to the output stream
BufferedOutputStream fos1 = new BufferedOutputStream(
response.getOutputStream());
fos1.write(ba1);
fos1.flush();
fos1.close();
}
}
}