Monday, March 21, 2011

PDF generation

Itext is a tool that can be used for generationg pdf.
Download iText-5.0.6.jar from http://sourceforge.net/projects/itext/files/iText/iText5.0.6/iText-5.0.6.jar/download
Following is a sample code that generates PDF.

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.itextpdf.text.BaseColor;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class PDFGenerator {
public static void main(String args[]) throws FileNotFoundException,DocumentException {
Document document = new Document(PageSize.A4, 50, 50, 50, 50);

PdfWriter.getInstance(document, new FileOutputStream("C:\\SampleTextTest.pdf"));document.open();

document.add(new Paragraph("This is a sample document"));
document.add(new Paragraph("How is the text in this color?",


FontFactory.getFont(FontFactory.TIMES_ITALIC, 14, Font.BOLD, new BaseColor(145,140, 250))));
document.close();

System.out.println("=======success=====");
}

}

Put the above code in the PDFGenerator.java file and run it after ensuring that the requiredjar file is accessible in the classpath.If the program is success, you will have a pdf file created in the path given.There are various other apis which can be used to implement our needs.Source http://www.ibm.com/developerworks/opensource/library/os-javapdf/

0 comments: