Search code examples
c#google-visualization

Get image from Google API Chart


I have a C# code running on server and I need to generate some charts using Google API Chart and then save those to images on server.

I remember Google API Chart had a wizard where you can create the chart but now it's 100% JavaScript so don't know if there is a way to do it.

Is that possible?


Solution

  • once the 'ready' has fired on the chart,
    you can use getImageURI to get a base 64 string,
    which can be saved as .PNG,
    or included in an img tag,
    as in the following example...

    to use a frozen version, you can replace 'current' with the latest save -- '45'

    google.charts.load('current', {
      callback: function () {
        var data = new google.visualization.DataTable();
        data.addColumn('date', 'Date');
        data.addColumn('number', '2005');
        data.addColumn('number', '2006');
        data.addRows([
           [new Date('01/01/2016'), 200, 210],
           [new Date('01/02/2016'), 190, 220],
           [new Date('01/03/2016'), 205, 200],
           [new Date('01/04/2016'), 220, 230],
           [new Date('01/05/2016'), 212, 210],
           [new Date('01/06/2016'), 185, 193],
           [new Date('01/07/2016'), 196, 207]
        ]);
        var options = {
          height: 400
        };
    
        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    
        google.visualization.events.addListener(chart, 'ready', function () {
          document.getElementById('image_div').innerHTML = '<img alt="Chart" src="' + chart.getImageURI() + '">';
        });
    
        chart.draw(data, options);
      },
      packages: ['corechart']
    });
    <script src="https://www.gstatic.com/charts/loader.js"></script>
    <div>Chart</div>
    <div id="chart_div"></div>
    <div>Image</div>
    <div id="image_div"></div>