Render Google Charts with Puppeteer

情到浓时终转凉″ 提交于 2020-03-05 03:10:00

问题


I am trying to figure ou the proper way to combine Puppeteer and the GoogleCharts library to render Bar charts and export a PNG image of the chart.

The basic layout, mostly inspired by the Puppeteer documentation seems to be something like that, to create a new page with a canvas element.

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    await page.setContent(`
            <!DOCTYPE html>
                <html>
                    <body>
                        <canvas id="chart" width="580" height="400"></canvas>
                    </body>
                </html>
            `);
    await browser.close();
})();

I have found this npm package to work with Google Charts: https://www.npmjs.com/package/google-charts. The chart.draw method seems to accept a DOM element in which it will render the chart.

According to the documentation of this package, the usage looks pretty simple.

const pie_1_chart = new GoogleCharts.api.visualization.PieChart(document.getElementById('chart1'));
pie_1_chart.draw(data);

How can I execute the draw method so that it render the chart inside the #canvas DOM element of the Puppeteer's page ?

Also, if you could give me an example of the proper way to export the page/canvas as a PNG image, that would be very appreciated.

NOTE: I browsed a lot to find an existing library/package that would do what I am trying to achieve, but the closest I could found is a TypeScript package for Chart.JS: https://github.com/SeanSobey/ChartjsNodePuppeteer. I am not familiar with TypeScript/ES6, so I don't know how I could adapt this library to make it work with the Google Charts library instead of Chart.JS.

Thanks


回答1:


I've set up a puppeteer code which loading Google Chart example page's Iframe and then screenshot the elementHandle #chart_div. This is way too much faster and simpler than loading another library.

Next you can create HTML DOM with a div element and set up a Google Chart with it and take screenshot the div element.

    const page = await browser.newPage()
    page.setDefaultNavigationTimeout(0);

    const goto = await page.goto('https://developers-dot-devsite-v2-prod.appspot.com/chart/interactive/docs/gallery/barchart_9a8ce4c79b8da3fa2e73bee14869e01b6f7fb5150dc7540172d60b5680259b48.frame')
    const wait = await page.waitForSelector('#chart_div > div', {'visible' : true, 'timeout' : 0})
    const elem = await page.$('#chart_div')
    const save = await elem.screenshot({path : 'googlechart.png' })


来源:https://stackoverflow.com/questions/58532808/render-google-charts-with-puppeteer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!