i am searching for java code to view pdf file on browser without downloading them. The files will be inserted through database.Help will be appreciated.
Asked
Active
Viewed 3,358 times
-2
-
4*"java code to view pdf file on browser without downloading them."* This is impossible. A browser ***must*** download a file in order to display it! BTW - 1) Words typed in all lower case are hard to read, like trying to listen to someone who is mumbling. Please use an upper case letter at the start of sentences, for the word I, and proper names like `ArrayList` or Oracle. 2) This had the [tag:eclipse] tag added and none other. This has **nothing** to do with your IDE and everything to do with Java and PDF (for which tags are now added). – Andrew Thompson Mar 07 '15 at 10:43
-
Thanks a lot for your free advice. – Rutwik Nandha Mar 09 '15 at 07:08
-
Possible duplicate of [How to force files to open in browser instead of download (pdf)?](https://stackoverflow.com/questions/6293893/how-to-force-files-to-open-in-browser-instead-of-download-pdf) – Alex K Mar 01 '18 at 17:29
1 Answers
1
You need to use a servlet to do that:
import java.io.IOException;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
public class viewPDF extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
OutputStream out = null;
DB1 db = new DB1();
Connection conn=db.dbConnect(
"jdbc:jtds:sqlserver://localhost:1433/smpp","sa","");
try {
response.setContentType("application/pdf");
out = response.getOutputStream();
byte[] b = db.getPDFData(conn);
out.write(b,0,b.length);
out.close();
} catch (Exception e) {
throw new ServletException(
"Exception in Excel Sample Servlet", e);
} finally {
if (out != null)
out.close();
}
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
doGet(request, response);
}
}
See more info here and a fully working example which uses a PDF from a database in a browser: java-tips

Farshid Shekari
- 2,391
- 4
- 27
- 47

adrCoder
- 3,145
- 4
- 31
- 56
-
-
1Please accept my answer by clicking the tick box on the left of my answer, below the arrow, if you found it helpful – adrCoder Mar 09 '15 at 07:10
-