Skip to content

Instantly share code, notes, and snippets.

@battlehorse
Created November 2, 2011 15:21
Show Gist options
  • Save battlehorse/1333906 to your computer and use it in GitHub Desktop.
Save battlehorse/1333906 to your computer and use it in GitHub Desktop.
Demo script to convert Google Chart Tools charts into PNG images.
<html>
<head>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/rgbcolor.js"></script>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/canvg.js"></script>
<script>
function getImgData(chartContainer) {
var chartArea = chartContainer.getElementsByTagName('iframe')[0].
contentDocument.getElementById('chartArea');
var svg = chartArea.innerHTML;
var doc = chartContainer.ownerDocument;
var canvas = doc.createElement('canvas');
canvas.setAttribute('width', chartArea.offsetWidth);
canvas.setAttribute('height', chartArea.offsetHeight);
canvas.setAttribute(
'style',
'position: absolute; ' +
'top: ' + (-chartArea.offsetHeight * 2) + 'px;' +
'left: ' + (-chartArea.offsetWidth * 2) + 'px;');
doc.body.appendChild(canvas);
canvg(canvas, svg);
var imgData = canvas.toDataURL("image/png");
canvas.parentNode.removeChild(canvas);
return imgData;
}
function saveAsImg(chartContainer) {
var imgData = getImgData(chartContainer);
// Replacing the mime-type will force the browser to trigger a download
// rather than displaying the image in the browser window.
window.location = imgData.replace("image/png", "image/octet-stream");
}
function toImg(chartContainer, imgContainer) {
var doc = chartContainer.ownerDocument;
var img = doc.createElement('img');
img.src = getImgData(chartContainer);
while (imgContainer.firstChild) {
imgContainer.removeChild(imgContainer.firstChild);
}
imgContainer.appendChild(img);
}
</script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart", "treemap", "geochart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
// Pie chart
var data = new google.visualization.DataTable();
data.addColumn('string', 'Task');
data.addColumn('number', 'Hours per Day');
data.addRows(5);
data.setValue(0, 0, 'Work');
data.setValue(0, 1, 11);
data.setValue(1, 0, 'Eat');
data.setValue(1, 1, 2);
data.setValue(2, 0, 'Commute');
data.setValue(2, 1, 2);
data.setValue(3, 0, 'Watch TV');
data.setValue(3, 1, 2);
data.setValue(4, 0, 'Sleep');
data.setValue(4, 1, 7);
var chart = new google.visualization.PieChart(document.getElementById('pie_div'));
chart.draw(data, {width: 450, height: 300, title: 'My Daily Activities'});
// Line chart
data = new google.visualization.DataTable();
data.addColumn('string', 'Year');
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');
data.addRows(4);
data.setValue(0, 0, '2004');
data.setValue(0, 1, 1000);
data.setValue(0, 2, 400);
data.setValue(1, 0, '2005');
data.setValue(1, 1, 1170);
data.setValue(1, 2, 460);
data.setValue(2, 0, '2006');
data.setValue(2, 1, 860);
data.setValue(2, 2, 580);
data.setValue(3, 0, '2007');
data.setValue(3, 1, 1030);
data.setValue(3, 2, 540);
var chart = new google.visualization.LineChart(document.getElementById('line_div'));
chart.draw(data, {width: 450, height: 300, title: 'Company Performance'});
// Treemap
data = new google.visualization.DataTable();
data.addColumn('string', 'Region');
data.addColumn('string', 'Parent');
data.addColumn('number', 'Market trade volume (size)');
data.addColumn('number', 'Market increase/decrease (color)');
data.addRows([
["Global",null,0,0],
["America","Global",0,0],
["Europe","Global",0,0],
["Asia","Global",0,0],
["Australia","Global",0,0],
["Africa","Global",0,0],
["Brazil","America",11,10],
["USA","America",52,31],
["Mexico","America",24,12],
["Canada","America",16,-23],
["France","Europe",42,-11],
["Germany","Europe",31,-2],
["Sweden","Europe",22,-13],
["Italy","Europe",17,4],
["UK","Europe",21,-5],
["China","Asia",36,4],
["Japan","Asia",20,-12],
["India","Asia",40,63],
["Laos","Asia",4,34],
["Mongolia","Asia",1,-5],
["Israel","Asia",12,24],
["Iran","Asia",18,13],
["Pakistan","Asia",11,-52],
["Egypt","Africa",21,0],
["S. Africa","Africa",30,43],
["Sudan","Africa",12,2],
["Congo","Africa",10,12],
["Zair","Africa",8,10]
]);
var tree = new google.visualization.TreeMap(document.getElementById('treemap_div'));
tree.draw(data, {
minColor: '#f00',
midColor: '#ddd',
maxColor: '#0d0',
headerHeight: 15,
fontColor: 'black',
showScale: true});
data = new google.visualization.DataTable();
data.addRows(6);
data.addColumn('string', 'Country');
data.addColumn('number', 'Popularity');
data.setValue(0, 0, 'Germany');
data.setValue(0, 1, 200);
data.setValue(1, 0, 'United States');
data.setValue(1, 1, 300);
data.setValue(2, 0, 'Brazil');
data.setValue(2, 1, 400);
data.setValue(3, 0, 'Canada');
data.setValue(3, 1, 500);
data.setValue(4, 0, 'France');
data.setValue(4, 1, 600);
data.setValue(5, 0, 'RU');
data.setValue(5, 1, 700);
var options = {};
var container = document.getElementById('map_div');
var geochart = new google.visualization.GeoChart(container);
geochart.draw(data, options);
data = new google.visualization.DataTable();
data.addColumn('number', 'Age');
data.addColumn('number', 'Weight');
data.addRows(6);
data.setValue(0, 0, 8);
data.setValue(0, 1, 12);
data.setValue(1, 0, 4);
data.setValue(1, 1, 5.5);
data.setValue(2, 0, 11);
data.setValue(2, 1, 14);
data.setValue(3, 0, 4);
data.setValue(3, 1, 4.5);
data.setValue(4, 0, 3);
data.setValue(4, 1, 3.5);
data.setValue(5, 0, 6.5);
data.setValue(5, 1, 7);
var chart = new google.visualization.ScatterChart(document.getElementById('scatter_div'));
chart.draw(data, {width: 400, height: 240,
title: 'Age vs. Weight comparison',
hAxis: {title: 'Age', minValue: 0, maxValue: 15},
vAxis: {title: 'Weight', minValue: 0, maxValue: 15},
legend: 'none'
});
}
</script>
</head>
<body>
<div id="img_div" style="position: fixed; top: 0; right: 0; z-index: 10; border: 1px solid #b9b9b9">
Image will be placed here
</div>
<button onclick="saveAsImg(document.getElementById('pie_div'));">Save as PNG Image</button>
<button onclick="toImg(document.getElementById('pie_div'), document.getElementById('img_div'));">Convert to image</button>
<div id="pie_div"></div>
<button onclick="saveAsImg(document.getElementById('line_div'));">Save as PNG Image</button>
<button onclick="toImg(document.getElementById('line_div'), document.getElementById('img_div'));">Convert to image</button>
<div id="line_div"></div>
<button onclick="saveAsImg(document.getElementById('treemap_div'));">Save as PNG Image</button>
<button onclick="toImg(document.getElementById('treemap_div'), document.getElementById('img_div'));">Convert to image</button>
<div id="treemap_div" style="width: 450px; height: 300px;"></div>
<button onclick="saveAsImg(document.getElementById('map_div'));">Save as PNG Image</button>
<button onclick="toImg(document.getElementById('map_div'), document.getElementById('img_div'));">Convert to image</button>
<div id="map_div" style="width: 500px; height: 300px"></div>
<button onclick="saveAsImg(document.getElementById('scatter_div'));">Save as PNG Image</button>
<button onclick="toImg(document.getElementById('scatter_div'), document.getElementById('img_div'));">Convert to image</button>
<div id="scatter_div"></div>
</body>
</html>
@jc8390
Copy link

