Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Streaming pdf files

843842Feb 9 2009 — edited Feb 23 2009
I'm on windows using apache 2.2 communicating with tomcat 6 via mod_jk. I have a pdf file that is linearized (fast web view-enabled).

I'm having trouble byte serving (gradually showing the pdf file in chunks as it downloads as opposed to waiting for the entire file to finish downloading before viewing) the pdf. Some of the pdf files I need to serve are up to 80 MB. I know that out-of-the-box apache byte serves pdfs just fine, but I need to stream the pdfs through tomcat for security reasons.

Here is the [most pertinent] code that currently works:
public void doPost(HttpServletRequest req, HttpServletResponse res)
        throws IOException, ServletException {

        displayPdfResponse((PdfController) controller, res);
}

    /**
     * Display pdf response.
     * 
     * @param pdfController PdfController for this request
     * @param res           HttpServletResponse being returned
     * @throws Exception If lookup fails
     */
    private void displayPdfResponse(
        PdfController pdfController, HttpServletResponse res)
            throws Exception {

        res.setHeader("Cache-Control", "no-cache");        

        InputStream pdf = pdfController.getPdf();
        if (pdf == null) {
            res.setContentType("text/plain");
            res.getWriter().write("No document available.");
        } else {
            res.setContentType("application/pdf");
            res.setHeader("Content-Disposition", "inline");
            res.setHeader("Accept-Ranges", "bytes");

            DataOutputStream stream = 
                new DataOutputStream(res.getOutputStream());

            byte[] buf = new byte[4096];
            int bytesRead;
            while ((bytesRead = pdf.read(buf)) > 0) {
                stream.write(buf, 0, bytesRead);
            }
        }     
    }
The issue is it's not gradually loading the pdf in chunks. The user just stares at a blank page until the entire file loads. Large pdf files can take over 30 seconds to load and that's if the given pdf loads. In many cases on wireless, the file is just too big and times out.

Right now I'm thinking that I'm either missing a header parameter or I need to actually write a more complicated streaming function that gets the given requested content-range from the browser pdf plugin as its sent and serve the pdf piecemeal.

Please let me know if you have any ideas.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 23 2009
Added on Feb 9 2009
11 comments
1,420 views