birdus
birdus

Reputation: 7504

Loading a font directly from a file in C#

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.

Upvotes: 23

Views: 26987

Answers (3)

MiMFa
MiMFa

Reputation: 1164

I modified the @user2126375`s trick as follows:

public PrivateFontCollection FontCollection = new PrivateFontCollection();
public FontFamily AddToFontCollection(string path)
    => AddToFontCollection(File.ReadAllBytes(path));
public FontFamily AddToFontCollection(byte[] fontBytes)
{
    var handle = System.Runtime.InteropServices.GCHandle.Alloc(fontBytes, System.Runtime.InteropServices.GCHandleType.Pinned);
    IntPtr pointer = handle.AddrOfPinnedObject();
    try
    {
        FontCollection.AddMemoryFont(pointer, fontBytes.Length);
    }
    finally
    {
        handle.Free();
    }
    return FontCollection.Families.LastOrDefault();
}

Enjoy...

Upvotes: 1

user2126375
user2126375

Reputation: 1614

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();
    }
}

Upvotes: 15

bsguedes
bsguedes

Reputation: 791

This piece of code works for me (WPF):

FontFamily fontFamily = new FontFamily(@"C:\#FONTNAME")

In your example, it would be:

FontFamily fontFamily = new FontFamily(@"C:\Projects\MyProj\#free3of9");

The font name without the file extension, and keep the '#' symbol.

Upvotes: 11

Related Questions