I have this D3js line graph I'm working with.
I'd like to be able to save it as an image in the same directory as shown in this example
d3.select('#saveButton').on('click', function(){
var svgString = getSVGString(svg.node());
svgString2Image( svgString, 2*width, 2*height, 'png', save ); // passes Blob and filesize String to the callback
function save( dataBlob, filesize ){
saveAs( dataBlob, 'D3 vis exported to PNG.png' ); // FileSaver.js
function
}
});
no errors running the above
Although I am getting no errors, the file is not downloading when the button is clicked. What am I missing here? Thanks!
In your fiddle, you're appending g
to your svg
and assigning it your variable svg
:
var svg = d3.select("#priceWithMilestones")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
It looks like getSVGString()
expects the root node, and not a g
element. You should probably change your code so that svg
reflects the root svg element, and create another variable to store the g
element, but for a quick and dirty fix, you can change
var svgString = getSVGString(svg.node());
to
var svgString = getSVGString(d3.select('svg').node());
And should save. Updated fiddle: https://jsfiddle.net/c19664p3/8/
Edit: As for exported styles, it looks like you can't refer to selectors outside of the svg when declaring selecting. Additionally it looks like it has to consist of exactly just an id or a class. See my other answer for a more lax CSS rule exporter.
So changing this:
#priceWithMilestones .line {
fill: none;
stroke: #14da9e;
stroke-width: 2px;
}
to:
.line {
fill: none;
stroke: #14da9e;
stroke-width: 2px;
}
exports the line style for just the svg. Updated fiddle: https://jsfiddle.net/c19664p3/10/