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


Given a D3js code, such as:

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

        .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 ?

Problem courtesy of: Hugolpz


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');

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

        .attr("x", 10)
        .attr("y", 10)
        .attr("width", 80)
        .attr("height", 80)
        .style("fill", "orange");
//  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.

Solution courtesy of: Lars Kotthoff


I recently wanted to do just that and asked a question here. I was pointed to phantomJS. Using PhantomJS, I created a JS -


var page = require('webpage').create(),
    url = 'http://www.example.com/wordcloud.html';

page.open(url, function (status) {
    if (status !== 'success') {
        console.log('Unable to access network');
    } else {
        var svgData = page.evaluate(function(s){
                var serializer = new XMLSerializer();
                var element = document.getElementById("svg1");
                return serializer.serializeToString(element);
        console.log("<?xml version=\"1.0\"?>"+svgData);


<!DOCTYPE html>
<meta charset="utf-8">
<script src="d3.min.js"></script>
<script src="d3.layout.cloud.js"></script>
  var fill = d3.scale.category20();

  d3.layout.cloud().size([500, 800])
        "Hello", "world", "normally", "you", "want", "more", "words",
        "than", "this"].map(function(d) {
        return {text: d, size: 10 + Math.random() * 90};
      .rotate(function() { return ~~(Math.random() * 2) * 90; })
      .fontSize(function(d) { return d.size; })
      .on("end", draw)

  function draw(words) {
        .attr("width", 500)
        .attr("height", 800)
        .attr("transform", "translate(150,150)")
        .style("font-size", function(d) { return d.size + "px"; })
        .style("font-family", "Impact")
        .style("fill", function(d, i) { return fill(i); })
        .attr("text-anchor", "middle")
        .attr("transform", function(d) {
          return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
        .text(function(d) { return d.text; });

Then I run

phantomjs svggen.js > svgFile.svg

The resulting svgFile.svg is a standalone SVG File. For d3cloud check this.

Discussion courtesy of: Lord Loh.

node.js is the way to go. You can install d3 directly with npm. (It will also add jsdom as a dependency to provide a "fake" DOM.) After the d3 code generates the SVG, just grab its contents and write to a file.

Discussion courtesy of: Stephen Thomas

if you donot want to use node.js , then use phantomJs , here you can find a demo https://github.com/subramanya2107/d3js-phantomjs-demo.git

Discussion courtesy of: subbu

Here's a very short node script that will output an svg to stdout generated with d3.js.

#!/usr/bin/env node

var d3 = require("d3"),
    jsdom = require("jsdom").jsdom;

var body = d3.select(jsdom().documentElement).select("body");

var svg = body.append("svg");

Link to snippet on bl.ocks.org

Discussion courtesy of: Shan Carter

This recipe can be found in it's original form on Stack Over Flow.