Skip to content

Instantly share code, notes, and snippets.

@aralroca
Last active November 9, 2022 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aralroca/be192309e9b0cb8908ae361fed9d6c56 to your computer and use it in GitHub Desktop.
Save aralroca/be192309e9b0cb8908ae361fed9d6c56 to your computer and use it in GitHub Desktop.
Convert SVG to another format in Node.js (Requires inkscape installed)
import fs from 'fs';
import { spawn } from 'child_process';
type Format =
| 'dxf'
| 'emf'
| 'eps'
| 'fxg'
| 'gpl'
| 'hpgl'
| 'html'
| 'jpg'
| 'odg'
| 'pdf'
| 'png'
| 'pov'
| 'ps'
| 'sif'
| 'svgz'
| 'tar'
| 'tex'
| 'tiff'
| 'webp'
| 'wmf'
| 'xaml'
| 'zip';
/*
* 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();
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment