How To Set PDF File Display In Servlet

In this article we will write a simple program which will write content to a PDF file. Example of writing data into PDF using Servlet. Create a Servlet called PDFDemo.



import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PDFDemo extends HttpServlet{
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			   throws IOException {
			  PrintWriter out = response.getWriter();
			  String filepath = "/home/jsp.pdf";
			  response.setHeader("Content-Disposition", "inline; filename=’jsp.pdf'");
			  FileOutputStream fileout = new FileOutputStream(filepath);



  • Content-Disposition in response header contains inline disposition type and file name attributes.
  • inline is disposition type. If it is marked “inline” then it should be automatically displayed when the message is displayed.
  • filename is name of the file used when creating the file.
  • ContentType is used to display MIME (Multipurpose Internet Mail Extensions) type. MIME type describes contents of various files.
  • PrintWriter object is used to display the result.
  • FileOutputStream is an output stream which is used to write data to file or file descriptor.

Execute the above program, right mouse click on the class PDFDemo and select Run>Run As, a pdf file with the name jsp.pdf would be created at the specified path in our case it is /home/jsp.pdf.

Previous Tutorial : How To Initialize Variables In Servlet?  || Next Tutorial : 

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!