I’ve been using canvg in the past to convert SVG to PNG, but as you’ll see from the link, it doesn’t support all of SVG capabilities. If you use D3 or any library that likes to work in SVG, then you may come across something that doesn’t work – in my case it was textPath.

SVG provides the capability for drawing text along an arbitrary path, and I needed to do this in my Chord Snip add-on, but I didn’t have any way to take that generated SVG and create an image that Google Sheets could use as an embedded image.
Ideally then, I’d like to use the browser to render the SVG instead of canvg, then somehow get at the rasterized result to make a png image out of it, then pass it to Google Sheets. Here’s how.
The Dom has an API method to create an object – createObjectURL(svgtext). The API differs from browser to browser, but here’s how to find it.

The idea is to create that object from the svg code, load it to an image element, then write that image to canvas. We can then use toDataURL() to make a base64 encoded PNG image and we’re done.
First step is to create the url, but that will fail unless the svg code has its namespace defined, so we’ll poke the svg code

make a blob

and then create the URL from the blob

next we’ll need a canvas, but we need to deduce the canvas size required by digging around in the svg code.

now we can create a canvas element to temporarily use. I’m also going allow some margin space to be passed over as an argument, so the canvas will need to big enough for the image plus any padding round it.

I’ll need a new image, and when it’s loaded, I can write it to my canvas. As an additional piece of sugar, I’ll allow the image to have an optional background fill – useful if you have a margin or transparent input. If it does have one, then I need a second canvas that can be used to styling to which the first one is written. The whole thing is wrapped in a promise, so it can be resolved passing over the toDataUrl() of the final canvas representation of the svg image.

The whole thing can be used like this.

The code

I’ll report on browser compatibility as I try them out, or let me know if you try them out.

For more like this see Google Apps Scripts Snippets
Why not join our forum, follow the blog or follow me on twitter to ensure you get updates when they are available.