Google Charts as Image

前端 未结 5 2053
南旧
南旧 2021-02-13 19:36

I am trying to use Google charts to embed images of charts in the emails. So Each user will have a unique graph.

Can we use the API and embed a unique URL that will ren

5条回答
  •  独厮守ぢ
    2021-02-13 20:06

    To render Google Charts as an image, you can use Google Charts Node, an open-source project that uses Puppeteer to render the charts.

    google-charts-node is available as an NPM library and can be used like so:

    const GoogleChartsNode = require('google-charts-node');
    
    function drawChart() {
      const data = google.visualization.arrayToDataTable([
        ['City', '2010 Population',],
        ['New York City, NY', 8175000],
        ['Los Angeles, CA', 3792000],
        ['Chicago, IL', 2695000],
        ['Houston, TX', 2099000],
        ['Philadelphia, PA', 1526000]
      ]);
    
      const options = {
        title: 'Population of Largest U.S. Cities',
        chartArea: {width: '50%'},
        hAxis: {
          title: 'Total Population',
          minValue: 0
        },
        vAxis: {
          title: 'City'
        }
      };
    
      const chart = new google.visualization.BarChart(container);
      chart.draw(data, options);
    }
    
    // Render the chart to image
    const image = await GoogleChartsNode.render(drawChart);
    

    Now you can save the image buffer as a file or return it as an HTTP response, etc. It looks like this:

    The Google Charts node renderer is also available as a web service, as described here, so you can use it in any language besides JS.

    If you're interested in using a more universal open-source chart format, you can also use QuickChart, a Chart.js render API.

提交回复
热议问题