svg to png nodejs in javascript

To convert SVG to PNG in Node.js using JavaScript, you can use the 'svg2img' package. First, install it using npm with the following command:

npm install svg2img
20 chars
2 lines

Then, you can use the following code to convert SVG string to PNG image:

index.tsx
const fs = require('fs');
const svg2img = require('svg2img');

const svgString = '<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><circle cx="50" cy="50" r="40" fill="red" /></svg>';

svg2img(svgString, function(error, buffer) {
    if (error) {
        console.error(error);
        return;
    }

    fs.writeFileSync('output.png', buffer);
    console.log('SVG converted to PNG successfully');
});
418 chars
15 lines

In this code:

  1. Replace svgString with your SVG content.
  2. The svg2img() function converts the SVG string to PNG buffer.
  3. Use fs.writeFileSync() method to save the PNG buffer to a file ('output.png' in this case).

Make sure you have the necessary permissions to write to a file in the specified directory.

Remember to handle errors accordingly in a full-fledged application.

related categories

gistlibby LogSnag