簡體   English   中英

使用servlet在瀏覽器中顯示PDF

[英]Display PDF in browser with a servlet

我想在瀏覽器中顯示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));

Java的:

@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();
    }
}

我的問題是,這是在我的瀏覽器中顯示文本的二進制輸出

我不確定我做錯了什么。 我已經嘗試將標題更改為附件而不是內聯,但這顯示了同樣的事情。 我相信我想要內聯,因為我希望在瀏覽器中顯示它而不是下載它。

你的JavaScript部分毫無意義。 您將獲取PDF文件作為ajax響應,然后嘗試將其設置為<object>元素的data屬性。 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>');

webbrowser將負責在給定的URL上發送適當的HTTP請求並使用Adobe Acrobat Reader插件初始化/呈現<object>元素 - 如果有的話,我寧願附上<a href="pdfURL">PDF</a><object>以便下載鏈接至少有一個優雅的降級。


具體問題無關 ,Java代碼根本不是servlet的一部分,而是Spring MVC動作。 我建議您直接了解您的術語並閱讀我們的Servlets維基頁面,以了解它們的真實含義。

response.setHeader("Content-Disposition", "attachment;filename=" + pdfName);
 response.setHeader("Content-Disposition", "inline; filename='" + pdfName + "'");

您無法在線顯示PDF。 它需要獨自在自己的頁面(或Iframe)上。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM