How do I use iText Phrase class?

The com.itextpdf.text.Phrase represent a phrase of text in the Document object. The Phrase object knows how to add spacing between lines of text. So if we add some phrase into the document it will start on a new line when it reaches the right edge of the document. The default leading / line spacing of a Phrase object is 16.

package org.kodejava.example.itextpdf;

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

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

public class PhraseDemo {
    public static void main(String[] args) {
        // Creates an instance of Document.
        Document document = new Document();
        try {
            // Write the pdf document into a file using the PdfWriter
            // and passes the document object and a FileOutputStream.
            PdfWriter.getInstance(document, new FileOutputStream("PhraseDemo.pdf"));
            document.open();

            // Add a some Phrase element into the document.
            document.add(new Phrase("This is the first text "));
            document.add(new Phrase("This is the second text "));
            document.add(new Phrase("This is the third text "));
            document.add(new Phrase("This is the fourth text "));
            document.add(new Phrase("This is the fifth text "));
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
    }
}

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

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply