Search code examples
javascriptfontsgraphicstruetypeopentype

Converting OpenType / TrueType format to png images using NodeJS


I've been recently facing a problem.

I need to generate images from a font file otf/ttf using the following code application:

let font = loadFont("Verdana.ttf");
font.Generate("Hello world");

would output an image with Hello world written with the Verdana font. I've searched a bit and find the library opentype.js which can parse a font file but I don't really understand what to do for the next steps, there is a lot of data and I don't know which one can be used to do what I need.

I don't really know where to start to be honest, if someone have keywords or something else that might be useful for me, i'd be glad to know.

Thank you.


Solution

  • Rather than using something like node-canvas (which is the best canvas emulation for Node, but also requires compilation-at-install-time with a hard dependency on GTK), you can just ask OpenType.js to typeset the text and then get the SVG for that:

    const font = opentype.load('yourfonthere');
    const yourString = `.....`;
    const path = font.getPath(yourString, 0, 0);
    const pathElementString = path.toSVG();
    

    You can then put that path in an SVG document:

    const { x1, x2, y1, y2 } = path.getBoundingBox();
    const w = x2 - x1;
    const h = y2 - y1;
    const svgDocument = `<svg width="${w}" height="${h}" viewBox="${x1} ${y1} ${w} ${h}">
      ${pathElementString}
    </svg>`;
    

    And now you have an SVG file that you can either keep in memory or write to disk.

    Going from SVG to PNG then becomes a matter of "using any of quite a lot of possible tools, both node based (e.g. convert-svg-to-png) or CLI-based", because you can always set up a folder watcher that looks for new SVG files being put in a folder/dir (either as part of your npm scripts, or as independent system task), or you can make your code trigger an exec or spawn after writing your file to disk.

    (just remember that if you go the CLI route, you're almost certainly locking your code into one specific OS, so... less advised. That said, it's always important to remember that just because you're using Node, you don't have to make Node do everything. Writing a file to disk, and then using a vastly superior CLI utility to cover one or more of the last steps is a perfectly valid programming approach)