Search code examples
node.jsfontsopentype

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


I trying to create a font subset with opentype.js in node

my code

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()));

and I try to use sub.otf in browser;

but chrome is complaining the font file

OTS parsing error: cmap: Failed to parse table

(StackOverflow editor does not allow me to input Chinese characters in code block);

and I find this problem only happens when create glyph with non-latin characters.


Solution

  • I finnally find that the string pass to font.stringToGlyph has duplicated characters. I have to remove the dupcated ones by myself

    function rmDupChar(text) {
      return [...new Set(text.split(''))].join('');
    }
    
    let subfontGlyph = font.stringToGlyphs(rmDupChar('一大段文字中文字体子集'));