Fonttools looks like a good option in Python: https://github.com/fonttools/fonttools
A Node.js one: https://github.com/foliojs/fontkit claims usage:
var fontkit = require('fontkit');
// open a font synchronously
var font = fontkit.openSync('font.ttf');
// layout a string, using default shaping features.
// returns a GlyphRun, describing glyphs and positions.
var run = font.layout('hello world!');
// create a font subset
var subset = font.createSubset();
run.glyphs.forEach(function(glyph) {
subset.includeGlyph(glyph);
});
subset.encodeStream()
.pipe(fs.createWriteStream('subset.ttf'));
TODO learn how to use it icon fonts like font awesome. You can get the Unicode character used for each glyph easily from their website: https://fontawesome.com/icons/comment?s=regular but also of course form distro files, e.g. npm install --save-dev fontawesome-free@1.0.4
we see at node_modules/fontawesome-free/css/all.css
.fa-comment:before {
content: "\f075"; }
I tried somthing along:
const fs = require('fs');
const path = require('path');
const fontkit = require('fontkit');
const EXT = '.woff2'
const glyphs = {
'fa-solid-900': [
'\u{f03a}',
'\u{f042}',
'\u{f062}',
'\u{f0c1}',
'\u{f111}',
'\u{f02c}',
],
'fa-regular-400': [
'\u{f075}',
],
'fa-brands-400': [
'\u{f266}',
],
}
for (const fontname in glyphs) {
const font_basename = fontname + EXT
const font = fontkit.openSync(path.join('node_modules', 'fontawesome-free', 'webfonts', font_basename));
const subset = font.createSubset();
for (const glyph of font.glyphsForString(glyphs[fontname].join(''))) {
subset.includeGlyph(glyph);
}
subset.encodeStream().pipe(fs.createWriteStream(path.join('dist', font_basename)));
}
and it did produce e.g. fa-solid-900.woff2
, but that font file did not work for me for some reason, the glyphs weren't showing. Also it was much larger than the original font file, at 405K rather than 77K for the original. Tested at:
"fontawesome-free": "1.0.4",
"fontkit": "1.8.1",
Browser shows error:
Failed to decode downloaded font: dist/fa-solid-900.woff2
tmp.html#tmp-2:1
OTS parsing error: hhea: misaligned table
The same happens when I try with the TTF versions.
Maybe also consider: https://github.com/omacranger/fontawesome-subset which auto extracts. But it doesn't auto extract the corresponding CSS as well it seems, just the fonts? Tested at "fontawesome-subset": "3.0.0"
, I notice that that package requires building native dependencies which is a downside. Then I tried a hello world and that failed: https://github.com/omacranger/fontawesome-subset/issues/16#issuecomment-1046822754