Tutorials

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>
Furqan

Well. I've been working for the past three years as a web designer and developer. I have successfully created websites for small to medium sized companies as part of my freelance career. During that time I've also completed my bachelor's in Information Technology.

Recent Posts

Llama 3.1 vs GPT-4 Benchmarks

We evaluated the performance of Llama 3.1 vs GPT-4 models on over 150 benchmark datasets…

July 24, 2024

Transforming Manufacturing with Industrial IoT Solutions and Machine Learning

The manufacturing industry is undergoing a significant transformation with the advent of Industrial IoT Solutions.…

July 6, 2024

How can IT Professionals use ChatGPT?

If you're reading this, you must have heard the buzz about ChatGPT and its incredible…

September 2, 2023

ChatGPT in Cybersecurity: The Ultimate Guide

How to Use ChatGPT in Cybersecurity If you're a cybersecurity geek, you've probably heard about…

September 1, 2023

Add Cryptocurrency Price Widget in WordPress Website

Introduction In the dynamic world of cryptocurrencies, staying informed about the latest market trends is…

August 30, 2023

Best Addons for The Events Calendar Elementor Integration

The Events Calendar Widgets for Elementor has become easiest solution for managing events on WordPress…

August 30, 2023