我有多个不同大小(高度和宽度)的图像需要使用 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/