svg to png in typescript

index.ts
import fs = require('fs');
import { JSDOM } from 'jsdom';
import { convertFile } from 'convert-svg-to-png';

// Read the SVG file
const svgContent = fs.readFileSync('input.svg', 'utf8');

// Create a DOM instance
const dom = new JSDOM(svgContent);

// Get the SVG element
const svg = dom.window.document.querySelector('svg');

// Convert SVG to PNG
convertFile('output.png', svg.outerHTML)
    .then(() => console.log('PNG file saved'))
    .catch((e) => console.error('An error occurred:', e));
496 chars
18 lines

In this code snippet, we are reading an SVG file using fs module, then converting it to a DOM instance using jsdom. We extract the SVG element from the DOM, and use convert-svg-to-png package to convert the SVG to a PNG file.

related categories

gistlibby LogSnag