PostScript Metrics & Kerning with PHP/GD

So you want to render a nice PostScript Type 1 font (.pfb/.pfa) using PHP+GD. Sadly, you just realized you can’t load the associated font metrics (.pfm/.afm) in PHP.

The “afm” (ASCII) and “pfm” (Binary) metric files contain, amongst other things, the metrics and the kerning information about the font. To render a font correctly, both the font and the metrics are required.

Freetype2 supports metrics, but you have to load them up “manually”, using the FT_Attach_Stream() or FT_Attach_File() functions. Sadly GD (and PHP) knows nothing about PostScript metric files.

I used to include basic pfm/afm functionalities in my Better Freetype2 patch for PHP 3 & 4, but it’s gone now, being too ugly.

A better approach is to convert the font to OpenType.

As you might know, a Type 1 font has cubic curves (Bézier), a simple hinting system, and requires 2 files. On the other hand a TrueType font is based on quadratic curves (requiring more points), has a more powerful hinting system (and so generally better looking screen rendering) and places everything in a single file.

An OpenType font file is essentially a Type 1 font in a TrueType file.

Using Fontlab’s TransType or FontLab Studio is quite a painless (and non-free) process: you load your .pfb file in FontLab Studio, then you export it in OpenType format. (The metric file is automatically imported if it resides in the same directory)

Using FontForge is uglier (visually speaking :), but free and Linux-compatible. The process is similar to FLS above, but when exporting, you should select the “OpenType (CFF)” format and, in the Options tab, check “Apple”.

If you want, you can also create a script for FontForge (see FontForge’s Scripting Tutorial) to convert your fonts from the command line.

You can now use the new OpenType file to turn this:

Into this:

(This is Bitstream Charter Bold)