Hugolpz Hugolpz - 1 month ago 12
Node.js Question

D3js: how to generate standalone SVG files? (Nodejs)

Given a D3js code, such as:

function () {
var svg = window.d3.select("body")
.append("svg")
.attr("width", 100)
.attr("height", 100);

svg.append("rect")
.attr("x", 10)
.attr("y", 10)
.attr("width", 80)
.attr("height", 80)
.style("fill", "orange");
}


How to generate a correct stand alone *.svg file with my D3js code & NodeJS ?

Answer

Github repository svgcreator.node.js to try out.


D3 doesn't care at all what actually generate your SVG. The main problem with creating only SVG is that you can't have Javascript then, which of course means that you can't use D3. Apart from this fundamental no-no, there's nothing stopping you :)

Proof of concept: Inspired by the other answer, here's some proof-of-concept code using jsdom.

1. Install NodeJS (1).

curl http://npmjs.org/install.sh | sh       #this should work (not tested)

2. Install jsdom using the Node Packages Manager (2):

$npm install jsdom

3. Wrap your D3js code within some jsdom code, paste into a jsdom.node.js file :

var jsdom = require('jsdom');

jsdom.env(
  "<html><body></body></html>",
  [ 'http://d3js.org/d3.v3.min.js' ],
  function (err, window) {
    var svg = window.d3.select("body")
        .append("svg")
        .attr("width", 100).attr("height", 100);

    svg.append("rect")
        .attr("x", 10)
        .attr("y", 10)
        .attr("width", 80)
        .attr("height", 80)
        .style("fill", "orange");
// PRINT OUT:
    console.log(window.d3.select("body").html());
//  fs.writeFileSync('out.svg', window.d3.select("body").html()); // or this
  }
);

4. Run in terminal

$node jsdom.node.js > test.svg

The stdout output is the SVG, which is then injected into a test.svg file. Job done.

As Gilly points out in the comments, you may need version 3 of jsdom for this to work.

Comments