Brick icon

C# Font Embedding

Brick | PRO | 08/30/15 11:58:27 AM UTC | 0 ⭐ | 247 👁️ | Never ⏰ | []
C# |

1.68 KB

|

None

|

0 👍

/

0 👎

[DllImport("gdi32.dll")]
private static extern IntPtr AddFontMemResourceEx(IntPtr pbPurista, uint cbPurista, IntPtr pdv,
    [In] ref uint pcFonts);
 
public static FontFamily LoadFont(byte[] fontArray)
{
    int dataLength = fontArray.Length;
 
    IntPtr ptrData = Marshal.AllocCoTaskMem(dataLength);
    Marshal.Copy(fontArray, 0, ptrData, dataLength);
 
    uint cFonts = 0;
 
    AddFontMemResourceEx(ptrData, (uint) dataLength, IntPtr.Zero, ref cFonts);
    PrivateFontCollection pfc = new PrivateFontCollection();
    pfc.AddMemoryFont(ptrData, dataLength);
 
    Marshal.FreeCoTaskMem(ptrData);
    return pfc.Families[0];
}
 
public static FontFamily LoadFont(Stream fontStream)
{
    int dataLength = (int) fontStream.Length;
    byte[] fontArray = new byte[dataLength];
    fontStream.Read(fontArray, 0, dataLength);
 
    IntPtr ptrData = Marshal.AllocCoTaskMem(dataLength);
    Marshal.Copy(fontArray, 0, ptrData, dataLength);
 
    uint cFonts = 0;
 
    AddFontMemResourceEx(ptrData, (uint) fontArray.Length, IntPtr.Zero, ref cFonts);
    PrivateFontCollection pfc = new PrivateFontCollection();
    pfc.AddMemoryFont(ptrData, dataLength);
 
    Marshal.FreeCoTaskMem(ptrData);
    return pfc.Families[0];
}
 
private static void SetFont(FontFamily font, Control c, float size)
{
    const FontStyle fontStyle = FontStyle.Bold;
    c.Font = new Font(font, size, fontStyle);
}
 
public static Stream FromEmbedded(string path)
{
    Assembly assembly = Assembly.GetEntryAssembly();
    string name =
        assembly.GetManifestResourceNames().First(s => s.EndsWith(path, StringComparison.OrdinalIgnoreCase));
    return assembly.GetManifestResourceStream(name);
}

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