How do I create a PDF document using iText?

This example is the first example of the iText series on how to use the iText library to create a PDF document.

In this example we show how to use the Document class, getting an instance of PdfWriter, etc. Creating a simple Paragraph and set the text alignment and the font. Let see the code below:

package org.kodejava.example.itextpdf;

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

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

public class PDFDocumentCreate {
    public static void main(String[] args) {
        //
        // Create a new document.
        //
        Document document = new Document();
        try {
            //
            // Get an instance of PdfWriter and create a HelloWorld.pdf 
            // file as an output.
            //
            PdfWriter.getInstance(document,
                    new FileOutputStream(new File("HelloWorld.pdf")));
            document.open();

            //
            // Create our first paragraph for the pdf document to be 
            // created. We also set the alignment and the font of the 
            // paragraph.
            //
            String text =
                    "Kode Java website provides beginners to Java " +
                    "programming some examples to use the Java API " +
                    "(Application Programming Interface) to develop " +
                    "applications. Learning from some examples will " +
                    "hopefully decrease the time required to learn " +
                    "Java.";
            Paragraph paragraph = new Paragraph(text);
            paragraph.setAlignment(Element.ALIGN_JUSTIFIED);
            paragraph.setFont(new Font(
                    Font.FontFamily.HELVETICA, 10, Font.NORMAL));

            document.add(paragraph);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
    }
}

In the example above you've seen some basic steps that we use to produce a PDF documents. These steps are:

  • Create a Document object that represents a PDF document.
  • The PdfWrite object that need the Document and an OutputStream object write the content of the PDF we added to the Document into a PDF file.
  • We add a paragraph into the Document instance using the Paragraph object.
  • Finally we need to close the document by calling the Document.close() method.