Generate PDF for Google Charts through Javascript

03 / Mar / 2015 by Mansi Arora 6 comments

In a previous blog, we learnt, how to draw a google chart.

Let’s say, I have 5 graphs on my page and I want to generate a PDF which contains these graphs using a JavaScript.

For that we will use jsPDF plugin.

Step 1. Create a hidden-empty DIV, to store graph-images:

<div id='graph-images' style='display:none'></div>

Step 2. Update your ‘drawMyChart()’ function to get image of chart

var data = ...
var options =
   ...
}

var chart = new google.visualization.ComboChart(document.getElementById('chart_div')); /* Define your ComboChart object */
google.visualization.events.addListener(chart, 'ready', function () {
  var content = '<img src="' + chart.getImageURI() + '">';
  $('#graph-images').append(content);
}); /* Adds a listener to make a image of chart inside a #graph-images*/

chart.draw(data, options); /* draw the chart using above define 'data' and 'options' */

Google Chart API provides access to a PNG image of a chart, using the getImageURI() method. When the chart object is ready a ‘img’ tag is appended in the ‘#graph-images’ DIV.

Step 3 : Include plugin javascript files : jspdf.js, FileSaver.js, zlib.js, png.js,jspdf.plugin.addimage.js, and jspdf.plugin.png_support.js

Step 4 : Add functionality to generate a PDF of the above saved chart-images :

function generatePDF() {
var doc = new jsPDF('p', 'pt', 'a4', false) /* Creates a new Document*/
doc.setFontSize(15); /* Define font size for the document */
var yAxis = 30;
var imageTags = $('#graph-images img');
for (var i = 0; i < imageTags.length; i++) {
        if (i % 2 == 0 && i != 0) { /* I want only two images in a page */
            doc.addPage();  /* Adds a new page*/
            yAxis = 30; /* Re-initializes the value of yAxis for newly added page*/
        }
        var someText = 'Chart '+(i+1);
        doc.text(60, yAxis, someText); /* Add some text in the PDF */
        yAxis = yAxis + 20; /* Update yAxis */
        doc.addImage(imageTags[i], 'png', 40, yAxis, 530, 350, undefined, 'none');
        yAxis = yAxis+ 360; /* Update yAxis */
    }
doc.save('Chart_Report' + '.pdf') /* Prompts user to save file on his/her machine */
}

Here we are adding a chart heading and the image for all the charts drawn.

Step 5 : Whenever there’s an error adding any image in the PDF, jsPDF API throws a error ‘throw new Error()’ and stops any further processing. For this we can provide exception handling :

 try {
        doc.addImage(imageTags[i], 'png', 40, yAxis, 530, 350, undefined, 'none');
        yAxis = yAxis+ 360; /* Update yAxis */
    }
    catch (e) {
        doc.text(120, yAxis + 30, 'SOME ERROR OCCURRED WHILE ADDING IMAGE');
        yAxis = yAxis + 50 /* Update yAxis */
    }

Our code remains the same, we just need to move doc.addImage(*, *, *, *, *, *) into the try-catch block, so that whenever any error occurs while inserting image inside the PDF, we add this text : ‘SOME ERROR OCCURRED WHILE ADDING IMAGE’, and continue further.

Hope this helps everyone!

FOUND THIS USEFUL? SHARE IT

comments (6)

  1. Akhil Balakrishnan

    Another small error in the code.

    doc.save(‘Chart_Report’ + ‘.pdf’) line should be inside the generatePDF function. It’s currently outside the function.

    Other than that the code works great. Thank you for saving my day!

    Reply

Leave a comment -