Why doesn't FontFactory.GetFont() work for all fonts?

Tags: fontsfont directoryregister fontsFontFactoryiText 5

If I say:

var georgia = FontFactory.GetFont("Georgia Regular", 10f);
it doesn't work. When I check the state of the variable georgia, it has its Family property set to the value UNDEFINED and its FamilyName property set to Unknown.

It only works if I actually load and register the font file and then get it like so:

FontFactory.Register("C:\\Windows\\Fonts\\georgia.ttf", "Georgia");
var georgia = FontFactory.GetFont("Georgia", 20f);

Why is that?

Posted on StackOverflow on Jun 3, 2014 by Water Cooler v2

iText is written in Java, which means it's platform-independent. It ships with 14 AFM files containing the metrics of the 14 Standard Type 1 fonts (4 flavors of Helvetica, 4 flavors of Times Roman, 4 flavors of Courier, Symbol and ZapfDingbats).

As soon as you need other fonts, you need to register the font files by passing the path to the font directory or the path to an actual font. The font directory on Linux is different from the font directory on Windows (there is no "C:/Windows/fonts" on Linux). There's also a method registerDirectories() that looks at the operating system you're currently using and that registers all the 'usual suspects' (iText guesses the font path based on the OS). This method is expensive: it registers all fonts it finds and this costs time and memory.

Once fonts are registered, you can ask the FontFactory for the registered names. This is shown in the FontFactoryExample. You'll notice the difference between the getRegisteredFonts() method and the getRegisteredFamilies() method.

Additional note: the original question is about iTextSharp, written in C#. iTextSharp is ported from Java and tries to stay as close as possible to the original version written in Java. Nevertheless, the same rationale applies: starting up an application would be much slower if iTextSharp would have to scan the fonts directory. In most applications, you only need a handful of fonts; registering all fonts available in the Windows fonts directory would be overkill.