iTextSharp: Turn any Font into a BaseFont

The excellent iTextSharp library requires that you pass a BaseFont object into many of its methods. There are only a handful of hardcoded BaseFont fonts available:

BaseFont.COURIER
BaseFont.HELVETICA
BaseFont.TIMES_ROMAN

However, you can turn any font in the system’s Fonts folder into a BaseFont. Here is the usage:

public void DoSomething()
{
    string fontName = "Algerian";
    float fontSize = 12;

    RegisterBaseFont(fontName);

    BaseFont baseFont = FontFactory.GetFont(fontName).BaseFont;
}

private void RegisterBaseFont(string fontName, float fontSize)
{
    if (!FontFactory.IsRegistered(election.OverlayFontName))
    {
        string path = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
            GetSystemFontFileName(new Font(new FontFamily(fontName), fontSize)));

        FontFactory.Register(path);
    }
}

private static string GetSystemFontFileName(Font font)
{
    string fontname = font.Name + " (TrueType)";
    RegistryKey fonts = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows NT\CurrentVersion\Fonts", false);

    if (fonts != null)
    {
        return
            (from fntkey in fonts.GetValueNames()
                where fntkey == fontname
                select fonts.GetValue(fntkey).ToString())
                .FirstOrDefault();
    }

    fonts = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Fonts", false);

    if (fonts == null)
    {
        throw new Exception("Can't find font registry database.");
    }

    return
        (from fntkey in fonts.GetValueNames() where fntkey == fontname select fonts.GetValue(fntkey).ToString())
            .FirstOrDefault();
}
Tagged on: ,

Leave a Reply

Your email address will not be published. Required fields are marked *