- Java EE Tutorials
- Servlets Tutorials
- Servlets Interview Questions
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.
package javabeat.net.servlets; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; 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(); response.setContentType("application/pdf"); String filepath = "/home/jsp.pdf"; response.setHeader("Content-Disposition", "inline; filename=’jsp.pdf'"); FileOutputStream fileout = new FileOutputStream(filepath); fileout.close(); out.close(); } }
Explanation:
- 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 :