I’d like to convert a simple dynamic svg snippet into a PNG data URI on the server. Something like this:
var svg = \'
Take a look at svg-to-img.
It relies on headless Chrome under the hood to do the conversion.
To use svg-to-img in your project, run:
npm install svg-to-img
Here's how to convert a svg
to a base64-encoded png
:
const svgToImg = require("svg-to-img");
(async () => {
const svg = "<svg xmlns='http://www.w3.org/2000/svg'/>";
const png = await svgToImg.from(svg).toPng({ encoding: "base64" });
console.log("data:image/png;base64," + png);
})();
Disclaimer: I'm the author of svg-to-img.
Here's a way to do it using Fabric.js:
Step 1: Install Cairo and node-canvas:
(I'm on Ubuntu 14.04, instructions for other OSes can be found here.)
sudo apt-get update
sudo apt-get install libcairo2-dev libjpeg8-dev libpango1.0-dev libgif-dev build-essential g++
sudo npm install canvas
Step 2: Install Fabric.js:
sudo npm install fabric
Step 3: Run the following JavaScript with node
:
var fabric = require('fabric').fabric;
var canvas = new fabric.createCanvasForNode(100, 100);
var svgStr = '<svg height="100" width="100"><circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /></svg>';
fabric.loadSVGFromString(svgStr, function(objects, options) {
var obj = new fabric.PathGroup(objects, options);
canvas.add(obj);
console.log('<img src="' + canvas.toDataURL() + '" />');
});
Result:
(Ran on node v0.10.25.)
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAABmJLR0QA/wD/AP+gvaeTAAAHD0lEQVR4nO2dW2wVRRjHf6XSFgq1BUEoIiCXKih4jYmGxAR8MBa5RQloDD7wAA/og8EHfdAXEowm8oCGJxQviXhJjKkEUSgKeIkoohYLCCggt0JbwBah9vNhdnt2z57LbDl7dujOL/nSmZOzZ2e+/+52d+abb8FisVgsFovFYrFYLImmJO4GaDIAmAZMBCY5f8cCA4FKoBrVl26gHfgH6AAOAfsd2wfsATqL2/RwmCrINcB04AHH7gXKC/C7/wLfAo3AVmAH0FWA3+2TlAAzgfVAGyBFsFZnfzMx5OA0oRGlwALgOWBqpi+UAFOA24DJQJ1jg4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