How to deserialize an uploaded font from a Base64String?

133 views Asked by At

I need to get the font family name from an uploaded font. The user uploads a .ttf file. When I try to deserialize the data I get the following error "The input stream is not a valid binary format." The font data is uploaded via a HTML5 FileReader using readAsDataURL().

Can anyone spot what I'm doing wrong? I suspect I'm using the wrong deserializer... but I'm not sure.

//clean the font data of encoding
var cleanFontData = brandingsFontAddViewModel.FontData.Split(',')[1];
var fontBytes = Convert.FromBase64String(cleanFontData);

using (Stream memStream = new MemoryStream(fontBytes, 0,  fontBytes.Length))
{
    var deserializer = new BinaryFormatter();
    var font = (Font)deserializer.Deserialize(memStream);
}
1

There are 1 answers

0
NullReference On BEST ANSWER

Finally found the answer.

// used to store our font and make it available in our app
                var pfc = new PrivateFontCollection();

                IntPtr data = Marshal.AllocCoTaskMem((int) ms.Length);

                Marshal.Copy(fontBytes, 0, data, (int)ms.Length);

                pfc.AddMemoryFont(data, (int)ms.Length);

                Marshal.FreeCoTaskMem(data);

                var fontWithMime = "data:application/x-font-truetype;charset=utf-8;base64," + cleanFontData;

                fontName = pfc.Families[0].Name;