svg-render

Render high-quality PNG images from an SVG

Usage no npm install needed!

<script type="module">
  import svgRender from 'https://cdn.skypack.dev/svg-render';
</script>

README

svg-render

Render high-quality PNG images from an SVG

CI npm-downloads npm-version

CLI

The easiest way to convert your SVG to a PNG is on the command line:

npx svg-render < input.svg > output.png

You can also resive your SVG, since it is scalable after all:

npx svg-render --width 512 < input.svg > output.png

See npx svg-render --help for more info.

If you use this often, you might benefit from installing it on your path directly:

npm install --global svg-render

svg-render < input.svg > output.png

The generated images are unoptimized. You can optimize them with something like pngmin-cli:

npx svg-render < input.svg | npx pngmin-cli > output.png

API

You can require this module in your script as well:

const { promises: fs } = require('fs');
const render = require('svg-render');

(async () => {
  const outputBuffer = await render({
    buffer: await fs.readFile('/path/to/my/input.svg'),
    width: 512
  });

  await fs.writeFile('./output.png', outputBuffer);
})();

Options:

  • buffer <Buffer>: Required. The SVG being rendered.
  • width <Number>: Optional. The desired width of the output PNG. Defaults to the width defined in the SVG (or proportionally scaled based on height when defined).
  • height <Number>: Optional. The desired height of the output PNG. Defaults to the height defined in the SVG (or proportionally scaled based on width when defined).
  • expandUseTags <Boolean>: Optional. Whether to replace instances of use tags in the SVG with the contents that those tags are linking to. This is generally necessary for rendering method being used to work correctly. Defaults to true.

Note: both width and height are optional, but they work together. If neither is provided, the PNG will be the original size of the SVG. If only one of the properties is provided, the other will automatically be scaled proportionally to the original SVG size. If both are provided, the PNG will be stretched to that exact size, regardless of proportions.