Day152 — convert SVG to PNG in JavaScript
I needed to convert an SVG image into a png one in a project. Here records the methods I tried.
My SVG uses a custom embedded font.
Method 1, using sharp
sharp(inputBuffer)
.resize(1000, 1000)
.png()
.toFile('output.png', (err, info) => { ... });
It only supports font installed in the OS. It can tricky to get the correct name for the font you installed. Even if I successfully make it to work on my Windows machine, I need to do that once again when I submit this code to a Linux Machine on AWS. It just does not worth my time.
Worst of all, it does not support embedded font. Sharp is using librsvg to render font, which is another whole system.
In summary, sharp does not cut it for my use case.
Method 2, using a headless browser
My SVG image is shown perfectly fine in any browser, Chrome, Firefox, and Edge. So, I think it could work if I use a headless browser to render the SVG in HTML, then screenshot the page into a PNG. It saves me a lot of hustle of setting up the env and loading the correct font.
Also, my SVG does not have a transparent background so the screenshot method works for me.