How to send Google Chart by email?

2

What would be a viable solution to send a Chart via email via PHP? To get the Chart, I use the following form:

      google.load("visualization", "1", {packages:["corechart"]});
    				      google.setOnLoadCallback(drawChart);
    				      function drawChart() {
    				        var data = google.visualization.arrayToDataTable([
    					        ['Element', 'Density', { role: 'style' }],
    					        ['Copper', 8.94, '#b87333', ],
    					        ['Silver', 10.49, 'silver'],
    					        ['Gold', 19.30, 'gold'],
    					        ['Platinum', 21.45, 'color: #e5e4e2' ]
    					      ]);
    
    				        var options = {
    				          title: 'Company Performance',
    				          hAxis: {title: 'Year',  titleTextStyle: {color: '#333'}},
    				          vAxis: {minValue: 0}
    				        };
    
    				        var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
    
    
    				        google.visualization.events.addListener(chart, 'ready', function () {
    					        chart_div.innerHTML = '<img src="' + chart.getImageURI() + '">';
    					        console.log(chart_div.innerHTML);
    					      });
    
    				        chart.draw(data, options);
    				      }
    <script type="text/javascript" src="https://www.google.com/jsapi"></script><divid="chart_div"></div>

That way it returns the Chart to me in a "printable" version.

    
asked by anonymous 10.11.2015 / 18:55

1 answer

2

Google Charts are designed using SVG. Some email providers provide SVG reading, others do not. The solution I found was convert SVG to PNG and save the PNG file on the server and include a <img src=""> tag in the email body.

From Google Chart to PHP

Google Chart works on the Front-end. PHP is a server-side language. You will need to run the frontend for the graph to be drawn and then collect the entire generated SVG and forward it to PHP. With jQuery, you could grab content using something simple like

var content = jQuery('#chart_div').html();

Once this is done, use an Ajax call to deliver the content to the server so that it can be sent by email.

Remarks: In particular, I preferred to write SVG in PHP itself than to use Google Chart. You can learn how to make graphics using SVG and have PHP itself write all the SVG content and convert it to PNG. This way, there is no need for front-end script executions. The server itself would take care of everything.

Converting SVG to PNG

   $path = 'path/to/file.png';

    $im = new Imagick();
    $im->readImageBlob($svg_value);

    /* png settings */
    $im->setImageFormat("png24");
    // $im->resizeImage(720, 445, imagick::FILTER_LANCZOS, 1);  /* Optional, if you need to resize */

    $im->writeImage($path); /* (or .jpg) */
    $im->clear();
    $im->destroy();
    
13.11.2015 / 16:04