javascript - JSPDF - 如何将具有不同页面大小(高度和宽度)的多个图像导出到单个 pdf 文件

标签 javascript jquery jspdf

我有多个不同大小(高度和宽度)的图像需要使用 jspdf 转换为 PDF,但我无法使用 addPage() 函数来执行此操作。 是否可以将不同页面大小的图像导出为单个 pdf?

最佳答案

我实际上能够使用 addPage([imgWidth, imgHeight]) 添加具有不同图像大小的多个页面除了第一页,它由 new jsPDF('l', 'pt', 'a4') 定义。

可以使用 .deletePage(1) 删除空白的第一页。如果愿意,您还可以在首页添加一些文本。

<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>

更好但更复杂的方法是使用固定页面格式并计算图像大小和纵横比,然后相应地设置参数(并根据需要旋转图像)以使图像适合 纸张,即本例中的 a4。它可以是 pdf.addImage(img, 'JPEG', adjustedX, adjustedY, adjustedWidth, adjustedHeight, null, 'NONE');pdf.addImage(img, 'JPEG', adjustedX, adjustedY, adjustedWidth, adjustedHeight, null, -90);

有关代码示例,请参阅我的 answer to this question .

关于javascript - JSPDF - 如何将具有不同页面大小(高度和宽度)的多个图像导出到单个 pdf 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52294633/

相关文章:

javascript - 使用 jsPDF 和 html2canvas 将具有属性 "hidden"的 div 转换为 pdf

javascript - 为什么 ASP 经典 Select Case 分支中不会弹出 javascript 警报?

javascript - jQuery 是否在不设置普通事件处理程序的情况下处理事件?

javascript - 通过react-router重复使用相同的组件两次

delegates - jQuery 使用委托(delegate)会导致每个元素触发事件 (2 4 8 16 32)

javascript - 使用 jquery 验证表单输入字段

javascript - 如何迭代 json 对象列表?

javascript - 将下拉菜单的数据复制到选择时的文本框?

reactjs - React 将 Div 和 Table 组件转换为具有多个页面和 CSS 的 PDF