[英]jsPDF How to set images to fit with various page size height & width to a single PDF file
[英]JSPDF - How to export multiple images with various page size (height & width) to a single pdf file
我有多个大小(高度和宽度)不同的图像,需要使用jspdf转换为PDF,但是我很难使用addPage()
函数来做到这一点。 是否可以将具有不同页面大小的图像导出到单个pdf?
实际上addPage([imgWidth, imgHeight])
除了第一页是由new jsPDF('l', 'pt', 'a4')
定义的,我实际上可以使用addPage([imgWidth, imgHeight])
添加具有不同图像大小的多个页面。
可以使用.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);
有关代码示例,请参见我对这个问题的回答 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.