jc8390 commented Dec 17, 2012

Hi,
I am getting the below error, In the demo link you have given.
"Uncaught TypeError: Cannot read property 'contentDocument' of undefined "

Please guide me how to run this example successfully, pls.

@bamtstic
Copy link

Hi guys,

Line 7 & 8 should be replaced with:

var chartArea = chartContainer.getElementsByTagName('div')[1];

Seems to work fine, google must have updated the way the graphs are done.

@TravisStude
Copy link

Hi,

I see the error CanvasRenderingContext2D is undefined as part of the canvg.js file. My include scripts are the following.

 <script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/rgbcolor.js"></script> 
 <script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/canvg.js"></script>

I tried to create a file with the CanvasRenderingContext2D object from here ...

http://code.google.com/p/base2/source/browse/trunk/src/base2/html5/canvas/CanvasRenderingContext2D.js?r=261

but that did not work. I only see this error with IE. Chrome and FF do not throw the error but nothing happens when I click the create image/download image buttons. IE also throws an error on the buttons, contentDocument is undefined in getImgData(), most likely related to the first error though.

Do you have any other suggestions?

Thanks,
TJ

@DannyOosterveer
Copy link

This script is awesome! I've been looking for this solution for over a year now. However, when I grab your code (without editing anything) and view it in my browser (Safari/Firefox for Mac) nothing seems to happen. What could be wrong?

@DannyOosterveer
Copy link

I just stumped onto: http://stackoverflow.com/questions/13824096/save-google-charts-as-a-image

This seems to fix the issue.

@johnathandev
Copy link

Also there is an alternative solution of a javascript library called grchartImg that supports all the browsers (IE<9) and can be convert google charts to image.Look at http://www.chartstoimage.eu

@Snakif
Copy link

Snakif commented Apr 8, 2013

I have this error:

