Friday, 2 October 2015

Example to write data into PDF using servlet

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.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.

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

No comments:

Post a Comment