Generate PDF for Google Charts through Javascript

03 / Mar / 2015 by Mansi Arora 11 comments

In a previous blog, we learned, 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 an ‘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 an 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 an image inside the PDF, we add following text: ‘SOME ERROR OCCURRED WHILE ADDING IMAGE’, and continue further.

Hope this helps everyone!

FOUND THIS USEFUL? SHARE IT

comments (11)

  1. Nadeem Sayyad

    image is working fine but when you give the graph’s container to imageTags it’s giving an error jspdf.debug.js:4262 Uncaught TypeError: Failed to execute ‘drawImage’ on ‘CanvasRenderingContext2D': The provided value is not of type ‘(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)’
    at createDataURIFromElement (jspdf.debug.js:4262)
    at Object.jsPDFAPI.addImage (jspdf.debug.js:4559)
    at HTMLInputElement. (dashboard:1046)
    at HTMLInputElement.dispatch (jQuery-2.1.4.min.js:3)
    at HTMLInputElement.r.handle (jQuery-2.1.4.min.js:3)
    createDataURIFromElement @ jspdf.debug.js:4262
    jsPDFAPI.addImage @ jspdf.debug.js:4559
    (anonymous) @ dashboard:1046
    dispatch @ jQuery-2.1.4.min.js:3
    r.handle @ jQuery-2.1.4.min.js:3

    Reply
  2. Sunil

    HI Mansi, thanks for the code. I have an issue while trying this code, I am getting blurred image of chart, can you help me?

    Reply
  3. priya

    var imageTags = $(‘#graph_images img’);
    imageTags.length;

    If try to alert imageTags..it pops up as [object object]
    the length of the image tag is zero.so i am unable to see the graph in pdf format.

    Reply
  4. 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 -