Wednesday, June 7, 2006

FontDialog and Font Paths

One of FeedJournal's system requirements is to be able to customize the fonts in the PDF newspaper. Honesty I thought that this would be a piece of cake. But, I run into some problems...

In the PDF file you can specify Type 1 and Type 2 fonts. Type 1 are common fonts, such as Courier, Helvetica and Times Roman. Adding these fonts are very straightforward since the PDF format supports them natively.

However the difficulties begin when the user should be able to select any font. The Type 2 fonts have to be specified using an absolute path to the font (which can be either TrueType or OpenType). No problem right? Yeah, that's what I said yesterday too. I tried to simply add a FontDialog to my settings form. From the control I wanted to get the selected font's absolute path. No dice... No matter how hard I looked for the suitable property in the .NET's Font class, it simply didn't exist. Actually I didn't find any property in the Font object from which I could deduct the correct path (there is not necessarily a correlation between the font's name and filename). I was scratching my head for a long time until I cam up with a solution, which is working good .

I created a static class called InstalledFonts, which upon startup gets the path in the SystemRoot environment variable, and iterates over all *.ttf files in the Fonts subdirectory. For each file it finds, it tries to load it into a PrivateFontCollection and checks which styles are associated to it. Each font found is added to a Dictionary mapping fonts to their system path. Later on I simply use this dictionary to make the mapping between installed fonts and their path.

No comments:

Post a Comment