7 Replies Latest reply on Apr 11, 2014 7:21 AM by jwenting

    how to serve PDF from servlet that opens at a named destination in the PDF file?


      My app requires context-sensitive help from a PDF file. I originally started out by using URL links such as




      where the PDF file contains a named destination that locates Chapter 5 in the file such that when this URL is used, downloads then opens the PDF file to Chapter 5 in the browser.


      The problem with this is that (1) I need to validate a user has permission to access this PDF file, and (2) I need to hide the PDF file's location from the user. I'm trying to solve both of these issues using a Java servlet that first validates the user then streams the PDF file to the browser.


      The following code works to open a popup window in the browser that asks the user if he/she wants to Save or Open the file.


      Here's the core Java servlet code:


              File file=new File("/path/to/my/myFile.pdf");

              if (file.exists()) {

                  res.setContentType("application/x-download");  // Set the content type (MIME Type) of the response.

                  res.setHeader("Content-Disposition", "attachment; filename");

                  returnFile(filename, res.getOutputStream());

              } else {

                  //error handling goes here



      where the method "returnFile()" is:


        private static void returnMyFile(String filename, OutputStream out) throws FileNotFoundException, IOException {

            InputStream in = null;

            try {

                in = new BufferedInputStream(new FileInputStream(filename));

                byte[] buf = new byte[4 * 1024]; // 4K buffer

                int bytesRead;

                while ((bytesRead = in.read(buf)) != -1) {

                    out.write(buf, 0, bytesRead);


            } finally {

                if (in != null) in.close();




      This solves the two issues above, but introduces a third issue not originally present: regardless of whether the user Saves then opens, or simply Opens the file, the file, when opened, always opens at page 1. How can I use a Java servlet to open a PDF file in a browser to a named destination defined in the PDF file?


      I actually don't want a popup window that asks the user whether he/she wants to Open or Save the file. Ideally, the file just opens in the browser from cache memory to the named destination, exactly as if the user had gone to this url:




      Is this possible from a Java servlet? Any hints MUCH appreciated.