Keep Coding

Never Stop Learning

How to convert Google Chart to PNG and PDF

chart_printableIf you use Google Chart for reporting and visualising data you may want to have a functionality of exporting charts to PNG and PDF files. Here I will guide you how to quickly convert Google Chart to PNG and PDF. For those of you interested in using Google Chart I recommend you to have a look at this tutorial that I made a while ago.


Before being able to export an interactive Google Chart to PDF we need to access the chart as a PNG first. Luckily, this has been described here by Google. But let’s quickly review it together:

Accessing Google Chart as a PNG

Considering the example explained here, using getImageURI() method we can modify the existing code to get PNG encoding of the chart:

Exporting an image to PDF

By having an image we can easily convert it to PDF. There are a variety of ways to do that. For example we can use HTML to PDF converters such as TCPDF or DOMPDF. Here you can find all the steps to use DOMPDF:

1. Download the latest release from here (v0.6.1 at the time of writing this).
2. Unzip the file and upload the folder to your host.
3. Create a form with an action pointing to the file that handles converting HTML to PDF. In my case the file is saveChartPDF.php:

4. Content of saveChartPDF.php simply is:

5. Now you just need to have this JavaScript code in the file that contains the form:

What does it do? easy! It just populates the value of hidden input (in this case htmlContentHidden) with the content of pie_chart_div div and submits the form when the button is clicked. You can check the demo here.

6 Comments

  1. Can you help me?
    Notice: Undefined variable: pie_chart_data

  2. Houssem MJID

    15 May 2015 at 8:11 pm

    Great work !!

  3. Hei Ehsan,

    thank u for your tutorial. I have tried a tutorial from you but the result is blank page in pdf. whats wrong?

    thanks

  4. Hi

    Why this code is not working ? it’s producing blank pdf.

  5. Hi, thanks for the tutor. Just now when I test your export to pdf demo, I got an error message says error.

  6. Hi, could you upgrade to the dompdf 0.7.0 version?

Leave a Reply

Your email address will not be published.

*