10

Once again I need your help.

I'm developing a small application on C# that uses a custom Font. The problem is, the font must be installed previously on the system. If the font is not present in the system it just uses Times New Roman. Is there any way to embed the font file in the application so it doesn't need to be installed in every system?

Thank you.

user295744
  • 341
  • 2
  • 5
  • 19
  • Possible duplicates: http://stackoverflow.com/questions/2288246, http://stackoverflow.com/questions/3007805/embedding-deploying-custom-font-in-net-app, http://stackoverflow.com/questions/556147/how-to-quickly-and-easily-embed-fonts-in-winforms-app-in-c – Cody Gray - on strike Dec 10 '10 at 17:03

2 Answers2

9

If you're still reading this, I might point out that you don't have to use unsafe code to load the font from a resource. Here's an example using Marshal.

PrivateFontCollection _fonts = new PrivateFontCollection();

byte[] fontData = Resources.CustomFontResourceName;

IntPtr fontPtr = Marshal.AllocCoTaskMem(fontData.Length);

Marshal.Copy(fontData, 0, fontPtr, fontData.Length);

_fonts.AddMemoryFont(fontPtr, fontData.Length);

Marshal.FreeCoTaskMem(fontPtr);

Font customFont = new Font(_fonts.Families[0], 6.0F);
Shibumi
  • 1,369
  • 9
  • 24
  • The article that the accepted answer links to explains that this is an option, both for VB.NET programmers and for those who don't want to use `unsafe` in C#. – Cody Gray - on strike Dec 11 '10 at 10:20
  • @Cody Then, I suppose, here is an example :). – Shibumi Dec 17 '10 at 14:06
  • when I use this approach to load fonts on my development machine it only works with .ttf fonts and not with .otf fonts. When I deploy my website to the cloud (windows azure) it only works with .otf fonts and not with .ttf fonts. How can this be? – fireydude Jul 10 '13 at 12:00
  • December 2010 was a long time ago! My only guess would be different .NET versions/flavors/configurations? Different OS settings? I think you might just have another question, rather than a comment to this one :). Good luck! – Shibumi Aug 05 '13 at 22:11
1

Note that if you use AddMemoryFont, you will need to use this api call "AddFontMemResourceEx" or it wont work.

PrivateFontCollection giving me symbols

Community
  • 1
  • 1
Will
  • 10,013
  • 9
  • 45
  • 77