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
This worked for me in Angular 2:
var img = new Image()
img.src = 'assets/sample.png'
pdf.addImage(img, 'png', 10, 78, 12, 15)
jsPDF version 1.5.3
assets directory is in src directory of the Angular project root
You defined Base64? If you not defined, occurs this error:
ReferenceError: Base64 is not defined
First you need to load the image, convert data, and then pass to jspdf (in typescript):
loadImage(imagePath): ng.IPromise<any> {
var defer = this.q.defer<any>();
var img = new Image();
img.src = imagePath;
img.addEventListener('load',()=>{
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL('image/jpeg');
defer.resolve(dataURL);
});
return defer.promise;
}
generatePdf() {
this.loadImage('img/businessLogo.jpg').then((data) => {
var pdf = new jsPDF();
pdf.addImage(data,'JPEG', 15, 40, 180, 160);
pdf.text(30, 20, 'Hello world!');
var pdf_container = angular.element(document.getElementById('pdf_preview'));
pdf_container.attr('src', pdf.output('datauristring'));
});
}
maybe a little bit late, but I come to this situation recently and found a simple solution, 2 functions are needed.
load the image.
function getImgFromUrl(logo_url, callback) {
var img = new Image();
img.src = logo_url;
img.onload = function () {
callback(img);
};
}
in onload event on first step, make a callback to use the jspdf doc.
function generatePDF(img){
var options = {orientation: 'p', unit: 'mm', format: custom};
var doc = new jsPDF(options);
doc.addImage(img, 'JPEG', 0, 0, 100, 50);}
use the above functions.
var logo_url = "/images/logo.jpg";
getImgFromUrl(logo_url, function (img) {
generatePDF(img);
});
No need to add any extra base64 library. Simple 5 line solution -
var img = new Image();
img.src = path.resolve('sample.jpg');
var doc = new jsPDF('p', 'mm', 'a3'); // optional parameters
doc.addImage(img, 'JPEG', 1, 2);
doc.save("new.pdf");
I find it useful.
var imgData = 'data:image/jpeg;base64,verylongbase64;'
var doc = new jsPDF();
doc.setFontSize(40);
doc.text(35, 25, "Octonyan loves jsPDF");
doc.addImage(imgData, 'JPEG', 15, 40, 180, 180);
http://mrrio.github.io/jsPDF/