Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Google Geochart to image (JPEG, PNG, etc.) or PDF in the browser

I'm using Google GeoCharts (https://developers.google.com/chart/interactive/docs/gallery/geochart#Overview) to dynamically generate color-coded maps in the browser. The geochart api draws the maps using javascript/svg... any advice for generating an exportable image file? (pdf, raster image, etc.)

Can this be done through google geocharts? If not, is there another service you can recommend?

*We were previously using GeoMaps but the resolution was not suitable.

like image 280
wearedag Avatar asked Jul 18 '12 16:07

wearedag


2 Answers

This can be done by following the steps on this page. Note that the code in the article is based on an old version of Google Visualization which used iframes, and will not work as posted. However, you can do the same using the following code (found in the comments):

var svg = $(chartContainer).find('svg').parent().html();
var doc = chartContainer.ownerDocument;
var canvas = doc.createElement('canvas');
canvas.setAttribute('style', 'position: absolute; ' + '');
doc.body.appendChild(canvas);
canvg(canvas, svg);
var imgData = canvas.toDataURL("image/png");
canvas.parentNode.removeChild(canvas);
return imgData; 

Note: I did not create this code, it was originally created by the author of the above site (Riccardo Govoni) and updated in the comments section by user Thomas.

like image 65
jmac Avatar answered Nov 15 '22 09:11

jmac


This is very well possible; I do this by exploiting the SVG to image converter from Highcharts. You simply find the svg code in the page and POST that to the highcharts exporting server along with a type paramater (e.g. image/jpeg), as width, and the filename to save it as.

Only downside: IE is not rendering SVG but VML for Google visualizations. No solution there yet, but it seems Highcharts also have difficulties with IE and VML to SVG conversions. So no luck there I'm afraid.

<form method="post" action="http://export.highcharts.com/" id="imageGetForm">
<input type="hidden" name="filename" value="savedFromGoogleVisualization" />
<input type="hidden" name="type" id="imageGetFormTYPE" value="" />
<input type="hidden" name="width" value="900" />
<input type="hidden" name="svg" value="" id="imageGetFormSVG" />
</form>

and execute the following script:

var svg=document.getElementById('chart_div').getElementsByTagName('svg')[0].parentNode.innerHTML;
$('#imageGetFormTYPE').val('image/jpeg');//e.g. image/jpeg application/pdf etc
$('#imageGetFormSVG').val(svg);
$('#imageGetForm').submit();

Working example here: http://jsfiddle.net/P6XXM/

like image 42
Jeroen Avatar answered Nov 15 '22 10:11

Jeroen