Tuesday, January 20, 2009

Generate PDF files from Java Applications dynamically

Generate PDF files from Java Standalone/Web Applications dynamically

IText is a freely available Java library from Lowagie.com. The iText library is powerful to generating PDFs.

Pre-requisites:

  1. Itext-2.1.4.jar (To download http://www.lowagie.com/iText/download.html )

    Optional (If we need to align text as traditional format):

    1.itext-hyph-xml.jar (To download http://sourceforge.net/project/showfiles.php?group_id=15255&package_id=151860&release_id=326129)

Configuring iText in Eclipse :

Being a pure Java library, iText comes in the form of a JAR file . Once you have downloaded the library (let's say, at path C:\temp), the following steps will configure the iText library in an Eclipse environment:

  1. Create a new Java project in Eclipse named like iText .
  2. Right-click on the iText project in Package Explorer view and select Properties.
  3. Click Java Build Path. On the Libraries tab, click Add External JARs.
  4. Browse to the C:\temp directory and select the itext-2.1.4.jar in this directory.
  5. Click OK.

OR

Place itext-2.1.4.jar file into your project lib folder (eg: G:\eclipseworkspace\Apps-Web\WebContent\WEB-INF\lib)

The iText API: Closer look

The com.lowagie.text.Document is the main class for PDF document generation. This is the first class to be instantiated. Once the document is created, we would require a writer to write into it. The com.lowagie.text.pdf.PdfWriter is a PDF writer. Some of the other commonly used classes are given below:

Basic Steps to do:

/* Simple HelloWorld.java program */

Step 1: Create a Document.

Step 2: Get a DocWriter instance (in this case, a PdfWriter instance)

Step 3: Open the Document.

Step 4: Add content to the Document.

Step 5: Close the Document.

 

Document document = new Document(); ------àStep 1

try {

PdfWriter.getInstance(document,new FileOutputStream("HelloWorld.pdf")); --------àStep2

document.open(); -----------------àStep3

document.add(new Paragraph("Hello World")); ---------------àStep4

} catch (Exception e) {

// handle exception

}

document.close(); ------------àStep5

let me know if you have any queries on this(IText).

Regards,

Cheekuri.

1 comment:

  1. very nice article...it will helps me a lot

    ReplyDelete