Google FontTools - Convert fonts to different formats (TTF, WOFF, WOFF2)
I wanted a way to convert fonts to different formats without having to rely on online tools - it shouldn't be really hard - I guessed. And luckily, it isn't. :)
Install FontTools
Google has released an opensource font conversion program which we'll use. We'll need python, pip and some libraries - so, let's get them first.
Install python (v3)
Download and install python3
:
- Windows (if you use WSL, see Linux installation, else: python.org/downloads/windows)
- Mac (use homebrew - recommended, or get it here: python.org/downloads/mac-osx)
- Linux (Debian-based -
apt install python3
)
Verify installation:
$ python3 --version
Python 3.8.5 # <-- expected output
Install pip (v3)
- Linux and Mac:
$ python3 -m pip --version
- Windows:
C:\> py -m pip --version
See: pip.pypa.io/en/stable/installing
Verify installation:
$ pip --version
pip 20.0.2 from /usr/lib/python3/dist-packages/pip (python 3.8) # <-- output
Install FontTools and brotli
FontTools:
$ pip install fonttools
Collecting fonttools
Downloading fonttools-4.21.1-py3-none-any.whl (849 kB)
|████████████████████████████████| 849 kB
Installing collected packages: fonttools
Successfully installed fonttools-4.21.1
brotli
$ pip install brotli
Collecting brotli
Downloading Brotli-1.0.9-cp38-cp38-manylinux1_x86_64.whl (357 kB)
|████████████████████████████████| 357 kB
Installing collected packages: brotli
Successfully installed brotli-1.0.9
Download NotoSans
We test with NotoSans, a pretty heavy font, which makes the compressed sizes easy to compare.
Download the font from here: google.com/get/noto and decompress the contents.
We use the python3
REPL to try this out:
$ cd /path/NotoSans
$ python3
Python 3.8.5 (default, Jan 27 2021, 15:41:15)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from fontTools.ttLib import TTFont
>>> f = TTFont('NotoSans-Regular.ttf')
>>> f.flavor='woff2'
>>> f.save('NotoSans-Regular.woff2')
>>> f.flavor='woff'
>>> f.save('NotoSans-Regular.woff')
>>> exit()
Verify converted files:
ls -alh
rwxr-xr-x 2 manoj manoj 4 KiB Sat Mar 13 13:35:12 2021 ./
rwxr-xr-x 16 manoj manoj 4 KiB Sat Mar 13 14:17:12 2021 ../
rw-r--r-- 1 manoj manoj 444 KiB Wed Sep 20 17:20:30 2017 NotoSans-Regular.ttf
rw-r--r-- 1 manoj manoj 233 KiB Sat Mar 13 13:35:13 2021 NotoSans-Regular.woff
rw-r--r-- 1 manoj manoj 163 KiB Sat Mar 13 13:34:54 2021 NotoSans-Regular.woff2
As you see, woff2 provides the best compression for usage on the web, as long as you don't have to support IE. Check browser support here: caniuse.com/?search=woff2