Home

Awesome

saveSvgAsPng

Installation

npm install save-svg-as-png

Prerequisites

SaveSvgAsPng relies on JavaScript promises, so any browsers that don't natively support the standard Promise object will need to have a polyfill.

Usage

To save a PNG, include the script saveSvgAsPng.js in your page, then call the saveSvgAsPng function with an SVG node and a filename:

saveSvgAsPng(document.getElementById("diagram"), "diagram.png");

The filename is the preferred filename when saving the image to the file system. The browser may change the name of the file if there is already a file by that name in the target directory.

If you want to scale the image up or down, you can pass a scale factor in an options object:

saveSvgAsPng(document.getElementById("diagram"), "diagram.png", {scale: 0.5});

Other options are documented below.

If you just want a dataURI for an SVG, you can call svgAsDataUri, which returns a promise:

svgAsDataUri(document.getElementById("diagram"), options).then(uri => ...);

If you want a dataURI of a PNG generated from an SVG, you can call svgAsPngUri, which also returns a promise:

svgAsPngUri(document.getElementById("diagram"), options).then(uri => ...);

Compatible with browserify and requirejs.

If you want to use TypeScript, necessary type definitions are available in Typings public registry.

Options

Testing

run tests with tape

npm test

Support

Chrome limits data URIs to 2MB, so you may have trouble generating PNGs beyod a certain size.

Internet Explorer will only work if canvg is passed in, otherwise it will throw a SecurityError when calling toDataURL on a canvas that's been written to. canvg may have it's own issues with SVG support, so make sure to test the output.