How can I remove glyphs from a WOFF?
Asked Answered
H

1

13

Are there any javascript libraries that can shrink a WOFF (and WOFF2) font down to only the glyphs used in an SVG image? For example, given a font and an array of strings it will return the bare minimum font needed to display those strings.

My first thought was to use SVG fonts which would be relatively simple but unfortunately they aren't supported in most browsers. WOFF and WOFF2 are well supported and are becoming the standard but so far I've not had any luck finding a library that suits my needs.

Hohenstaufen answered 24/1, 2015 at 22:12 Comment(0)
T
0

What you are looking for is a font subsetter. It will return a new font file to you that only has the required characters and kerning pairs. This can be quickly done with subset-font.

// npm i subset-font
const subsetFont = require('subset-font');

const mySfntFontBuffer = Buffer.from(/*...*/);

// Create a new font with only the characters required to render "Hello, world!" in WOFF2 format:
const subsetBuffer = await subsetFont(mySfntFontBuffer, 'Hello, world!', {
  targetFormat: 'woff2',
});

That being said, more powerful/flexible libraries exist such as fontkit. You might want this if you are looking for more complicated edits.

// npm install fontkit
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);
});

let buffer = subset.encode();
Tien answered 11/3, 2023 at 6:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.