Aug 22, 2026

If you are converting SVG to PNG then you probably want to keep the font styles intact. The resvg package can accommodate this with a font configuration. The font files themselves need to be loaded into buffers. Font styles need to be applied inline - CSS does not seem to apply.

const fs = require( 'fs' );
const path = require( 'path' );

const { Resvg, initWasm } = require( '@resvg/resvg-wasm' );

let wasmReady;

async function main( params ) {
  const svg = `
    <svg
      width="640"
      height="480"
      viewBox="0 0 640 480"
      xmlns="http://www.w3.org/2000/svg">
      <style>
        text {
          font-size: 36px;
        }
      </style>
      <text
        x="320"
        y="240"
        text-anchor="middle"
        dominant-baseline="middle">
        <tspan>Hello,</tspan>
        <tspan 
          font-family="Isidora" 
          fill="${params.color ?? 'black'}">${params.name ?? 'World'}!</tspan>
      </text>
    </svg>
  `;

  if( !wasmReady ) {
    wasmReady = initWasm( fs.readFileSync( 
      path.join( __dirname, 'index_bg.wasm' ) 
    ) );
  }

  await wasmReady;
  
  const regularBuffer = fs.readFileSync( 
    path.join( __dirname, 'Roboto-Regular.ttf' ) 
  );
  const boldBuffer = fs.readFileSync( 
    path.join( __dirname, 'Isidora-Bold.otf' ) 
  );

  const resvg = new Resvg( svg, {
    font: {
      fontBuffers: [regularBuffer, boldBuffer],
      loadSystemFonts: false,
      defaultFontFamily: 'Roboto',
      sansSerifFamily: 'Roboto'
    }
  } );

  return {
    statusCode: 200,
    headers: {
      'Content-Type': 'image/png'
    },
    body: Buffer.from( resvg.render().asPng() )
  };
}
Back to Notes