iText PDF Generation in java

Monday, July 27, 2009

iText is a freely available Java library from Lowagie.com (see Resources). The iText library is powerful and supports the generation of HTML, RTF, and XML documents, in addition to generating PDFs. You can choose from a variety of fonts to be used in the document. Also, the structure of iText allows you to generate any of the above-mentioned types of documents with the same code.

The iText library contains classes to generate PDF text in various fonts, generate tables in PDF document, add watermarks to pages, and so on. There are many more features available with iText. It would not be possible to demonstrate all of them in a single article. We will cover the basics required for PDF generation.

For this application you need following jars file
Text-2.1.6.jar
iText-rtf-2.1.6.jar
Text-rups-2.1.6.jar

PDFGeneration.java


/**
* File Name : PDFGeneration.java
* Created By : Nagarajuv
* Created Date : Jun 18, 2009
* Purpose : Generation of PDF Through iText api
*/
package com.raj.iTextPDF;

/**
* @author nagarajuv
*
*/
import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfWriter;

public class PDFGeneration {
/**
* Generates a PDF file with the itext API
*
* @param args
* no arguments needed here
*/
public static void main(String[] args) {

System.out.println("---> resulting PDF: PDFGenerationExample");
// step 1: creation of a document-object
Document document = new Document();
try {
// step 2: we create a writer
PdfWriter.getInstance(document,new FileOutputStream("pdfs/PDFGenerationExample.pdf"));

/** Setting margins to document*/
document.setMarginMirroring(true);
document.open();
// step 4: we add a paragraph to the document
document.add(new Paragraph(
"The left margin of this odd page is 36pt (0.5 inch); the right margin 72pt (1 inch); the top margin 108pt (1.5 inch); the bottom margin 180pt (2.5 inch)."));
Paragraph paragraph = new Paragraph();
paragraph.setAlignment(Element.ALIGN_JUSTIFIED);
for (int i = 0; i < 20; i++) {
paragraph.add("Hello World, Hello Sun, Hello Moon, Hello Stars, Hello Sea, Hello Land, Hello People. ");
}
document.add(paragraph);
document.add(new Paragraph(
"The right margin of this even page is 36pt (0.5 inch); the left margin 72pt (1 inch)."));


} catch (DocumentException de) {
System.err.println(de.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}

// step 5: we close the document
document.close();
}
}

Enjoy with this is nice example
Image Hosted by ImageShack.us
Image Hosted by ImageShack.us

0 comments: