使用java servlet在浏览器中显示Pdf

发布于 2024-12-04 06:26:05 字数 2652 浏览 1 评论 0 原文

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

请给我一些建议和示例


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

JSP 中的结果

%PDF-1.4 %��� 1 endstream endobj 4 0 obj <>>>/MediaBox[0 0 595 842]>> endobj 1 0 obj <> endobj 3 0 对象 <> endobj 5 0 obj <> endobj 6 0 obj <> endobj 外部参照 0 7 0000000000 65535 f 0000000389 00000 n 0000000015 00000 n 0000000477 00000 n 0000000232 00000 n 0000000540 00000 n 0000000585 00000 n 拖车 <<142354f5ebefd65d6aacd33a7cb2b4ab>]/Info 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;
}

I have pdf file in my application. I need to display the pdf in browser. I am reading the file as a fileInputStream, I need to display the pdf in browser with in my application. But i dont have the pdf path, I have the file stream.

Please give me some suggestion and examples


I have used ajax to display the pdf, I am using the call_method() javascript ajax request method to call the showPdf action, In showpdf action just converting the pdf file as ByteArrayOutputStream and write the result in the out put stream. But it showing the below metioned result.

Result in 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 xref 0 7 0000000000 65535 f 0000000389 00000 n 0000000015 00000 n 0000000477 00000 n 0000000232 00000 n 0000000540 00000 n 0000000585 00000 n trailer <<142354f5ebefd65d6aacd33a7cb2b4ab>]/Info 6 0 R/Size 7>> startxref 707 %%EOF

Please give some suggestion.

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 Methods:

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;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

森林迷了鹿 2024-12-11 06:26:05

您必须将 InputStream 写入响应 OutputStream,如下所示:

  • 您的 Content-Disposition 必须内联 >。
  • 您的 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();
    }
}

You will have to write your InputStream to your response OutputStream as follows:

  • Your Content-Disposition will have to be inline.
  • Your Content-Type will have to be application/pdf.
  • Your Content-Length will be the length (in bytes) of the total data in the InputStream.

Once set, write the input stream data to output stream of the response.

Something of this effect:

/* (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();
    }
}
就此别过 2024-12-11 06:26:05

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

请参阅 http://www.iana.org/assignments/media-types/

In your servlet, set the MIME type to the correct one for PDF : application/pdf

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文