Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading a font directly from a file in C#

Tags:

c#

.net

fonts

Is there a way to do something like this?

FontFamily fontFamily = new FontFamily("C:/Projects/MyProj/free3of9.ttf");

I've tried a variety of variations and haven't been able to get it to work.

UPDATE:

This works:

PrivateFontCollection collection = new PrivateFontCollection();
collection.AddFontFile(@"C:\Projects\MyProj\free3of9.ttf");
FontFamily fontFamily = new FontFamily("Free 3 of 9", collection);
Font font = new Font(fontFamily, height);

// Use the font with DrawString, etc.
like image 941
birdus Avatar asked Jun 03 '14 18:06

birdus


People also ask

How do I import a TTF file?

To install the TrueType font in Windows: Click on Start, Select, Settings and click on Control Panel. Click on Fonts, click on File in the main tool bar and select Install New Font. Select the folder where the font is located. The fonts will appear; select the desired font that is titled TrueType and click on OK.


1 Answers

This example shows how to add font from byte array - if font is stored in resources. It allows to add font from file too. Following code I am using on winforms:

It is little tricky, for loading TTF font from file you need to do this:

private PrivateFontCollection _privateFontCollection = new PrivateFontCollection();

public FontFamily GetFontFamilyByName(string name)
{
    return _privateFontCollection.Families.FirstOrDefault(x => x.Name == name);
}

public void AddFont(string fullFileName)
{
    AddFont(File.ReadAllBytes(fullFileName));
}   

public void AddFont(byte[] fontBytes)
{
    var handle = GCHandle.Alloc(fontBytes, GCHandleType.Pinned);
    IntPtr pointer = handle.AddrOfPinnedObject();
    try
    {
        _privateFontCollection.AddMemoryFont(pointer, fontBytes.Length);
    }
    finally
    {
        handle.Free();
    }
}
like image 57
user2126375 Avatar answered Oct 15 '22 22:10

user2126375