Can anyone tell how to display a PDF file which is stored in my database using servlets and JSP? Are there any specific jar files to be imported?
Asked
Active
Viewed 1.3k times
1
-
If the client computer has Java, then you can display the PDF using a JNLP or an applet. I have written an article [A Java PDF Web Viewer - Powered By PDFOne (for Java™)](http://www.gnostice.com/nl_article.asp?id=195&t=A_Java_PDF_Web_Viewer_-_Powered_By_PDFOne_(for_Java_trade;)) for my company. This article contains a demo that displays a PDF file on the local computer. You could change the code so that it displays a PDF generated off the DB server-side. – BZ1 Jan 07 '11 at 04:30
1 Answers
5
Just get it as InputStream
from DB and write it to OutputStream
of the response along a correct set of headers. Here's a snippet assuming you're using JDBC to interact with DB.
response.setContentType("application/pdf");
// ...
InputStream input = resultSet.getBinaryStream("columnname");
OutputStream output = response.getOutputStream();
// Write input to output the usual way.
// ...
When mapped on an url-pattern
of for example /pdfservlet
, then you can just call the servlet using <a>
link
<a href="pdfservlet?id=123">click here</a>
or by <object>
if you want to embed it in HTML.
<object data="pdfservlet?id=123" type="application/pdf" width="600" height="400">
</object>
You don't need any additional libraries. A complete kickoff example can be found here.

BalusC
- 1,082,665
- 372
- 3,610
- 3,555
-
@BalusC It is not opening the pdf file. Its just showing a blank page. I want to open the pdf file retrieved from database, What should i do? – suraj Apr 26 '12 at 06:33
-
Perhaps input hasn't been written to output, or the content in DB is actually empty. – BalusC Apr 26 '12 at 12:14