Search code examples
javapdfservletsstreaminglinearization

Stream linearized PDF from servlet to browser (fast web view)


I'm running a web app that provides a servlet. this servlet opens a pdf file from a Network File System and finally streams it to the requesting browser.

All the pdf files are linearized by adobe lifecycle pdf generator and ready for fast web view.

unfortunately, the fast web view does not work. I guess it's a problem of how to open and stream the file in java code and the setting of response header info. if i deploy a test pdf within my webapp onto the jboss AS and open it directly from the browser by url, the incrementel loading works.

can anyone help me?

Here's the code of my servlet:

response.setContentType("application/pdf");
response.setHeader("Expires", "0");
response.setHeader("Cache-Control",
    "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Content-Disposition",
    "inline;filename=" + documentReference);
response.setHeader("Accept-Ranges", "bytes");

File nfsPDF = new File(NFS_DIRECTORY_PATH + documentReference);

FileInputStream fis = new FileInputStream(nfsPDF);
BufferedInputStream bis = new BufferedInputStream(fis);
ServletOutputStream sos = response.getOutputStream();
byte[] buffer = new byte[(int) nfsPDF.length()];
while (true) {
   int bytesRead = bis.read(buffer, 0, buffer.length);
   if (bytesRead < 0) {
      break;
   }
   sos.write(buffer, 0, bytesRead);
}
sos.flush();
//... closing...

Solution

  • Let's see. You want to send a file in parts, right? Then you should check Range header (HTTP Header) and send only bytes in this range. I'm correct?