Display Pdf in browser using java servlet

后端 未结 2 1546
生来不讨喜
生来不讨喜 2020-11-29 10:52

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 applica

相关标签:
2条回答
  • 2020-11-29 11:00

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

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

    0 讨论(0)
  • 2020-11-29 11:20

    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题