To render an SVG to PNG in Node.js, import Resvg from @resvg/resvg-js. You can pass an options object to configure background color, scaling (fitTo), and fonts.
Key options:
background: A color string (e.g., 'rgba(238, 235, 230, .9)').fitTo: An object with mode ('width' or 'height') and value to scale the output.font: Configuration for fonts, including fontFiles (array of paths) and loadSystemFonts (boolean).
After calling resvg.render(), use pngData.asPng() to get the buffer.
const { promises } = require('fs')
const { join } = require('path')
const { Resvg } = require('@resvg/resvg-js')
async function main() {
const svg = await promises.readFile(join(__dirname, './text.svg'))
const opts = {
background: 'rgba(238, 235, 230, .9)',
fitTo: {
mode: 'width',
value: 1200,
},
font: {
fontFiles: ['./example/SourceHanSerifCN-Light-subset.ttf'], // Load custom fonts.
loadSystemFonts: false, // It will be faster to disable loading system fonts.
},
}
const resvg = new Resvg(svg, opts)
const pngData = resvg.render()
const pngBuffer = pngData.asPng()
console.info('Original SVG Size:', `${resvg.width} x ${resvg.height}`)
console.info('Output PNG Size :', `${pngData.width} x ${pngData.height}`)
await promises.writeFile(join(__dirname, './text-out.png'), pngBuffer)
}
main()