create fonts subset using opentype.js getting "OTS parsing error: cmap: Failed to parse table" error

create fonts subset using opentype.js getting "OTS parsing error: cmap: Failed to parse table" error

我试图在节点

中使用opentype.js创建一个字体子集

我的代码

const fs = require('fs');
const opentype = require('opentype.js');

let font = opentype.loadSync('./SourceHanSansCN-Heavy.otf');
let subfontGlyph = font.stringToGlyphs('一大段文字中文字体子集');

let subfont = new opentype.Font({
  familyName: 'SourceHanSansCN-Heavy',
  styleName: 'Heavy',
  unitsPerEm: font.unitsPerEm,
  ascender: font.ascender,
  descender: font.descender,
  glyphs: subfontGlyph
});


fs.writeFileSync('./sub.otf', Buffer.from(subfont.toArrayBuffer()));

我尝试在浏览器中使用 sub.otf

但是chrome 抱怨字体文件

OTS parsing error: cmap: Failed to parse table

(Whosebug编辑器不允许我在代码块中输入汉字);

我发现只有在使用 非拉丁语 字符创建字形时才会出现此问题。

我终于发现传递给font.stringToGlyph的字符串有重复的字符。我必须自己删除重复的

function rmDupChar(text) {
  return [...new Set(text.split(''))].join('');
}

let subfontGlyph = font.stringToGlyphs(rmDupChar('一大段文字中文字体子集'));