Creating a PDF Programmatically with iText

All will agree that pdf’s are cool, right? So, In this brief tutorial I will be describing how to create a pdf programmaticallywith NetBeans and how to add the iText library to your NetBeans projects. As is always the case this tutorial is intended to wet your appetite for the iText library. When you get serious you’ll want to create shapes and play with colors. In this tutorial I will show you how to create a pdf that shows a big Hello World at the top and draws eight squares underneath it. Here is the finished product, you can play around with the collors and draw loop to add more effects.

First thing you will need to have a copy of NetBeans. And also a copy of the iText Core jar. In Netbeans you will want to create a new project, call it “HelloWorld”. A this point you should create a new package, call it “pdfbuilder”.

Right click the package pdfbuilder you’ve just created and select New > Java Class:

Creating a New Java Source File

You will need to give the class a name so for this example you should call it HelloWorld then hit finish:

Naming a Java Class

Before we continue with the fun part we need to create a library for our iText jar and add it to the project. To do this all you have to do is Right Click on the libraries icon and select Add Library:

Adding a Library to the project

Create a new Library and name it iText:

Creating the iText Library

Add the iText Core jar that was downloaded earlier:

Adding the Jar to the Library

Now your is ready to accept the following code:

package pdfbuilder;

import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfWriter;

public class HelloWorld {

    public static void main(String[] args) {
            Document document = new Document();
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("c:/world.pdf"));

            PdfContentByte cb = writer.getDirectContent();
            BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
                    BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            cb.setFontAndSize(bf, 39);
            cb.setRGBColorFill(0xcc, 0x66, 0x66);
            cb.showTextAligned(Element.ALIGN_LEFT, "Hello World :)", 36, 788, 0);

            cb.setRGBColorFill(0x9a, 0xe4, 0xe8);
            for (int i = 0, j = 55; i < (j * 8); i += j)
                cb.roundRectangle(36 + i, 718, 50, 50, 5);

        } catch (Exception e)

What you get after you run this program is a file named world.pdf in the root of your c:/ drive.

4 comments / Add your comment below

Leave a Reply

Your email address will not be published. Required fields are marked *