Search code examples
.netfiletruetype

Create subset of a TrueType font file using .NET


I am trying to achieve following things:

  1. To create subset of original font file which targets only specific characters
  2. After browsing through Google I came across following APIs available:
    • ComputeSubset method of GlyphTypeface class in WPF
    • CreateFontPackage in FontSub.dll
  3. Though I am able to create subset a of a font file, I am not sure whether it is targetting the characters which I have specified because when I open that file (double click on file), I see all characters there. How exactly can I validate that? I installed that in c:\windows\fonts, and I am able to type all characters in that font whereas I was expecting it will only show characters which I selected.
  4. is there a programmer's reference for TrueType font (TTF) files which help us understand TTF files from a programming perspective?

Solution

  • I've used both methods you mention, the first one is far easier. Here's the code I use:

    Imports System.Text.Encoding
    Imports System.Collections
    Imports System.Windows.Media
    Public Class FontManager
        Sub New()
            CreateSubSet("my baloney has a first name", New Uri("C:\Windows\Fonts\impact.ttf"))
        End Sub
        Public Sub CreateSubSet(sourceText As String, fontURI As Uri)
            Dim glyphTypeface As GlyphTypeface = New GlyphTypeface(fontURI)
            Dim Index As Generic.ICollection(Of UShort)
            Index = New Generic.List(Of UShort)
            Dim sourceTextBytes As Byte() = Unicode.GetBytes(sourceText)
            Dim sourceTextChars As Char() = Unicode.GetChars(sourceTextBytes)
            Dim sourceTextCharVal As Integer
            Dim glyphIndex As Integer
            For sourceTextCharPos = 0 To UBound(sourceTextChars)
                sourceTextCharVal = AscW(sourceTextChars(sourceTextCharPos))
                glyphIndex = glyphTypeface.CharacterToGlyphMap(sourceTextCharVal)
                Index.Add(glyphIndex)
            Next
            Dim filebytes() As Byte = glyphTypeface.ComputeSubset(Index)
            Using fileStream As New System.IO.FileStream("C:\Users\Me\Documents\impact-subset.ttf", System.IO.FileMode.Create)
                fileStream.Write(filebytes, 0, filebytes.Length)
            End Using
        End Sub
    End Class
    

    Of course for sourceText, you can just send in unique characters if you want.

    The link gilamesh mentions is a great place for learning about TTF fonts. The other reference which I've found to be invaluable is http://developer.apple.com/fonts/TTRefMan/RM06/Chap6.html