Export SVG to PNG/JPEG Image Using Node.js Express.js and SVGExport Module

What is svgexport?

svgexport is a Node.js module and command-line tool for exporting SVG files to PNG and JPEG, it uses Puppeteer for rendering SVG files.

Installation

npm i -g svgexport

Usage

Scale 1.5x proportionally:

svgexport input.svg output.png 1.5x

Scale proportionally to set output width to 32px:

svgexport input.svg output.png 32:

Scale proportionally and pad output to set output width:height to 32px:54px:

svgexport input.svg output.png pad 32:54

Export -1:-1:24:24 (left:top:width:height) of input.svg to output.png:

svgexport input.svg output.png -1:-1:24:24 1x

Set output JPEG quality:

svgexport input.svg output.jpg 80%

Use a CSS to style input SVG:

svgexport input.svg output.jpg "svg{background:silver;}"

By default, Puppeteer has a page load timeout of 30 seconds. This might not be enough for large SVG files. If you want to change the page timeout, set the SVGEXPORT_TIMEOUT environment variable to the desired number of seconds.

// One minute timeout
SVGEXPORT_TIMEOUT=60 svgexport input.svg output.png

Node.js Module

Installation

npm install svgexport --save

Usage

<span class="pl-k">var</span> <span class="pl-s1">svgexport</span> <span class="pl-c1">=</span> <span class="pl-en">require</span><span class="pl-kos">(</span><span class="pl-s">'svgexport'</span><span class="pl-kos">)</span><span class="pl-kos">;</span>

<span class="pl-s1">svgexport</span><span class="pl-kos">.</span><span class="pl-en">render</span><span class="pl-kos">(</span><span class="pl-s1">datafile</span><span class="pl-kos">,</span> <span class="pl-s1">callback</span><span class="pl-kos">)</span><span class="pl-kos">;</span>

datafile can be an object, an array of objects or a JSON file path, see command line usage for its format

Node.js Express App in Browser

npm init -y
npm i express
npm i multer

Make a uploads directory inside the root project

index.js

const express = require('express')

const multer = require('multer')

const {exec} = require("child_process")

const bodyparser = require('body-parser')

const path = require('path')

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads')
    },
    filename: function (req, file, cb) {
        cb(null, Date.now() + path.extname(file.originalname)) //Appending extension
    }
})

var upload = multer({ storage: storage }).single('file')

const app = express()

app.use(bodyparser.urlencoded({extended:false}))
app.use(bodyparser.json())

app.get('/', (req, res) => {
    res.sendFile(__dirname + "/index.html")
})

app.post('/svgtoimage', (req, res) => {
    const format = req.body.format
    console.log(format)
    const outputfile = Date.now() + `output.jpg`
    upload(req,res,(err) => {
        if(err){
            console.log("Error in Uploading file")
        }
        else{
            console.log(req.file.path)
            exec(`svgexport ${req.file.path} ${outputfile}`,(err,stderr,stdout) => {
                if(err){
                    console.log("error in conversion of svg")
                }
                else{
                    res.download(outputfile,(err) => {

                    })
                }
            })
        }
    })
})

app.listen(5000, () => {
    console.log("App is listening on port 5000 ")
})

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SVG to PNG/JPEG</title>
</head>
<body>
    <form action="/svgtoimage" method="post" enctype="multipart/form-data">
        <input type="file" accept=".svg" name="file" required id="">
        <select name="format" id="">
            <option value="png" selected>PNG</option>
            <option value="jpg">JPG</option>
        </select>
        <button>Export to Image</button>
    </form>
</body>
</html>

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.