Advertisement
Brick

C# Font Embedding

Aug 30th, 2015
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.68 KB | None | 0 0
  1. [DllImport("gdi32.dll")]
  2. private static extern IntPtr AddFontMemResourceEx(IntPtr pbPurista, uint cbPurista, IntPtr pdv,
  3.     [In] ref uint pcFonts);
  4.  
  5. public static FontFamily LoadFont(byte[] fontArray)
  6. {
  7.     int dataLength = fontArray.Length;
  8.  
  9.     IntPtr ptrData = Marshal.AllocCoTaskMem(dataLength);
  10.     Marshal.Copy(fontArray, 0, ptrData, dataLength);
  11.  
  12.     uint cFonts = 0;
  13.  
  14.     AddFontMemResourceEx(ptrData, (uint) dataLength, IntPtr.Zero, ref cFonts);
  15.     PrivateFontCollection pfc = new PrivateFontCollection();
  16.     pfc.AddMemoryFont(ptrData, dataLength);
  17.  
  18.     Marshal.FreeCoTaskMem(ptrData);
  19.     return pfc.Families[0];
  20. }
  21.  
  22. public static FontFamily LoadFont(Stream fontStream)
  23. {
  24.     int dataLength = (int) fontStream.Length;
  25.     byte[] fontArray = new byte[dataLength];
  26.     fontStream.Read(fontArray, 0, dataLength);
  27.  
  28.     IntPtr ptrData = Marshal.AllocCoTaskMem(dataLength);
  29.     Marshal.Copy(fontArray, 0, ptrData, dataLength);
  30.  
  31.     uint cFonts = 0;
  32.  
  33.     AddFontMemResourceEx(ptrData, (uint) fontArray.Length, IntPtr.Zero, ref cFonts);
  34.     PrivateFontCollection pfc = new PrivateFontCollection();
  35.     pfc.AddMemoryFont(ptrData, dataLength);
  36.  
  37.     Marshal.FreeCoTaskMem(ptrData);
  38.     return pfc.Families[0];
  39. }
  40.  
  41. private static void SetFont(FontFamily font, Control c, float size)
  42. {
  43.     const FontStyle fontStyle = FontStyle.Bold;
  44.     c.Font = new Font(font, size, fontStyle);
  45. }
  46.  
  47. public static Stream FromEmbedded(string path)
  48. {
  49.     Assembly assembly = Assembly.GetEntryAssembly();
  50.     string name =
  51.         assembly.GetManifestResourceNames().First(s => s.EndsWith(path, StringComparison.OrdinalIgnoreCase));
  52.     return assembly.GetManifestResourceStream(name);
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement