Skip to content

Instantly share code, notes, and snippets.

@Ashung
Last active March 6, 2023 23:08
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ashung/7cbed68bdaab918fd01ff73ea1c2ab75 to your computer and use it in GitHub Desktop.
Save Ashung/7cbed68bdaab918fd01ff73ea1c2ab75 to your computer and use it in GitHub Desktop.
Subset font use opentype.js
{
"fonts": ["./src/NotoSerifSC-Bold.otf"],
"texts": " 0123456789:年月日时分秒公元农历腊零初一二三四五六七八九十廿甲乙丙丁戊己庚辛壬癸子丑寅卯辰巳午未申酉戌亥立春雨水惊蛰春分清明谷雨立夏小满芒种夏至小暑大暑立秋处暑白露秋分寒露霜降立冬小雪大雪冬至小寒大寒"
}
const config = require('./config.json');
const fonts = config.fonts;
const texts = config.texts;
const path = require('path');
const opentype = require('opentype.js');
const glyphs = [...new Set(texts.split(''))].join('');
fonts.forEach(item => {
const font = opentype.loadSync(item);
const postScriptName = font.getEnglishName('postScriptName');
const dist = path.join(
'dist',
postScriptName.replace(/-/g, '_').toLowerCase() + '_subset.otf'
);
const [familyName, styleName] = postScriptName.split('-');
const notdefGlyph = font.glyphs.get(0);
notdefGlyph.name = '.notdef';
subGlyphs = [notdefGlyph].concat(font.stringToGlyphs(glyphs));
const subsetFont = new opentype.Font({
familyName: familyName,
styleName: styleName,
unitsPerEm: font.unitsPerEm,
ascender: font.ascender,
descender: font.descender,
designer: font.getEnglishName('designer'),
designerURL: font.getEnglishName('designerURL'),
manufacturer: font.getEnglishName('manufacturer'),
manufacturerURL: font.getEnglishName('manufacturerURL'),
license: font.getEnglishName('license'),
licenseURL: font.getEnglishName('licenseURL'),
version: font.getEnglishName('version'),
description: font.getEnglishName('description'),
copyright: 'This is a subset font of ' + postScriptName + '. ' + font.getEnglishName('copyright'),
trademark: font.getEnglishName('trademark'),
glyphs: subGlyphs
});
subsetFont.download(dist);
});
@OnCloud125252
Copy link

您好,在其他論壇中幾乎找不到類似的程式,猜測是因為幾乎只有中文使用者有這方面的需求。
而我後來看到了你發表的文章,內容幫助了我很多,謝謝。

由於您使用 common js 的寫法,而我因為專案需求,要使用 ES6 的寫法,於是我根據您的程式寫了一個 ES6 的版本

另外,我也順手完成了適用於 Next.js API 的版本,將原本直接載入字體檔的方式改為請求字體檔的 API,API 負責根據所需文字處理完字體後,回傳精簡版本的字體檔。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment