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.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

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.3</version>
</dependency>

Maven Central

Wayan

1 Comments

Leave a Reply

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