Wednesday, February 23, 2011

Generate PDF

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
public class PDFServlet extends HttpServlet {
 public void init(ServletConfig config) throws ServletException {
  super.init(config);
 }
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  doPost(request, response);
 }
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  String query = null;
  response.setContentType("application/pdf"); // Code 1
   //PrintWriter pw=response.getWriter();
  Document document = new Document();
  try {
   PdfWriter.getInstance(document, response.getOutputStream()); // Code
                   // 2
   document.open();
   try {
    int rcount = 0;
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection conn = DriverManager.getConnection(
      "jdbc:oracle:thin:@localhost:1521", "hr", "tiger");
    query = "SELECT * FROM REGIONS";
    Statement state = conn.createStatement(
      ResultSet.CONCUR_UPDATABLE,
      ResultSet.TYPE_SCROLL_SENSITIVE);
    ResultSet rs = state.executeQuery(query);
    ResultSetMetaData mdata = rs.getMetaData();
    int colcount = mdata.getColumnCount();
    PdfPTable table = new PdfPTable(1);
    while (rs.next()) {
     rcount++;
    }
    rs.beforeFirst();
    rs.next();
    table.addCell(mdata.getColumnName(colcount));
    rs.beforeFirst();
    for (int i = 1; i <= rcount; i++) {
     for (int j = 1; j <= colcount-1; j++) {
    
      table.addCell(rs.getString("region_name"));
     }
    }
    document.add(table);
    document.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
  } catch (DocumentException e) {
   e.printStackTrace();
  }
 }
}

0 comments:

Post a Comment