Exporting D3 graphs

While playing around with D3, I was always disappointed, that the resulting images are stuck in the browser afterwards. However, since you use merely use D3 to generate an embedded SVG image, it should not be that hard to get it out, should it?

Actually its pretty simple using a bit jquery magic, you can get the SVG image in a popup with this simple snippet:

var svg = \$('#svg-image')
.clone()
.wrap("<div>")
.parent()
.html(),
dataURL = ("data:image/svg+xml;utf8," +
encodeURI(svg));

window.open(dataURL);


Here the first line create a temporary copy of the desired image and warps it into an div element. The inner html content of this div element, i.e., the image we want to export, is then assigned to the variable svg (idea from this SO answer). The source is then transformed into a valid HTML5 data URL, which can be opened in a new browser window.

As an example consider the pie chart, adapted from this d3 example. To save the pie chart as an SVG image, just click the button below and save it any local file using "Save As".