How do I define a font for text object in iText?

We can set font style for text object such as Chunk, Phrase, Paragraph, etc. using the com.itextpdf.text.Font class. We can define the font face, size, style and its color using this class.

package org.kodejava.itextpdf;

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

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

public class FontDemo {
    public static void main(String[] args) {
        Document doc = new Document();
        try {
            PdfWriter.getInstance(doc, new FileOutputStream("FontDemo.pdf"));
            doc.open();

            // Creates some fonts
            Font largeBold = new Font(Font.FontFamily.COURIER, 32,
                    Font.BOLD);
            Font smallItalic = new Font(Font.FontFamily.HELVETICA, 10,
                    Font.ITALIC);
            Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12,
                    Font.ITALIC | Font.UNDERLINE, BaseColor.RED);

            // Creates chunk, phrase and paragraph with font
            // information.
            Chunk chunk = new Chunk("Hello World", largeBold);
            Phrase phrase =
                    new Phrase("The quick brown fox ", smallItalic);
            Paragraph paragraph =
                    new Paragraph("jumps over the lazy dog", redFont);

            doc.add(chunk);
            doc.add(phrase);
            doc.add(paragraph);
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            doc.close();
        }
    }
}

Maven Dependencies

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

Maven Central

Wayan

Leave a Reply

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