JSPDF - How To Export Multiple Images With Various Page Size (height & Width) To A Single Pdf File
Solution 1:
I was actually able to add multiple pages with different image sizes using addPage([imgWidth, imgHeight])
except the first page, which is defined by new jsPDF('l', 'pt', 'a4')
.
The blank first page can be deleted using .deletePage(1)
. You can also add some text to the first page if you will.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js"
integrity="sha384-NaWTHo/8YCBYJ59830LTz/P4aQZK1sS0SneOgAvhsIl3zBu8r9RevNg5lHCHAuQ/"
crossorigin="anonymous"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<script>
function exportPdf(urls) {
let pdf = new jsPDF('l', 'pt', 'a4');
pdf.text(20, 20, 'Some text here');
for (let i = 0; i < urls.length; i++) {
let img = new Image();
img.src = urls[i];
img.onload = function () {
const imgWidth = this.width;
const imgHeight = this.height;
const imgRatio = imgWidth / imgHeight;
if (i >= 0) {
if (imgRatio > 0) {
pdf.addPage([imgWidth, imgHeight]);
}
else {
pdf.addPage([imgWidth, imgHeight], 'p');
}
}
pdf.setPage(i + 2);
pdf.addImage(img, 'JPEG', 0, 0, imgWidth, imgHeight, null, 'NONE');
if (i == urls.length - 1) {
pdf.save('Photos.pdf');
}
}
}
}
</script>
A better, but more complicated, way is to use fixed page format and calculate the image size and aspect ratio and then set the parameters (and rotate the image if needed) accordingly so that the image can fit the paper, i.e., a4 in this case. It can be either pdf.addImage(img, 'JPEG', adjustedX, adjustedY, adjustedWidth, adjustedHeight, null, 'NONE');
or pdf.addImage(img, 'JPEG', adjustedX, adjustedY, adjustedWidth, adjustedHeight, null, -90);
For a code sample, see my answer to this question.
Post a Comment for "JSPDF - How To Export Multiple Images With Various Page Size (height & Width) To A Single Pdf File"