File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes displaying pdf file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "displaying pdf file" Watch "displaying pdf file" New topic

displaying pdf file

clyde melly
Ranch Hand

Joined: Sep 04, 2003
Posts: 152
import javax.servlet.*;
import javax.servlet.http.*;

public class ServletPdf extends HttpServlet

public void doPost (HttpServletRequestrequest,
HttpServletResponse response)
throws ServletException, IOException

BufferedInputStream bis = null;
BufferedOutputStream bos = null;

ServletOutputStream out =
response.getOutputStream ();

String title = "Simple Servlet Output";


String fileURL ="C:/servletxml/melly/ch03.pdf";

response.setHeader("Content-disposition","attachment; filename=" +"Example.pdf" );
try {
URL url = new URL( fileURL );
// Use Buffered Stream for reading/writing.
bis = new BufferedInputStream(url.openStream());
bos = new BufferedOutputStream(out);
byte[] buff = new byte[2048];
int bytesRead;
// Simple read/write loop.
while(-1 != (bytesRead =, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
} catch( MalformedURLException e) {
System.out.println ( "MalformedURLException." );
throw e;
} catch( IOException e) {
System.out.println ( "IOException." );
throw e;
} finally {
if (bis != null)
if (bos != null)
Displays an error page.Init is called.Kindly help.
Idly Vada
Ranch Hand

Joined: Sep 02, 2003
Posts: 135
change content type header to application/pdf
ie use
clyde melly
Ranch Hand

Joined: Sep 04, 2003
Posts: 152
same error page displayed when using (application/pdf)
Lasse Koskela

Joined: Jan 23, 2002
Posts: 11962
Forgive me if this is a stupid question but are you invoking the servlet with a GET or POST request?

Author of Test Driven (2007) and Effective Unit Testing (2013) [Blog] [HowToAskQuestionsOnJavaRanch]
I agree. Here's the link:
subject: displaying pdf file
It's not a secret anymore!