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.
Use google method chart. getImageURI() to get image url then store into the variable after using jquery to submit form. Get HTML data to get images url and store into the images folder, and then retrieve images and content. print into pdf using mpdf.
Google Charts can be printed directly from your browser, or from JavaScript via the print() function. If you want to provide access to a PNG image of a chart, you can use the getImageURI() method.
Apparently, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With