fontello / svg2ttf

SVG -> TTF font convertor
MIT License
518 stars 79 forks source link

Should not throw error on glyph without outline for U+0020 #124

Open btangmu opened 1 year ago

btangmu commented 1 year ago

svg2ttf fails if a glyph has no outline, that is, no 'd' attribute. For example, given this glyph:

<glyph unicode=" "/>

or, equivalently

<glyph unicode="&#x0020;" />

It should not be treated as an error. The space character (U+0020) can be included in a font. Some software (such as XeTeX) complains if a font does not contain it. There should be no requirement for this glyph (or any glyph), to have a 'd' attribute.

The bug is in this code:

function getGlyph(glyphElem, fontInfo) {
  var glyph = {};

  if (glyphElem.hasAttribute('d')) {
    glyph.d = glyphElem.getAttribute('d').trim();
  } else {
    // try nested <path>
    var pathElem = glyphElem.getElementsByTagName('path')[0];

    if (pathElem.hasAttribute('d')) {
      // <path> has reversed Y axis
      glyph.d = svgpath(pathElem.getAttribute('d'))
        .scale(1, -1)
        .translate(0, fontInfo.ascent)
        .toString();
    } else {
      throw new Error("Can't find 'd' attribute of <glyph> tag.");
    }
  }

First, since pathElem may be undefined, the condition should be if (pathElem && pathElem.hasAttribute('d')) or more briefly if (pathElem?.hasAttribute('d')) (with question mark) to prevent this error:

TypeError: Cannot read properties of undefined (reading 'hasAttribute')

Second, this line should be deleted: throw new Error("Can't find 'd' attribute of <glyph> tag.");