How to write data into PDF using Servlet

Servlet Tutorial: How to write data into PDF using servlet. Let's see the simple example to write data into PDF using servlet.

How to write data into PDF using Servlet

How to write data into PDF using Servlet

Here, we are going to see how we can write data into PDF using servlet technology. We are simply writing some data using servlet and it will get displayed in the PDF.

To create such application, you need to have the spdf.jar file. If you download this example, you will get the example with jar file.

Example to write data into PDF using servlet

Let's see the simple example of writing data into PDF using servlet. In this example, we have mentioned the content type application/pdf that must be specified to display data in the PDF format.

ServletPDF.java

  1. import java.io.*;  
  2. import java.util.*;  
  3. import javax.servlet.*;  
  4. import javax.servlet.http.*;  
  5. import com.darwinsys.spdf.PDF;  
  6. import com.darwinsys.spdf.Page;  
  7. import com.darwinsys.spdf.Text;  
  8. import com.darwinsys.spdf.MoveTo;  
  9.   
  10. public class ServletPDF extends HttpServlet {  
  11.   
  12. public void doGet(HttpServletRequest request,  
  13.         HttpServletResponse response) throws IOException {  
  14.   
  15. PrintWriter out = response.getWriter();  
  16. response.setContentType("application/pdf");  
  17.   
  18. response.setHeader("Content-disposition","inline; filename='samtpoint.pdf'");  
  19.   
  20. PDF p = new PDF(out);  
  21. Page p1 = new Page(p);  
  22. p1.add(new MoveTo(p, 200700));  
  23. p1.add(new Text(p, "www.samtpoint.com"));  
  24. p1.add(new Text(p, "by Sam"));  
  25.           
  26. p.add(p1);  
  27. p.writePDF();  
  28.   
  29. }  
  30. }