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.
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.
import glob
import os
from fontTools.ttLib import TTFont
for filepath in glob.iglob('.workspace/*.ttf'):
= TTFont(filepath)
f = 'woff2'
f.flavor print('INFO:fontTools.ttLib.woff2: Generating WOFF2 for ' + filepath)
0] + '.woff2')
f.save(os.path.splitext(filepath)[
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.
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.
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.
# 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.
- Thanks to Rosalie Wagner for pointing out that I can use fontTools for such conversions.
- I used the same approach to generate variable webfonts for JetBrainsMono.