I host one of my production webs on a hosted server that I do not control.  This is much easier than having to worry about maintaining a server in my home (and the problems that come with hosting in your home - like horrible speeds, power outages, etc.).

Yesterday, as I was migrating the site over to the new host, I ran into a few problems.  The first problem is that I take advantage of HttpModules to enable custom extensions like .product and .category.  This was easily solved by opening a ticket with my ISP help desk and asking them to map the extensions to the .NET runtime (just like .aspx or .asmx are).

The second problem was a little more interesting.  In order to provide the branding of the site, I had to create a dynamic title image generator that grabbed the titles out of the database and built an image using a specific font.  The issue I ran into here is that my host does not have the particular font that I need installed on the server.  I went looking for a way that I could use this font without submitting another help ticket.  I figured two things: if I was the administrator for my host, I'd be a little irritated by such a request (even though I'm certain they would have done it anyway) - also, if the server ever got rebuilt, then I 'd have to ask to have the font installed each time.

Well, I found the answer I was looking for, and it is an incredibly simple solution.

Here's the code that I used to have:

    Font tFont = new Font("French Script MT", 30, FontStyle.Bold);

Since my host didn't have the French Script MT font installed, I had to use a class called the PrivateFontCollection.  Here is the new code:

    // load a Private font collection to ensure we have the correct font
    PrivateFontCollection fontCollection = new PrivateFontCollection();
    fontCollection.AddFontFile(fontPath +
"\\FRSCRIPT.TTF"
);
    Font tFont = new Font(fontCollection.Families[0], 30, FontStyle
.Bold);

As you can see, it was just a matter of loading the font from disk and using the first family in the fontCollection in the Font class constructor.

Initially, I can see two primary use cases for this class:

  • Hosted web servers - Using GDI+, it is possible to create images using a specific font.  There's a good chance that the font you need isn't going to be on the server (and may not be licensed to that host).  This is the use case that I ran into.
  • Windows applications - With the new WinFX WPF applications coming out these days taking advantage of rich graphical user experiences, I can see where it would be useful to use the PrivateFontCollection to keep a ClickOnce application from having to install a font in the system Font directory.  This would lower the security permissions required to execute the code and would provide a much more secure experience for your users.