Sunday, November 11, 2012

Java class to Generate PDF




import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;

import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class PdfGenerate {

public static void main(String[] args) {
try {
OutputStream file = new FileOutputStream(new File("L:\\MySamplePdf.pdf"));

Document document = new Document();
PdfWriter.getInstance(document, file);

document.open();
document.add(new Paragraph("Hello World, iText"));
document.add(new Paragraph(new Date().toString()));
PdfPTable table = new PdfPTable(3); // 3 columns.

           PdfPCell cell1 = new PdfPCell(new Paragraph("Cell 1"));
           PdfPCell cell2 = new PdfPCell(new Paragraph("Cell 2"));
           PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 3"));
           PdfPCell cell4 = new PdfPCell(new Paragraph("Cell 4"));
           PdfPCell cell5 = new PdfPCell(new Paragraph("Cell 5"));
           PdfPCell cell6 = new PdfPCell(new Paragraph("Cell 6"));


           table.addCell(cell1);
           table.addCell(cell2);
           table.addCell(cell3);
           table.addCell(cell4);
           table.addCell(cell5);
           table.addCell(cell6);


           document.add(table);

document.close();
file.close();

} catch (Exception e) {

e.printStackTrace();
}
}
}


Jar File Required are,
itextpdf-5.2.1.jar

No comments:

Post a Comment