Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save a Google Chart as SVG?

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.

like image 539
Cornstalks Avatar asked Oct 02 '12 20:10

Cornstalks


People also ask

How do I save a Google graph as a PDF?

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.

How do I print a Google chart?

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.


2 Answers

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)

like image 111
Cornstalks Avatar answered Oct 26 '22 11:10

Cornstalks


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.

Google Chrome DevTools screenshot

like image 1
VincentTellier Avatar answered Oct 26 '22 13:10

VincentTellier