How do I use iText Document class?

The com.itextpdf.text.Document is the core class of the iText library. This class represents a pdf document. Basically to work with a document we must first create an instance of a Document. After the instance created we open the document by calling the open() method. To add some content into the document we can use the add() method. Finally after done with the document we must close it by calling the close() method.

If you need to write and flush the document into a file we can use a PdfWriter class. The class constructor accept a Document object and an OutputStream object to do the work.

package org.kodejava.example.itextpdf;

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

public class DocumentDemo {
    public static void main(String[] args) {
        // Creates an instance of a Document.
        Document document = new Document();
        try {
            // To work with a Document we must open the document, add
            // some contents and finally close the document.
            document.open();
            document.add(new Paragraph("Hello World!"));
            document.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<!-- http://repo1.maven.org/maven2/com/itextpdf/itextpdf/5.5.10/itextpdf-5.5.10.jar -->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.10</version>
</dependency>

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🙂.

Leave a Reply

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