I am using jspdf to convert an image into a PDF.
I have converted the image into a URI using base64encode. But the problem is that there are no errors or warnings sh
I had the same issue with Base64 not being defined. I went to an online encoder and then saved the output into a variable. This probably is not ideal for many images, but for my needs it was sufficient.
function makePDF(){
var doc = new jsPDF();
var image = "data:image/png;base64,iVBORw0KGgoAA..";
doc.addImage(image, 'JPEG', 15, 40, 180, 160);
doc.save('title');
}
In TypeScript, you can do:
private getImage(imagePath): ng.IPromise<any> {
var defer = this.q.defer<any>();
var img = new Image();
img.src = imagePath;
img.addEventListener('load',()=>{
defer.resolve(img);
});
return defer.promise;
}
Use the above function to getimage object. Then the following to add to pdf file:
pdf.addImage(getImage(url), 'png', x, y, imagewidth, imageheight);
In plain JavaScript, the function looks like this:
function (imagePath) {
var defer = this.q.defer();
var img = new Image();
img.src = imagePath;
img.addEventListener('load', function () {
defer.resolve(img);
});
return defer.promise;
};
For result in base64, before convert to canvas:
var getBase64ImageUrl = function(url, callback, mine) {
var img = new Image();
url = url.replace("http://","//");
img.setAttribute('crossOrigin', 'anonymous');
img.onload = function () {
var canvas = document.createElement("canvas");
canvas.width =this.width;
canvas.height =this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL(mine || "image/jpeg");
callback(dataURL);
};
img.src = url;
img.onerror = function(){
console.log('on error')
callback('');
}
}
getBase64ImageUrl('Koala.jpeg', function(img){
//img is a base64encode result
//return img;
console.log(img);
var doc = new jsPDF();
doc.setFontSize(40);
doc.text(30, 20, 'Hello world!');
doc.output('datauri');
doc.addImage(img, 'JPEG', 15, 40, 180, 160);
});
Though I'm not sure, the image might not be added because you create the output before you add it. Try:
function convert(){
var doc = new jsPDF();
var imgData = 'data:image/jpeg;base64,'+ Base64.encode('Koala.jpeg');
console.log(imgData);
doc.setFontSize(40);
doc.text(30, 20, 'Hello world!');
doc.addImage(imgData, 'JPEG', 15, 40, 180, 160);
doc.output('datauri');
}
The above code not worked for me. I found new solution :
var pdf = new jsPDF();
var img = new Image;
img.onload = function() {
pdf.addImage(this, 10, 10);
pdf.save("test.pdf");
};
img.crossOrigin = "";
img.src = "assets/images/logo.png";
if you have
ReferenceError: Base64 is not defined
you can upload your file here you will have something as :
data:image/jpeg;base64,/veryLongBase64Encode....
on your js do :
var imgData = 'data:image/jpeg;base64,/veryLongBase64Encode....'
var doc = new jsPDF()
doc.setFontSize(40)
doc.addImage(imgData, 'JPEG', 15, 40, 180, 160)
Can see example here