Last active
November 9, 2022 08:41
-
-
Save aralroca/be192309e9b0cb8908ae361fed9d6c56 to your computer and use it in GitHub Desktop.
Convert SVG to another format in Node.js (Requires inkscape installed)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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