Use custom font with nodeJs and svgToPng

420 views Asked by At

I'm trying to convert an SGV to PNG using the library svgToPng

This works great, other than the custom Google font I am using does not display properly.

What should look like this

enter image description here

Instead instead looks like this

enter image description here

Here is the complete code which includes the font as a base64 string, this renders fine in a browser, but when ran on nodeJS does not work. I've also tried having the font files with relative and absolute paths to the Google CDN, both of which do the same result.

I am wanting to run this as an Azure Function, so the option to install the font on my machine isn't an option which I have seen before in others answers.

var svgString = `<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="800" height="800"><defs></defs><style>@font-face { font-family: 'Dokdo'; src: url(data:application/font-woff2;charset=utf-8;base64,d09GMgABAAAAABuoABAAAAAAK8QAABtHAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP0ZGVE0cGh4GYACDMghQCYRlEQgKvhS1WgtoAAE2AiQDgUwEIAWERgeCDgyDDBsIJlWHetg4ADaanzaiSjO17P8vB9oYIdgOfWslQhFl46MeYe1BQd/s6H6DPesiYMP1FmdPnaEMj2I53ZLZCG1iOA5ORFuUJYzHruWKYtXF/284/jmHlFBS5zDajU0X774uh1/FUOPd+nwy1duuklSh4Becj5BkFuKxjndekt0vqu3J0AkyJnVWUuwAW3bYATmAyirrLHk3C5RFso8QcvfctKR/LvNcAfp5+iua735ugLYZHBwZcqSEWAEWJq3gEJExZViIhYkRxSrCrXUVbu2i3+2jyv9v7XUmxDsbhIWzf0I0SYpg63IqKzwL2VMl732zW1K6wrwio0xXyPDiVl5hcwwRbf29/VBnJSX3pNntbIUWKEALTDfSLBxBUzw5rdPa8SFC+VXx8X+4pnubTJZ1N2EnDHvWU6axd7aIEEAmXMC4wIOL/P/261fvvP1yvxhJTEOxzCFEK+UJMnNn//mDz6LD+8juYvMwfaikSIim3kQz8VMhdELIlESnJeD7uum9mduZ4H5rB8TpffCmSuIgCQRr2W8fUfasB1gjnPd1y3C6MjNuQsU2RENablIHkCxX3+rOHJocP18wq/rW2+FFlcJVMP82FYKQLQ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rHGTNyFMqHuSal2yWHpf/9kuFUrfj5dsVzbVAd4sz3N9iesgszxjbS+B4v831meTN13/aj/YKAAAA) format('woff2');    font-weight: normal;    font-style: normal;}</style><g><rect fill="rgb(80,80,80)" stroke="none" x="0" y="0" width="150" height="70"></rect><text fill="rgb(255,255,255)" font-family="Dokdo" font-size="50px" x="10" y="50">TEST</text></g></svg>`;

var buffer = await svg2png(Buffer.from(svgString));
var result = await buffer.toString("base64");
console.log(result);
1

There are 1 answers

1
S. Esteves On

If your SVG contains text and used on an <img> tag, web fonts will not render on all browsers due to security reasons, and will be displayed using system fonts (mostly Times New Roman).

You must embed the fonts first. Try https://vecta.io/nano to compress your SVG and download it as PNG. If it doesn't embed your fonts, use Sketch, Photoshop, ... to vectorize the font first.