ReferenceError: chartContainer is not defined
[Detener en este error]

var chartArea = chartContainer.getElementsByTagName('iframe')[0];

@nverba
Copy link

nverba commented Apr 18, 2013

Google charts have updated and no longer use the iframe referenced in this gist. Also 'chartArea' is no longer defined. You can fix it up by replacing the following lines. Credit~>

-        var chartArea = chartContainer.getElementsByTagName('iframe')[0].
-        contentDocument.getElementById('chartArea');

+        var chartArea = chartContainer.getElementsByTagName('svg')[0].parentNode;

You can view a working demo here or here.

Having an issue with line and area graph axis though. On the rendered image the vAxis is positioned wrongly (too close) and covers part of the graph area. Anyone have ideas on how to fix this? You can see the issue on the demo page if you click to view one of the line graph.

@philtsip
Copy link

The tutorial code no longer works, but I added two fixes to it in an answer on StackOverflow: http://stackoverflow.com/a/16137983/571733

  1. Set the chartArea variable to work with Google Visualization API version 1.32 (Sept 24, 2012) and later
  2. Use canvg.js r157 as a workaround for a regression identified by @nverba

@sam215
Copy link

sam215 commented May 1, 2013

Hii when i try this code for 3-d column chart its not working ..for pie chart its working ..bt 4 column ..not..so what should i have to do now???

@Mallareddy15
Copy link

Thanks for The great example. Basically I am a salesforce developer.
Coming to my requirement I have a page with two Google visualization API column charts and one table i want to save it as image all in one click instead of giving separate buttons for each chart is it possible to this . If possible can you please help me.

@mpetherb
Copy link

The image wasnt working, Changed it to work: https://gist.github.com/mpetherb/7085315

 function getImgData(chartContainer) {
    var chartArea = chartContainer.getElementsByTagName('svg')[0].parentNode;
    var svg = chartArea.innerHTML;
    var doc = chartContainer.ownerDocument;
    var canvas = doc.createElement('canvas');
    canvas.setAttribute('width', chartArea.offsetWidth);
    canvas.setAttribute('height', chartArea.offsetHeight);


    canvas.setAttribute(
        'style',
        'position: absolute; ' +
        'top: ' + (-chartArea.offsetHeight * 2) + 'px;' +
        'left: ' + (-chartArea.offsetWidth * 2) + 'px;');
    doc.body.appendChild(canvas);
    canvg(canvas, svg);
    var imgData = canvas.toDataURL("image/png");
    canvas.parentNode.removeChild(canvas);
    return imgData;
  }

@sathishH
Copy link

sathishH commented Nov 7, 2013

As per this I am converting google charts to SVG images. Here getting SVG image path using canvas.toDataURL(), By using this path I can show image in html but not in PD4ML pdf as it is throwing an error
'ERROR STDERR - Bad Base64 input character at 6644: 59(decimal)'.
how to get correct svg path?

@harryjan
Copy link

harryjan commented Jul 7, 2014

https://developers.google.com/chart/interactive/docs/printing may be helpful for a supported method of exporting images (HTML5 Browsers only)

@MULLAINATHAN
Copy link

How to Export google chart as CSV ..?
Please help me.
Thanks in advance.

@satyajit225
Copy link

This was working on only on chrome and firefox.
but now not working on firefox

@farhanalisoharwardi
Copy link

This is only working in Chrome & Safari. Not working in Firefox.
In Firefox it creates a BLACK image for JPEG and a BLANK image for PNG/JPG.

@dejwsz
Copy link

dejwsz commented Nov 18, 2014

I can confirm it stopped working in latest Firefox, some recent changes in Firefox prevented this to work

@bideshpuja
Copy link

I cannot convert line graph to png image in firefox. please give me a proper suggestion.
"And http://bl.ocks.org/nverba/raw/5411684/ " this link not work in firefox for line graph and pie chart

@ragunathmuthukumar
Copy link

I cannot convert line graph to png image in firefox. please give me a proper suggestion as soon as possible....plz.....

@irmela
Copy link

irmela commented Oct 29, 2015

Had the same problem. There was additional html markup inside of var svg. I fixed it by changing

var chartArea = chartContainer.getElementsByTagName('svg')[0].parentNode;
var svg = chartArea.innerHTML;

to

var chartArea = chartContainer.getElementsByTagName('svg')[0].parentNode;
var svg = '<svg>' + chartContainer.getElementsByTagName('svg')[0].innerHTML + '</svg>'

@GoutamTMS
Copy link

Uncaught ReferenceError: canvg is not defined
This error occurring..

@FGRibreau
Copy link

FGRibreau commented Oct 11, 2016

If you don't want to host it, scale it yourself, and would like gif animation on top of it (nice for animated charts in emails!) you may want to give a try to https://image-charts.com !

No more server-side chart rendering pain, just 1 URL = 1 image chart.

a

One last thing, it's a drop-in replacement for the soon-to-be-shutdown Google Image Chart!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment