Displaying pdf in jsp

JSP is the wrong tool for the job of serving a file download. JSP is designed as a view technology with the intent to easily produce HTML output with taglibs and EL. Basically, with your JSP approach, your PDF file is cluttered with <!DOCTYPE>, <html> etc tags and therefore corrupted and not recognizable as a valid PDF file. This is by the way one of the reasons why using scriptlets is a bad practice. It has namely completely confused you as to how stuff is supposed to work. In this particular case, that is using a normal Java class for the file download job.

You should be using a servlet instead. Here’s a kickoff example, assuming that Servlet 3.0 and Java 7 is available:

@WebServlet("/foo.pdf")
public class PdfServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        File file = new File("/absolute/path/to/foo.pdf");
        response.setHeader("Content-Type", getServletContext().getMimeType(file.getName()));
        response.setHeader("Content-Length", String.valueOf(file.length()));
        response.setHeader("Content-Disposition", "inline; filename=\"foo.pdf\"");
        Files.copy(file.toPath(), response.getOutputStream());
    }

}

(if Servlet 3.0 is not available, then map it in web.xml the usual way, if Java 7 is not available, then use a read/write loop the usual way)

Just copypaste this class in its entirety into your project and open the desired PDF file by /contextpath/Saba_PhBill.pdf instead of /contextpath/youroriginal.jsp (after having organized it in a package and autocompleted the necessary imports in the class, of course).

E.g. as follows in a JSP where you’d like to show the PDF inline:

<object data="${pageContext.request.contextPath}/Saba_PhBill.pdf" type="application/pdf" width="500" height="300">
    <a href="${pageContext.request.contextPath}/Saba_PhBill.pdf">Download file.pdf</a>
</object>

(the <a> link is meant as graceful degradation when the browser being used doesn’t support inlining application/pdf content in a HTML document, i.e. when it doesn’t have Adobe Reader plugin installed)

See also:

Leave a Comment