Reputation: 1043
I have got charts generated with D3 Javascript library and i need to save these to file PNG or SVG.
Is there some library that makes the job?
I found this https://github.com/sampumon/SVG.toDataURL but is not working on my html5, in firefox console i got this error:
NS_ERROR_NOT_AVAILABLE: Component is not available [Interrompi per questo errore]
ctx.drawImage(img, 0, 0);
Upvotes: 17
Views: 30476
Reputation: 6313
This extension works with all <svg>
tags in the page: https://chrome.google.com/webstore/detail/svg-export/naeaaedieihlkmdajjefioajbbdbdjgp?hl=en-GB
Upvotes: 2
Reputation: 19
Here is a simple method to save svg elements to png(though it uses server-side scripting, which may be different from what you'd expect): Checkout this page.
As is documented by the author, the client extract the svg element (using XMLSerializer.serializeToString)and send it to server; the server convert it to png and send it back to the client. The server can use any program that is convenient(rsvg-convert in this case).
You can use this library to do this on client side (check it out!):
canvg is a SVG parser and renderer. It takes a URL to a SVG file or the text of an SVG file, parses it in JavaScript, and renders the result on a Canvas element
Use it like this:
//load a svg snippet in the canvas with id = 'drawingArea'
canvg(document.getElementById('drawingArea'), '<svg>... </svg>')
Then you can use the toDataURL method:
document.getElementById('drawingArea').toDataURL('image/png');
Upvotes: 1
Reputation: 341
Example from developer.mozilla.org demonstrating how to export svg to png using canvas element.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var data = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +
'<foreignObject width="100%" height="100%">' +
'<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:40px">' +
'<em>I</em> like ' +
'<span style="color:white; text-shadow:0 0 2px blue;">' +
'cheese</span>' +
'</div>' +
'</foreignObject>' +
'</svg>';
var DOMURL = window.URL || window.webkitURL || window;
var img = new Image();
var svg = new Blob([data], {type: 'image/svg+xml'});
var url = DOMURL.createObjectURL(svg);
img.onload = function () {
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
var png_img = canvas.toDataURL("image/png");
}
img.src = url;
Upvotes: 9