Tech and Media Labs
This site uses cookies to improve the user experience.




Getting Started with IText PDF API for Java

Jakob Jenkov
Last update: 2014-05-24

To use IText PDF API for Java you must first download the IText JAR file from the IText website, and include it on your application class path.

Here is a simple code example that generates a very simple PDF document using IText:

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

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

/**

 */
public class HelloWorldExample {

    public static void main(String[] args) {

        Document document = new Document();

        try {
            PdfWriter.getInstance(document,
                new FileOutputStream("HelloWorld.pdf"));

            document.open();
            document.add(new Paragraph("A Hello World PDF document."));
            document.close(); // no need to close PDFwriter?

        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}

Here is what happens in the code example:

  1. First a Document instance is created. This Document instance represents the PDF document. To add content to the PDF document, you call methods on the Document instance.

  2. Second, a PDFWriter is created, passing the Document instance and an OutputStream to its constructor. The Document instance is the document we are currently adding content to. The OutputStream is where the generated PDF document is written to. In this example the PDF document is written to a file, using a FileOutputStream.

  3. Third, the document is opened by calling document.open(). Now you can add content to the Document instance.

  4. Fourth, content (a Paragraph instance) is added to the Document instance.

  5. Fifth, the Document instance is closed, by calling document.close(). It is important to close the document, to flush all content in the document to the PDFWriter.

That's it.

Jakob Jenkov




Copyright  Jenkov Aps
Close TOC