JSPDF - How to export multiple images with various page size (height & width) to a single pdf file

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-17 21:32:13

问题


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?


回答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.



来源:https://stackoverflow.com/questions/52294633/jspdf-how-to-export-multiple-images-with-various-page-size-height-width-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!