0

I insert background image to svg like described here Now I need convert it to png on server side. I try bash command:

 convert -density 1200 march.svg march.png

In result I see svg only without background raster image. Also I try npm svg-to-png and also not see background.

How I can resolve this issue? Thanks!

UPD:

Downliad march.svg

tolyan
  • 809
  • 3
  • 10
  • 27

1 Answers1

0

Requires inkscape installed, but in Node.js you can have a function like this one:

import fs from 'fs';
import { spawn } from 'child_process';
  
/*
*  Requires:
*   
* > brew install inkscape
*/
async function convertSvgToFormat(svg: string, format: Format): Promise<Buffer> {
  return new Promise((resolve, reject) => {
    const id = crypto.randomUUID();
    const input = `in_${id}.svg`;
    const output = `out_${id}.${format}`;
    const command = `inkscape --export-type=${format} ${input} --export-filename=${output}`;
    const clear = () => [input, output].forEach((file) => fs.unlinkSync(file));

    fs.writeFileSync(input, svg);

    spawn(command, { shell: true, stdio: 'inherit' })
      .on('close', (out) => {
        if(out !== 0) reject()
        else resolve(fs.readFileSync(output));
        clear();
      })
      .on('error', (error) => {
        reject(error);
        clear();
      });
  });

To use it:

const pngBuffer = await convertSvgToFormat('<svg><text>Test</text><svg>', 'png')

All supported formats of inkscape:

type Format =
  | 'dxf'
  | 'emf'
  | 'eps'
  | 'fxg'
  | 'gpl'
  | 'hpgl'
  | 'html'
  | 'jpg'
  | 'odg'
  | 'pdf'
  | 'png'
  | 'pov'
  | 'ps'
  | 'sif'
  | 'svgz'
  | 'tar'
  | 'tex'
  | 'tiff'
  | 'webp'
  | 'wmf'
  | 'xaml'
  | 'zip';
Aral Roca
  • 5,442
  • 8
  • 47
  • 78