4

我正在做一个 JSP 站点,我需要在其中显示 PDF 文件。我有 webservice 的 PDF 文件的字节数组,我需要将该字节数组显示为 HTML 中的 PDF 文件。我的问题是如何将该字节数组转换为 PDF 并在新选项卡中显示该 PDF。

4

3 回答 3

3

使用输出流将这些字节保存在磁盘上。

FileOutputStream fos = new FileOutputStream(new File(latest.pdf));

//create an object of BufferedOutputStream
bos = new BufferedOutputStream(fos);

byte[] pdfContent = //your bytes[]

bos.write(pdfContent);

然后将其链接发送到客户端以从那里打开。像http://myexamply.com/files/latest.pdf

于 2013-09-25T08:03:06.730 回答
3

更好的是为此使用 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();
        }
    }
}
于 2013-09-25T08:08:17.090 回答
1

可悲的是,您没有告诉我们您使用的是什么技术。

使用 Spring MVC,将@ResponseBody其用作控制器方法的注释并简单地返回字节,如下所示:

@ResponseBody
@RequestMapping(value = "/pdf/shopping-list.pdf", produces = "application/pdf", method=RequestMethod.POST)
public byte[] downloadShoppingListPdf() {
    return new byte[0];
}

在新选项卡中打开是一个无关的事情,必须在 HTML 中处理。

于 2013-09-25T07:55:01.820 回答