3

PDFファイルをブラウザで表示したい。私はJSでPDFへのパスを持っており、JavaからサーブレットとしてPDFを取得するための呼び出しを行っています。これが私がこれまでに持っているものです:

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>');

<object>Web ブラウザーは、指定された URL に適切な HTTP 要求を送信し、Adobe Acrobat Reader プラグインを使用して要素を初期化/レンダリングすることに注意を払い<a href="pdfURL">PDF</a>ます<object>。ダウンロードリンク。


具体的な質問とは関係ありませんが、Java コードはサーブレットの一部ではなく、Spring MVC アクションです。条件を明確にして、サーブレットの 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 に答える