I'm using the code below to create a PDF of an image when the user clicks the "download" button. It's almost working fine but the problem is that it’s generating two PDF files instead of one.
(function($) {
$(document).ready(function() {
$('#downloadPDF').click(function() {
var doc = new jsPDF("p", "mm", "a4");
function getDataUri(url, callback) {
var image = new Image();
image.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size
canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size
canvas.getContext('2d').drawImage(this, 0, 0);
// Get raw image data
callback(canvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, ''));
// ... or get as Data URI
callback(canvas.toDataURL('image/png'));
};
image.src = url;
}
// Usage
getDataUri('/cover.png', function(dataUri) {
console.log('RESULT:', dataUri);
doc.addImage(dataUri, 'png', 0, 0, 210, 297, undefined, 'FAST');
doc.save('download.pdf')
});
})
})
})(jQuery)
I think it’s a loop, but I can't figure out how to solve it.
You seem to be calling callback
twice, once after the comment // Get raw image data
and another time after // ... or get as Data URI
. Remove one of the calls depending which case you want and it should solve the problem.