Why is my font not applied when I create a PDF document?

Category: 
Tags: fontsregister fontsFontFactoryiText 5

I am generating PDF documents with iText. When I try to include the "Agenda Tabular Light" font, iText ignores my choice of font. I confirmed that the font isn't set using Adobe Reader's File > Properties > Fonts. The PDF shows that Helvetica was used, but I didn't choose Helvetica. The colors are visible, but not the font.

My code looks like this:

public static final Font FONT_HEADER = FontFactory.getFont(AGENDA_TABULAR_LIGHT, 18, Font.NORMAL, TITLE_COLOR);
I even I tried a sample program.

// step 1
Document document = new Document();
// step 2
PdfWriter.getInstance(document, new FileOutputStream(filename));
Q> // step 3 document.open(); // step 4: Font font = FontFactory.getFont("Agenda Tabular Light"); System.out.println(font.toString()); document.add(new Phrase("Agenda Tabular Light J j", font)); Font fontbold = FontFactory.getFont("Times-Roman", 12, Font.BOLD); document.add(new Phrase("Times-Roman, Bold", fontbold)); document.add(Chunk.NEWLINE);
document.close();

It displays like Times-Roman and uses a different font for agenda. But whenever I see fonts tab on properties of Adobe Reader, it displays Helvetica.

Posted on StackOverflow on Jul 1, 2015 by lasheul

As explained in the comments, this usually doesn't work:

Font font = FontFactory.getFont("garamond bold");

By default only the standard Type 1 fonts are known to the FontFactory and "garamond bold" isn't one of those fonts, hence Helvetica will be used instead (Helvetica is the default font in iText).

You can "teach" the FontFactory where to find other fonts by registering them.

You could try:

FontFactory.registerDirectories();

But that is a very expensive operation as you ask iText to search your operating system for font files in different font directories (e.g. C:/Windows/Fonts). This can take a few seconds and you'll end up with much more fonts than you need (and maybe the font you need won't be registered anyway).

The best way is to register the fonts you need like this:

FontFactory.register("c:/windows/fonts/garabd.ttf", "garamond bold");

We tell iText where to find the ttf file ("c:/windows/fonts/garabd.ttf") and we define an alias for that font ("garamond bold"). Now that the font name is registerd, we can start using it:

Font myBoldFont = FontFactory.getFont("garamond bold");