The new Google Chart API creates charts as SVGs (not PNGs as it used to). I'd like to be able to save the generated SVG. How can I do this?
If I use Chrome to inspect elements on the page, I can find the svg tag that holds the SVG. I'd like to be able to get the generated SVG using JavaScript. I'd prefer not to search the HTML source for the svg tag in JavaScript, and if there's a way to get the SVG string directly from the chart object (maybe the ChartWrapper class?) that would be preferable.
The new Google Chart API creates charts as SVGs (not PNGs as it used to). I'd like to be able to save the generated SVG. How can I do this?
If I use Chrome to inspect elements on the page, I can find the svg tag that holds the SVG. I'd like to be able to get the generated SVG using JavaScript. I'd prefer not to search the HTML source for the svg tag in JavaScript, and if there's a way to get the SVG string directly from the chart object (maybe the ChartWrapper class?) that would be preferable.
Share Improve this question asked Oct 2, 2012 at 20:43 CornstalksCornstalks 38.2k19 gold badges83 silver badges149 bronze badges2 Answers
Reset to default 13Apparently, this is not supported by the Google Charts API (references 1, 2, and 3). I created the below hack to get the SVG string as a workaround. Below is the full JavaScript.
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
// Create and draw the visualization.
var chart = new google.visualization.PieChart(document.getElementById('visualization'));
google.visualization.events.addListener(chart, 'ready', allReady); // ADD LISTENER
chart.draw(data, {title:"So, how was your day?"});
}
function allReady() {
var e = document.getElementById('visualization');
// svg elements don't have inner/outerHTML properties, so use the parents
alert(e.getElementsByTagName('svg')[0].outerHTML);
}
google.setOnLoadCallback(drawVisualization);
Note that this doesn't work in IE because the Google Charts API doesn't use SVG in IE. I'm always open to better solutions.
(thanks to untill for suggesting .outerHTML
over .parentNode.innerHTML
)
You can also use Google Chrome DevTools, especially the element selector then you can copy/past the SVG you're looking for directly from the DOM.