Thursday, October 15, 2009

Java : Create Table in PDF file

Here is the program to create table in PDF file.

You need to download iText jar file to run this code. Get iText from http://www.lowagie.com/iText/download.html

Here is the complete code.

/* PDFTable.java */

import java.io.*;
import java.awt.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
import com.lowagie.text.Font;
// reference to Font is ambiguous
//java.awt.Font and com.lowagie.text.Font

public class PDFTable
{
public static void main(String arg[])throws Exception
{
Document document=new Document(PageSize.A4,50,10,10,10);

PdfWriter.getInstance(document,new FileOutputStream("PDFTable.pdf"));
document.open();
document.add(new Paragraph("Simple and Easy Codes"));
document.add(new Paragraph("http://simpleandeasycodes.blogspot.com/",FontFactory.getFont(FontFactory.COURIER, 14,Font.BOLD, new Color(255, 150, 200))));

Table table = new Table(3);

table.setBorderWidth(1);
table.setBorderColor(new Color(0, 0, 255));
table.setPadding(5);
table.setSpacing(5);

Cell cell = new Cell("header");
cell.setHeader(true);
cell.setColspan(3);
table.addCell(cell);
table.endHeaders();

cell = new Cell("example cell with colspan 1 and rowspan 2");
cell.setRowspan(2);
cell.setBorderColor(new Color(255, 0, 0));
table.addCell(cell);

table.addCell("1.1");
table.addCell("2.1");
table.addCell("1.2");
table.addCell("2.2");
table.addCell("cell test1");

cell = new Cell("big cell");
cell.setRowspan(2);
cell.setColspan(2);

table.addCell(cell);
table.addCell("cell test2");

document.add(table);


document.close();
}
}