Loading custom fonts

You can supply a font with your application if it's not commonly installed on the target platform. You should ensure you have a license to distribute the font -- the terms are often specified within the font file itself, and can be viewed with your operating system's font viewer.

Loading a custom font must be performed in two steps:

  1. Let pyglet know about the additional font or font files.
  2. Load the font by its family name.

For example, let's say you have the Action Man font in a file called action_man.ttf. The following code will load an instance of that font:

action_man = pyglet.font.load('Action Man')

Similarly, once the font file has been added, the font name can be specified as a style on a label or layout:

label = pyglet.text.Label('Hello', font_name='Action Man')

Fonts are often distributed in separate files for each variant. Action Man Bold would probably be distributed as a separate file called action_man_bold.ttf; you need to let pyglet know about this as well:

action_man_bold = font.load('Action Man', bold=True)

Note that even when you know the filename of the font you want to load, you must specify the font's family name to pyglet.font.load.

You need not have the file on disk to add it to pyglet; you can specify any file-like object supporting the read method. This can be useful for extracting fonts from a resource archive or over a network.

If the custom font is distributed with your application, consider using the Application resources.

Supported font formats

pyglet can load any font file that the operating system natively supports. The list of supported formats is shown in the table below.

Font Format Windows XP Mac OS X Linux (FreeType)
TrueType (.ttf) X X X
PostScript Type 1 (.pfm, .pfb) X X X
Windows Bitmap (.fnt) X   X
Mac OS X Data Fork Font (.dfont)   X  
OpenType (.ttf) [8]   X  
X11 font formats PCF, BDF, SFONT     X
Bitstream PFR (.pfr)     X
[8]All OpenType fonts are backward compatible with TrueType, so while the advanced OpenType features can only be rendered with Mac OS X, the files can be used on any platform. pyglet does not currently make use of the additional kerning and ligature information within OpenType fonts.