【问题标题】:Display Pdf in browser using java servlet使用 java servlet 在浏览器中显示 Pdf
【发布时间】:2017-07-13 11:14:08
【问题描述】:

我的应用程序中有 pdf 文件。我需要在浏览器中显示 pdf。我正在将文件作为 fileInputStream 读取,我需要在我的应用程序中的浏览器中显示 pdf。但是我没有pdf路径,我有文件流。

请给我一些建议和例子


我使用 ajax 来显示 pdf,我使用 call_method() javascript ajax 请求方法来调用 showPdf 动作,在 showpdf 动作中只是将 pdf 文件转换为 ByteArrayOutputStream 并将结果写入输出流。但它显示了下面提到的结果。

JSP 中的结果

%PDF-1.4 %��� 1 endstream endobj 4 0 obj >>/MediaBox[0 0 595 842]>> endobj 1 0 obj endobj 3 0 obj endobj 5 0 obj endobj 6 0 OBJ endobj外部参照0 7 0000000000 65535˚F0000000389 00000ñ0000000015 00000ñ0000000477 00000ñ0000000232 00000ñ0000000540 00000ñ0000000585 00000ñ拖车] /信息6 0 R /大小7 >> startxref 707 %% EOF

请给点建议。

Javascript ajax:

call_method(); <br/>
function call_method(){

    Ext.Ajax.request({
            waitMsg: 'Saving changes...',
            url:'test.action?method=showPdf',
            params : { },       
            failure:function(response,options){

            },
            success:function(response,options){
                $("#pdf_content").show();               
                $("#pdf_content").html(response.responseText);
                $("#pdf_content").show('slow');
            }
    });
}

Java 方法:

public String showPdf() throws IOException {

    getResponse().setContentType("application/pdf");

    getResponse().setHeader("Content-disposition","inline; filename=automatic_start.pdf" );


    ByteArrayOutputStream baos = getByteArrayOutputStream();

    getResponse().setContentLength(baos.size());

    ServletOutputStream sos;

    sos = getResponse().getOutputStream();

    baos.writeTo(sos);

    sos.flush();

    return null;
}


private ByteArrayOutputStream getByteArrayOutputStream() throws IOException {

    String filePath = "/homefolder/";

    String folderPath=filePath+"1122/automatic_start.pdf";

    File file = new File(folderPath);

    FileInputStream fis = new FileInputStream(file);



    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] buf = new byte[256];
     try {
            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                bos.write(buf, 0, readNum); //no doubt here is 0
                //Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
                System.out.println("read " + readNum + " bytes,");
            }

        } catch (IOException ex) {
            ex.printStackTrace();
        }


    return bos;
}

【问题讨论】:

  • 我有同样的问题,但没有得到解决方案。请帮帮我。我应该在 jsp 页面中更改什么。需要帮助。!!
  • 我有同样的问题......但对我来说这是因为我没有包含 response.setHeader("Content-disposition","inline; filename=automatic_start.pdf" );由于我没有要下载的实际文件名(因为 pdf 由“内存中”提供),所以我认为我不需要在那里有文件名。 IE 似乎需要它,否则它会显示您在浏览器中提到“%PDF-1.4 % ...”的胡言乱语。加上它很有用,所以如果它是内联的,并且用户决定保存,我相信它默认为该名称。 PS 也可以使用“attachment; ...”而不是“inline; ...”。

标签: java jsp pdf servlets mime-types


【解决方案1】:

在您的 servlet 中,将 MIME 类型设置为 PDF 的正确类型:application/pdf

http://www.iana.org/assignments/media-types/

【讨论】:

    【解决方案2】:

    您必须将您的InputStream 写到您的回复OutputStream,如下所示:

    • 您的Content-Disposition 必须是inline
    • 您的Content-Type 必须是application/pdf
    • 您的Content-Length 将是InputStream 中总数据的长度(以字节为单位)。

    设置后,将输入流数据写入响应的输出流。

    这种效果的东西:

    /* (non-Javadoc)
     * @see org.bfs.bayweb.util.renderer.ServletViewRenderer#render(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
     */
    public void render(ServletRequest request, ServletResponse response) throws IOException {
        // TODO Auto-generated method stub
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
            int inputStreamLength = 0;
            int length = 0;
            while ((length = getInputStream().read(buffer)) > 0) {
                inputStreamLength += length;
                baos.write(buffer, 0, length);
            }
    
            if (inputStreamLength > getContentLength()) {
                setContentLength(inputStreamLength);
            }
    
            if (response instanceof HttpServletResponse) {
                HttpServletResponse httpResponse = (HttpServletResponse) response;
                httpResponse.reset();
                httpResponse.setHeader("Content-Type", getContentType());
                httpResponse.setHeader("Content-Length", String.valueOf(getContentLength()));
                httpResponse.setHeader("Content-Disposition", "\"" + getContentDisposition() + "\"" + ((getFileName() != null && !getFileName().isEmpty()) ? "; filename=\"" + getFileName() + "\"": ""));
            }
    
            response.getOutputStream().write(baos.toByteArray(), 0, (int)getContentLength());
    
            //finally
            response.getOutputStream().flush();
    
            //clear
            baos = null;
        } finally {
            // TODO Auto-generated catch block
            close(response.getOutputStream());
            close(getInputStream());
        }
    }
    
    private void close(Closeable resource) throws IOException {
        if (resource != null) {
            resource.close();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-28
      • 1970-01-01
      • 2014-08-03
      • 1970-01-01
      • 2023-02-23
      • 2014-06-18
      • 1970-01-01
      相关资源
      最近更新 更多