java.net member

Rechercher dans ce site

Hello World, in PDF, using iText and Java

>> 23 September 2010

Generating PDF from your Java programs is nowadays possible and easy, thanks to iText a free/Open Source project (you can also have a commercial license).

IText let you (between other things) generate PDF documents and save these as ordinary .pdf file from any Java program. It can also generate a PDF document on the fly, this one, for instance can be served from a servlet.

In this tiny tutorial, I'll generate a .pdf file from a Java program.

Note about GAEJ
In older versions of iText, some dependencies were not on the "The JRE Class White List" of Google. In this version (and maybe in other recent versions), this problem was likely solved and restricted class exception is now over, or at least in the code i've been testing for the last couple of days (simple PDF documents).

Official site of iText
http://itextpdf.com/

Download site
http://sourceforge.net/projects/itext/files/

Download iText
itext is available as .jar file (the current version is 5.0.4)

Installing
  • If you use a Java project (In Eclipse for instance), just create a folder of your choice in the project (in the example I called it "lib"), copy "iText-5.0.4.jar", to "lib" folder.
  • Add "iText-5.0.4.jar" (now in YourProject/lib) to YourProject/properties/Java Build Path


HelloWorld!!!

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

/**
*
* @author kaesar ALNIJRES
*
*/

public class HelloWorldFromIText {


public static void main(String[] args) {

Document document = new Document();

try {
PdfWriter.getInstance(document, new FileOutputStream("/home/kas/helloWorld.pdf"));


document.open();

document.add(new Paragraph("Hello World!!!"));

document.close();

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}


0 comments:

Post a Comment

  © Blogger template Simple n' Sweet by Ourblogtemplates.com 2009

Back to TOP