Wednesday, November 12, 2014

Extracting data from Mysql and creating PDF file using JAVA

//Table name : customer
// Database name: vishal
//PDF name : HelloWorld.pdf

package pdfread;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

public class CreatePDF
{
public static void main(String[] args) throws ClassNotFoundException, SQLException
{
Document document = new Document();
Connection conn = null;
Statement stmt = null;
try
{
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("/home/PdfLocation/HelloWorld.pdf"));
document.open();

Class.forName("com.mysql.jdbc.Driver");

// STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = (Connection) DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/vishal", "root", "root");

PdfPTable table=new PdfPTable(6);

System.out.println("Creating statement...");
stmt = (Statement) conn.createStatement();
String sql= "SELECT * from customer";
ResultSet rs = stmt.executeQuery(sql);

while (rs.next()) {
table.addCell(rs.getString("TRNID"));
table.addCell(rs.getString("NAME"));
table.addCell(rs.getString("DATE"));
table.addCell(rs.getString("AMOUNT"));
table.addCell(rs.getString("MATCH_FLAG"));
table.addCell(rs.getString("PS"));
}

document.add(new Paragraph("Table customer.\n"));
document.add(table);
document.close();
writer.close();
} catch (DocumentException e)
{
e.printStackTrace();
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
System.out.println("Done");
}
}

No comments:

Post a Comment