jsPDF文档/页面旋转

3
有没有办法使用 jsPDF 旋转整个文档或页面?我正在寻找类似于以下的东西:
var doc = new jsPDF('p', 'mm', [137, 66]);
// Add content...
doc.rotate(90); // <---- Something like this
doc.save('test.pdf');

2
我没有找到“文档/页面旋转”问题的正确答案,但我成功地实现了我想要的效果。基本上,当我添加一张图片时,我只需使用9个参数来设置旋转。doc.addImage(img,'png',x,y,height,width,null,null,-90); - Oleksandr Tserkovnyi
1个回答

1
我有一个项目需要从URL中导出图像作为完整页面的PDF。在这种情况下,你不能简单地使用doc.addImage(img,'png',xy,height,width,null,null,-90),因为图像会超出边界。请参见此stackoverflow answer以获取详细信息。您需要计算图像的宽高比和页面的相对宽高比来重置x y,width,height。以下是我用来实现这一点的代码。
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();
        img.src = urls[i];
        img.onload = function () {
            const imgWidth = this.width;
            const imgHeight = this.height;
            const imgRatio = imgWidth / imgHeight;
            if (i > 0) { pdf.addPage(); }
            pdf.setPage(i + 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; // why not 2?
                    pdf.addImage(img, 'JPEG', (pageWidth - (imgHeight / ip) / wc) / 2, -(((imgHeight / ip) / wc) + margin), pageHeight / ip, (imgHeight / ip) / wc, null, 'NONE', -90);
                }
                else {

                    pdf.addImage(img, 'JPEG', (pageWidth - imgHeight / wc) / 2, -(imgHeight / wc), pageHeight, imgHeight / wc, null, 'NONE', -90);
                }
            }
            if (i == urls.length - 1) {
                pdf.save('Photo.pdf');
            }
        }
    }
}

我尝试了你的解决方案,它很好用,但是在90度旋转模式下的图像出现在pdf的中心。我们有没有办法从右侧开始填充图像? - Vipin Yadav
我希望图像位于页面中心。但是,如果你想从右侧开始,你可以重新计算数学。我认为原则应该是相同的。 - Weihui Guo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接