Skip to main content

Generating webfonts with fontTools

Previously, I wrote a note on ways to convert ttf fonts to woff and woff2 formats. Unfortunately, those methods gave me mixed results when it comes to variable fonts. Many times, I found that axes were messed up after conversion.

In this post, I’ll use a more robust approach for font conversion using fontTools: a library for manipulating fonts.

Preparing a working environment

Let’s create a Dockerfile in a folder (say, fonttoolslab) to install required dependencies.

dockerfile
FROM python:alpine3.15

RUN apk add --no-cache --virtual .build-deps gcc g++
RUN pip install fonttools[woff]
RUN apk del .build-deps

To convert a bunch of ttf files, you can dump them into a folder (say, .workspace) and then invoke the following script.

python
woff2.py
import glob
import os
from fontTools.ttLib import TTFont

for filepath in glob.iglob('.workspace/*.ttf'):
	f = TTFont(filepath)
	f.flavor = 'woff2'
	print('INFO:fontTools.ttLib.woff2: Generating WOFF2 for ' + filepath)
	f.save(os.path.splitext(filepath)[0] + '.woff2')

This script loops over all the ttf files in the .workspace directory, and converts them into woff2 files.

Open terminal in the directory where you created the Dockerfile and woff2.py (that’s fonttoolslab) and run the following command to generate a Docker image.

sh
docker build -t fonttoolslab .

This will generate a Docker image fonttoolslab:latest.

Converting the files

Copy all your ttf files in the .workspace directory (create one if you haven’t).

Launch a Docker container as follows.

sh
docker run --rm -it -v ${pwd}:/fonts fonttoolslab sh

This will launch the container in interactive mode and you’ll land on a shell prompt. Run the following commands to finish the conversion.

sh
# cd /fonts
# python woff2.py

Open the .workspace folder on your machine. You’ll find a woff2 file corresponding to each ttf file. This method works for both static and variable fonts.