I am using jsPDF to generate PDF documents through Appcelerator\'s Titanium. Now i need to add a simple pie chart with two segments. How could i do that in simplest way?
I know it has been inactive for almost a year, but since it doesn't have an accepted answer, I'll try to answer.
Adding chart to jsPDF
1.Convert chart to supported image format (JPEG or PNG encoded in base64) using HTML Canvas.
2.Make sure the image URL available to the addImage function.
Below is an example to add image to jsPDF doc without having to include raw base64 code. It is taken from jsPDF example.
function demoImages() {
// Because of security restrictions, getImageFromUrl will
// not load images from other domains. Chrome has added
// security restrictions that prevent it from loading images
// when running local files. Run with: chromium --allow-file-access-from-files --allow-file-access
// to temporarily get around this issue.
var getImageFromUrl = function(url, callback) {
var img = new Image(), data, ret = {
data: null,
pending: true
};
img.onError = function() {
throw new Error('Cannot load image: "'+url+'"');
};
img.onload = function() {
var canvas = document.createElement('canvas');
document.body.appendChild(canvas);
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
// Grab the image as a jpeg encoded in base64, but only the data
data = canvas.toDataURL('image/jpeg').slice('data:image/jpeg;base64,'.length);
// Convert the data to binary form
data = atob(data);
document.body.removeChild(canvas);
ret['data'] = data;
ret['pending'] = false;
console.log("data",data);
if (typeof callback === 'function') {
callback(data);
}
};
img.src = url;
return ret;
};
// Since images are loaded asyncronously, we must wait to create
// the pdf until we actually have the image data.
// If we already had the jpeg image binary data loaded into
// a string, we create the pdf without delay.
var createPDF = function(imgData) {
var doc = new jsPDF();
doc.addImage(imgData, 'JPEG', 10, 10, 50, 50);
doc.addImage(imgData, 'JPEG', 70, 10, 100, 120);
doc.save('output.pdf');
}
getImageFromUrl('thinking-monkey.jpg', createPDF);
}
Good Documentation of jsPDF
You will learn a lot of jsPDF features from their practical documentation. For example source code, don't download from GitHub, because some files are missing. You can download from here.
note:remove semicolon on the 312th line of basic.js to make the code works.
Cheers,...