How to embed fonts in C# applications

luca 04/10/2013 0

I’m developing an application that will use custom fonts: you can avoid installing the fonts to the user’s PC embedding them in your app and loading at runtime: this tutorial explains how to do it…


Copy the font file in the project’s folder:

In my example I chose the Always Forever font by Brittney Murphy.

Add the file to your project with Add – Existing Item… and choosing your font:

Set Embedded Resource as Build Action:


First, configure the project allowing unsafe code:

Create an instance of the PrivateFontCollection object that will keep your font when you load in memory:

private PrivateFontCollection pfc = new PrivateFontCollection();

Read the file content and save it in the fontdata byte array:

Stream fontStream = this.GetType().Assembly.GetManifestResourceStream("EmbeddingFontDemo.always_forever.ttf");
byte[] fontdata = new byte[fontStream.Length];
fontStream.Read(fontdata, 0, (int)fontStream.Length);

Next, add the font to the PrivateFontCollection object; you need to use a pointer therefore you must surround the call with an unsafe block:

    fixed (byte* pFontData = fontdata)
      pfc.AddMemoryFont((System.IntPtr)pFontData, fontdata.Length);

To be able to use the font in a control, set the control’s UseCompatibleTextRendering property to true:

You can now apply your font to the control:

label1.Font = new Font(pfc.Families[0], 30, FontStyle.Regular);


I created a VisualStudio project to demonstrate what is explained above; the project is available in my GitHub’s repository.

Leave A Response »

This website uses cookies to ensure you get the best experience on our website maggiori informazioni

Questo sito utilizza i cookie per fonire la migliore esperienza di navigazione possibile. Continuando a utilizzare questo sito senza modificare le impostazioni dei cookie o clicchi su "Accetta" permetti al loro utilizzo.