Posted by Unknown on 2:08 PM
Labels:

Send data from database in PDF file as servlet response:
This example retrieves data from MySQL and sends response to the web browser in the form of a PDF document using Servlet. This program uses iText, which is a java library containing classes to generate documents in PDF, XML, HTML, and RTF. For this you need to place iText.jar file to lib folder of your JDK and set classpath for it. You can download this jar file from the link http:// www.lowagie.com/iText/download.html The program below will embed data retrieved from database in PDF document.

import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;

public class ShowPdf extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
res.setContentType("application/pdf");
//Create a document-object
Document document = new Document();
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");

java.util.List list = new ArrayList();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from employee");
while(rs.next()){
String id = rs.getString("empId");
String add = rs.getString("empAdd");
list.add(id+" "+add);
}
// Create a PDF document writer
PdfWriter.getInstance(document, res.getOutputStream());
document.open();
// Create paragraph
Paragraph paragraph = new Paragraph("Data from database:");
// Add paragraph to the document
document.add(paragraph);

com.lowagie.text.List list1=new com.lowagie.text.List(true);
Iterator i = list.iterator();
while(i.hasNext()){
list1.add(new ListItem((String)i.next()));
}
// Add list of data retrieved from database to the document
document.add(list1);
document.close();
}
catch (Exception e) {
e.printStackTrace();
// Close the document
document.close();
}

}
}

0 comments: