Codementor Events

Canvas JSON to SVG using Node

Published Oct 31, 2019
Canvas JSON to SVG using Node

Following is the steps / procedure to convert fabric json to SVG / PDF using NODE js script without using browser.

  1. Add the following node module packages in package.json
    npm install canvas@1.6.13, fabric@2.6, jsdom@9.12.0

  2. Load the node modules in js

var fs = require('fs'),
    fabric = require('fabric').fabric,
    out = fs.createWriteStream(__dirname + '/output.png');
  1. Read fabric js canvas json from local directory
let jsonstr = fs.readFileSync(__dirname + '/templates/8.json', 'utf-8');
let json = JSON.parse(jsonstr);
  1. Create static canvas
var canvas = new fabric.StaticCanvas(null, { width: wh.width, height: wh.height });
  1. Load the json in canvas and convert it as svg.
canvas.loadFromJSON(json, function() {

  //first render
  canvas.renderAll.bind(canvas);

  //save the canvas as SVG in server
  var svgoutput = canvas.toSVG();
  fs.writeFile("output.svg", svgoutput, function(err) {
    if (err) throw err;
  });
});

Other features that can be added is SVG to PDF using svg-to-pdfkit module.
Links of json,
http://kpomservices.com/canvas2svg/templates/8.json
converted svg, png, pdf
http://kpomservices.com/canvas2svg/output.svg
http://kpomservices.com/canvas2svg/output.pdf
http://kpomservices.com/canvas2svg/output.png

Discover and read more posts from Frederic Anand
get started
post commentsBe the first to share your opinion
Show more replies