3
votes

I'm trying to write a web application that supposed to get a link of a font, and return an image of something written in the format of the font that was sent.

I'm opening a stream that reads the font file, and send the file's InPtr to PrivateFontCollection.AddMemoryFont, so I could use it later with some graphics object. Everything works well when I use a valid .ttf file, but whenever I try to use .woff font files, I get 'System.IO.FileNotFoundException: File not found' for the AddMemoryFont line, even though I can see that the file was read with no error.

I tried using online converter to convert the .woff file to .ttf, and when I ran my code on the new .ttf file, it worked perfectly.

Is there a problem using .woff files, or do I need to change something to make it work?

WebClient client = new WebClient();
Stream stream = client.OpenRead("http://www.drivehq.com/file/df.aspx/shareID2129391/fileID59377155/arial.ttf"); // Works fine.
//Stream stream = client.OpenRead("http://themes.googleusercontent.com/static/fonts/kiteone/v1/VNHoD96LpZ9rGZTwjozAOvesZW2xOQ-xsNqO47m55DA.woff"); // Doesn't work.
PrivateFontCollection fonts;
FontFamily family = LoadFontFamily(stream, out fonts);

public static FontFamily LoadFontFamily(Stream stream, out PrivateFontCollection fontCollection)
{
    byte[] buffer = null;
    using (MemoryStream ms = new MemoryStream())
    {
        int count = 0;
        do
        {
            byte[] buf = new byte[1024];
            count = stream.Read(buf, 0, 1024);
            ms.Write(buf, 0, count);
        } while (stream.CanRead && count > 0);
        buffer = ms.ToArray();
    }

    var handle = System.Runtime.InteropServices.GCHandle.Alloc(buffer, System.Runtime.InteropServices.GCHandleType.Pinned);

    try
    {
        var ptr = System.Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 0);
        fontCollection = new PrivateFontCollection();
        fontCollection.AddMemoryFont(ptr, buffer.Length);
        return fontCollection.Families[0];
    }
    finally
    {
        handle.Free();
    }
}
1
It must be a TTF file, scratch WOFF.Hans Passant
Well, that is my question. is there a way using WOFF, or there's no way whatsoever? (except converting the file, of course)modz0r

1 Answers

0
votes

.NET Framework does not support importing of WOFF fonts, just like Windows XP/Vista/7/8.

You'll have to convert it to TTF using an external tool and import the TTF.