Martin
Martin

Reputation: 2300

Loading font-family from disk to PrivateFontCollection

I'm using the following code to load a font into memory for generating an image with GDI+:

var fontCollection = new PrivateFontCollection();
fontCollection.AddFontFile(Server.MapPath("~/fonts/abraham-webfont.ttf"));
fontCollection.Families.Count(); // => This line tells me, that the collection has 0 items.

There are no exceptions, but the fontCollection Families property is empty after the AddFontFile method has run without any exceptions.

I've verified that the path is valid (File.Exists returns true):

Response.Write(System.IO.File.Exists(Server.MapPath("~/fonts/abraham-webfont.ttf"))); // # => Renders "True"

The TTF-file seems to work fine, when I open the file, so it's not an invalid TTF-file: https://dl.dropboxusercontent.com/u/4899329/2016-10-12_22-44-52.png

Any suggestions?

Upvotes: 1

Views: 871

Answers (2)

OnceUponATimeInTheWest
OnceUponATimeInTheWest

Reputation: 1222

PrivateFontCollection is a simple shim over the Windows API. So the issue is not that the PrivateFontCollection is buggy but that the Font class is buggy.

However you can make this work by passing your Font constructor the family as obtained from the collection, rather than the name of the family. Something like this.

        var pf = new PrivateFontCollection();
        pf.AddFontFile(dir + "Polar Snow.ttf");
        var family = pf.Families[0];
        Debug.Assert(family.IsStyleAvailable(FontStyle.Regular));
        Font font = new Font(family, 48, FontStyle.Regular);

I tested this today up to .NET 9.0 and it seems fine with this simple fix.

Upvotes: 0

Martin
Martin

Reputation: 2300

Answer from Hans Passant solved the problem:

PrivateFontCollection is notoriously flakey. One failure mode that's pretty common today is that the font is actually an OpenType font with TrueType outlines. GDI+ only supports "pure" ones. The shoe fits, the web says that Abraham is an OpenType font. Works in WPF, not in Winforms.

Upvotes: 1

Related Questions