I have multiple images of different size(height & width) that need to be converted to PDF using jspdf, but I have trouble to use addPage()
function to do that.
Is it possible to export images with different page sizes to a single pdf?

- 3,669
- 5
- 34
- 56

- 21
- 2
- 6
-
Do you maybe have a short demo that describes the problem? – Arend Sep 12 '18 at 12:01
-
Is it possible or not to add different page size in single pdf using jspdf – Rahul Sharma Sep 12 '18 at 12:19
1 Answers
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.

- 3,669
- 5
- 34
- 56