itextFonts: iText 5 versus iText 7


In the first versions of iText, there was only one font class: Font.

With this font, you could create a Font object for fourteen fonts from five font families: Helvetica (regular, bold, oblique, bold-oblique), Times Roman (regular, bold, italic, bold-italic), Courier (regular, bold, oblique, bold-oblique), Symbol and Zapf Dingbats.

Such a Font object was created like this:

Font font = new Font(FontFamily.TIMES_ROMAN);

You also had to define the font size, for instance:

Font font14pt = new Font(FontFamily.TIMES_ROMAN, 14);

The default font was Helvetica; the default font size 12.

iText evolved and more fonts were supported. The BaseFont class was used to deal with these fonts internally. A BaseFont class was created like this:

BaseFont bf_russian = BaseFont.createFont(

The first parameter is the path to a font program, for instance a TTF file, the second parameter is the encoding, for instance CP1251 for Cyrillic characters, the third parameter indicates if a subset of the font needs to be embedded.

The BaseFont class is to be used when you add content at the lowest level, for instance when creating text objects in your code using beginText(), setFontAndSize(), setTextMatrix(), showText(), endText() sequences. Typically, you will only use this low-level approach if you are a PDF specialist. If you don't know anything of PDF syntax, you shouldn't use such a sequence.

You can also use the BaseFont class to create a Font object:

Font russian = new Font(bf_russian, 12);

Now we can use the russian font to create a Paragraph that contains Russian text.

There are some other ways in iText 5 to create Font objects, but this is the most common procedure. People were sometimes confused by the difference between Font and BaseFont, and they didn't always use the correct approach.

What we fixed in iText 7:

We made things more uniform. There is now a single PdfFont class, and you create a font using a PdfFontFactory:

PdfFont font = PdfFontFactory.createFont(FontConstants.TIMES_ROMAN);
PdfFont russian = PdfFontFactory.createFont(
    "src/main/resources/fonts/FreeSans.ttf", "CP1251", true);

You no longer need to create different font objects if you want to switch to another font size. Switching to a different font size can simply be done using the setFontSize() method:

Paragraph p = new Paragraph("Hello World! ")
    .add(new Text("Hallo Wereld! ").setFontSize(14))
    .add(new Text("Bonjour le monde! ").setFontSize(10));

The default font is still Helvetica and the default font size is still 12, but you can now define a font (and a font size) for the document:


In this case font will be the default font when adding a building block (for instance a Paragraph) without specifying a font.

Want to know more?

Read Introducing the PdfFont class which is chapter 1 in the iText 7: Building Blocks tutorial. Get the free ebook!