How do I create a PDF document using iText?

This example is the first example of the iText series, we are going to start by learning to use the iText PDF library to create a PDF document. We will see how to use the Document class, getting an instance of PdfWriter, creating a simple Paragraph and set the text alignment and the font.

The basic steps to produce a PDF documents 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.

And here is a code example that demonstrate the creation of a PDF document.

package org.kodejava.example.itextpdf;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;


public class DocumentCreate {
    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.
                    new FileOutputStream(new File("HelloWorld.pdf")));

            // 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 " +
            Paragraph paragraph = new Paragraph(text);
            paragraph.setFont(new Font(
                    Font.FontFamily.HELVETICA, 10, Font.NORMAL));

        } catch (DocumentException | FileNotFoundException e) {
        } finally {

Maven Dependencies

<!-- -->

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.