How To Add Several Images Onto A Pdf Using Jspdf
Solution 1:
You are starting the PDF creation, and then waiting for each image. Instead of doing such way, my proposal is to preload all images and wait for a callback when all images have been downloaded and are ready to print in jsPDF by invoking the addImage
function.
I did it in following way some time ago, as a part of a more complex jsPDF plugin
functionPicture(src) {
this.src = src;
this.img = null;
}
functionPreloader() {
this.pictures = [];
this.onpicturesloaded = null;
}
Preloader.prototype.setPicture = function(src) {
var id = src.split("/").pop().split(".")[0].toLowerCase();
this.pictures[id] = newPicture(src);
returnthis.pictures[id];
};
Preloader.prototype.loadPictures = function() {
var self = this, pictures = self.pictures, n = 0;
for(var id in pictures) {
if(pictures.hasOwnProperty(id)) {
var pic = self.pictures[id];
n++;
}
}
for(var id in pictures) {
if(pictures.hasOwnProperty(id)) {
var pic = self.pictures[id];
var decrease = function(e) {
if(--n == 0) {
self.onpicturesloaded();
}
}
var img = newImage();
img.onload = function() {
var pic = self.pictures[this.alt];
pic.img = this;
decrease();
};
img.alt = id;
img.src = pic.src;
}
}
};
I'm using the stripped filename as ìd
to get directly the associated image, for that reason there is this slightly overhead of the double loop inside the loadPictures
function, if you find this too bad, feel free to change it to a true array, where you can get directly the picture count as pictures.length
.
This id
is then also used in jsPDF as alias
for each image, to speed up the whole process, whereby the full image path is stored instead in picture.src
.
This is (more pr less) the usage of all that stuff above:
var pl = newPreloader();
pl.setPicture("pdf/a.jpg");
pl.setPicture("pdf/b.jpg");
pl.setPicture("pdf/c.jpg");
pl.onpicturesloaded = function() {
var doc = newjsPDF();
var pic = pl.pictures["a"];
doc.addImage(pic.img, "jpg", 10, 10, 100, 100, pic.img.alt, "FAST");
// add more images, print text, and so on
doc.save('mydocument.pdf');
};
pl.loadPictures();
Please note, this is just an extract on-the-fly of that jsPDF plugin, without some parts which i needed for example, to draw inside a canvas
and add on the fly the picture data to the PDF.
So, I am sure this can be further simplified and stripped down, but anyway, you can get the idea.
Post a Comment for "How To Add Several Images Onto A Pdf Using Jspdf"