Search code examples
python-3.xfontsttx-fonttools

How to use fontTools to detect Type 1 and OpenType CFF fonts


I know that it's possible to detect Type 1 and OpenType CFF (“PostScript flavored OpenType”) fonts by checking the first 4 bytes for 'OTTO' (0x4F54544F).

How would I do this in Python with the fontTools library? I.e., which font table would I need to check for this value?


Solution

  • The version is stored in the font file header, not in a font data table. If you have a ttLib.TTFont object (i.e. you've opened a font file with fontTools), you can look at the .sfntVersion attribute of your TTFont object to get the version (which will usually be either 0x00010000/Version 1 or 0x4F54544F/OTTO, but there are other possible values, see below). But that kind of assumes you've already created a TTFont object by opening a font file, so this might be a kind of chicken-and-egg issue. If you're interested in knowing the version before you attempt to open the file/create a TTFont, you'll have to sniff the first four bytes (at least), outside of fontTools.


    Note: I'm a little confused by your question. You mention Type 1, which is indeed a kind of PostScript font, but not (usually) the kind in OpenType/sfnt-housed fonts (that would be Type 2, "Compact Font Format", or CFF). There is supposedly a way to store Type 1 in OpenType/sfnt-housed fonts; Apple mentions this in their TrueType Reference manual:

    The values 'true' (0x74727565) and 0x00010000 are recognized by OS X and iOS as referring to TrueType fonts. The value 'typ1' (0x74797031) is recognized as referring to the old style of PostScript font housed in a sfnt wrapper. The value 'OTTO' (0x4F54544F) indicates an OpenType font with PostScript outlines (that is, a 'CFF ' table instead of a 'glyf' table). Other values are not currently supported.

    So if typ1 is in fact what you're asking about, you could look for 0x74797031/"typ1" in the first four bytes of the file. But actual typ1 sfnt-housed fonts are exceedingly rare -- like almost non-existent. The overwhelming majority of actual Type 1 fonts will be in either .PFA/.PFB files (for non-Mac platforms), or in a "Printer Font" file (pre-OS X Mac), which would be paired with the old resource-fork "suitcase" file containing bitmaps. Type 1 font files will have %!PS-AdobeFont-1 as the first bytes of the file.