The key is to calculate the aspect ratio of the image and the relative width / height ratio of the page. The following code is what I used to convert several images online to a PDF file. It will rotate the images depending on the orientation of the images / page and set the correct margin. For some reason, in the img.onload i function, img.onload does not increase automatically, but is equal to urls.length . I would appreciate it if you come up with an explanation. My project is to use images from online src. You should be able to change to suit your needs.
As for image rotation, if you see a blank page after rotation, it may just be outside the image. See this answer for details.
function exportPdf(urls) { let pdf = new jsPDF('l', 'mm', 'a4'); const pageWidth = pdf.internal.pageSize.getWidth(); const pageHeight = pdf.internal.pageSize.getHeight(); const pageRatio = pageWidth / pageHeight; for (let i = 0; i < urls.length; i++) { let img = new Image(); let j = i; img.src = urls[i]; img.onload = function () { const imgWidth = this.width; const imgHeight = this.height; const imgRatio = imgWidth / imgHeight; if (j > 0) { pdf.addPage(); } pdf.setPage(j + 1); if (imgRatio >= 1) { const wc = imgWidth / pageWidth; if (imgRatio >= pageRatio) { pdf.addImage(img, 'JPEG', 0, (pageHeight - imgHeight / wc) / 2, pageWidth, imgHeight / wc, null, 'NONE'); } else { const pi = pageRatio / imgRatio; pdf.addImage(img, 'JPEG', (pageWidth - pageWidth / pi) / 2, 0, pageWidth / pi, (imgHeight / pi) / wc, null, 'NONE'); } } else { const wc = imgWidth / pageHeight; if (1 / imgRatio > pageRatio) { const ip = (1 / imgRatio) / pageRatio; const margin = (pageHeight - ((imgHeight / ip) / wc)) / 4;
source share