3

我想在浏览器中显示 PDF 文件。我在 JS 中有 pdf 的路径,我正在调用从 java 中获取 PDF 作为 servlet。这是我到目前为止所拥有的:

JavaScript:

RequestManager.getJSON(Config.server + "getPDF.json?pdfPath=" + this.pathToPdfFile, (function(data){
        $("#" + this.divId).append('<object id="' + this.pdfObjectId + '" data="' + data + '" type="application/pdf" width="600" height="800"></object>');
        ResizeManager.addResizeHandler(this.pdfObjectId, this.divId, -10, -10);
    }).bind(this));

爪哇:

@RequestMapping("/getPDF")
public void pdfPathToServlet(Model model, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    String pdfPath = request.getParameter("pdfPath");
    if (pdfPath == null || pdfPath.equals(""))
        throw new ServletException("Invalid or non-existent file parameter in UrlServlet servlet.");

    if (pdfPath.indexOf(".pdf") == -1)
        pdfPath += ".pdf";

    File pdf = new File(pdfPath);
    String pdfName = pdfPath.substring(pdfPath.lastIndexOf("/") + 1, pdfPath.length());
    logger.debug(pdfName);
    ServletOutputStream stream = null;
    BufferedInputStream buf = null;
    try 
    {
        stream = response.getOutputStream();
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "inline; filename='" + pdfName + "'");
        FileInputStream input = new FileInputStream(pdf);
        response.setContentLength((int) pdf.length());
        buf = new BufferedInputStream(input);
        int readBytes = 0;
        while ((readBytes = buf.read()) != -1)
            stream.write(readBytes);
    } 
    catch (IOException ioe) 
    {
        throw new ServletException(ioe.getMessage());
    } 
    finally 
    {
        if (stream != null)
            stream.close();
        if (buf != null)
            buf.close();
    }
}

我的问题是这将我的浏览器中的二进制输出显示为文本。

我不确定我做错了什么。我尝试将标题更改为附件而不是内联,但这显示了同样的事情。我相信我想要内联,因为我希望在浏览器中显示它而不是下载它。

4

3 回答 3

5

您的 JavaScript 部分没有意义。您正在获取 PDF 文件作为 ajax 响应,然后尝试将其设置为元素的data属性。<object>data属性必须指向一个真实的 URL,而不是文件内容。相应地修复您的 JS:

$("#" + this.divId).append('<object id="' + this.pdfObjectId + '" data="' + Config.server + "getPDF.json?pdfPath=" + this.pathToPdfFile + '" type="application/pdf" width="600" height="800"></object>');

网络浏览器将负责在给定的 URL 上发送适当的 HTTP 请求,并使用 Adob​​e Acrobat Reader 插件初始化/呈现元素——<object>如果有的话,我宁愿将下载链接。<a href="pdfURL">PDF</a><object>


与具体问题无关,Java 代码根本不是 servlet 的一部分,而是 Spring MVC 操作。我建议您直接阅读我们的 Servlets wiki 页面以了解它们的真正含义。

于 2013-01-07T20:38:49.943 回答
0
response.setHeader("Content-Disposition", "attachment;filename=" + pdfName);
于 2013-01-07T19:51:13.687 回答
-1
 response.setHeader("Content-Disposition", "inline; filename='" + pdfName + "'");

您不能显示 PDF 内联。它需要单独在自己的页面(或 Iframe)上。

于 2013-01-07T19:50:27.590 回答