Generate PDF for Google Charts through Javascript
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:
[java]
<div id=’graph-images’ style=’display:none’></div>
[/java]
Step 2. Update your ‘drawMyChart()’ function to get image of chart
[java]
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’ */
[/java]
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:
[java]
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 */
}
[/java]
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:
[java]
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 */
}
[/java]
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!
doc.text( 60, yAxis, someText,); after this function call, its going to jspdf.js file and giving error while calling “getCharWidthsArray(text, options)” function where options are undefined.
“Unhandled exception at line 1607, column 17 in http://localhost:32401/Scripts/jspdf.js
0x800a138f – JavaScript runtime error: Unable to get property ‘widths’ of undefined or null reference”
I am getting an error $ is not defined. Please help
you need to include jquery in your html.
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
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?
Basically its the image font which is blurred and of larger size..
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.
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!
Could you please put the complete code to dowloand
My browser displays only the chart and no other png values for the chart. It says $ is not defined.
Did you include jQuery in your page ?
‘$’ is a shorthand notation for jQuery
im getting error code on pdf ‘SOME ERROR OCCURRED WHILE ADDING IMAGE’.not able to add image on pdf page
im getting error code on pdf ‘SOME ERROR OCCURRED WHILE ADDING IMAGE’.not able to add image on pdf page
no image stored in imageTags.