Html2canvas / jspdf 截断图像

3

我想要将项目中的一个元素制作成PDF文件,但是图像总是在右侧被裁剪掉了。我使用了jspdf和html2canvas。

这是我想要的效果:

我的目标

而这是我在PDF中得到的结果:

我的当前状态

正如您所看到的,图像无法适应右侧宽度。

我尝试过以下方法:

Html2Canvas图片被裁剪 https://tutel.me/c/programming/questions/44796908/jspdf+html2canvas++html++images+cut+off+capture https://www.reddit.com/r/learnjavascript/comments/cnn7q4/anyone_experience_with_jspdf_my_image_is_cut_off/ html2canvas离屏

但是这些方法都不起作用。

以下是我的代码:

const offerteId = $(e).data("id"),
              card = document.querySelector('.body-pdf-' + offerteId + ''),
              filename  = offerteId + '.pdf';

        html2canvas(card).then(function(canvas) {
            const img = canvas.toDataURL("image/png"),

            pdf = new jsPDF({
                orientation: 'p',
                unit: 'mm',
                format: 'a4',
            });

            // Optional - set properties on the document
            pdf.setProperties({
                title: offerteId.toString(),
                subject: 'Offerte: ' + offerteId.toString(),
            });

            const imgProps = pdf.getImageProperties(img);
            const pdfWidth = pdf.internal.pageSize.getWidth();
            const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;

            pdf.addImage(img, 'JPEG', 0, 0, pdfWidth, pdfHeight);
            pdf.save(filename);
        });

希望有人能够帮忙

4个回答

3
当html2canvas渲染图像时,它将捕获屏幕上可见区域。然后,对我而言唯一有效的方法是在我的CSS中添加以下代码。
.html2canvas-container { 
    width: 3000px; 
    height: 3000px; 
}

这段样式代码用于防止html2canvas将渲染限制在可视区域内。


Fernandes de Lima:你的解决方案对我很有用!谢谢!由于我正在使用Bootstrap,我还将所有被截断的div中的类“container”替换为“container-fluid”。 - ArtFranco

2
我今天遇到了类似的问题。我解决这个问题的方法是因为你在官方github上提出的一个问题:https://github.com/eKoopmans/html2pdf.js/issues/39

在将页面渲染成PDF之前,将html和body标签的宽度设置为794px,页面的宽度就可以很好地适应了。这对我来说已经足够好了,虽然这可能不是正确的答案。


1
啊,好的,我明白了!我不再使用jspdf和html2canvas了...现在我使用TCPDF,因为它对我来说是最好的选择。但我会将你的答案标记为正确答案,因为也许这会帮助其他遇到同样问题的人。 - Mark_

1

我曾经遇到过同样的问题,解决方法是设置窗口宽度与主页面容器以及html2canvas宽度相同。

function exportPDF(div, fileName) {
    const invoice = this.document.getElementById(div == null ? "generalDiv" : div);
    invoice.style.width =  $(window).width()+"px";
    var opt = {
        margin: 1,
        filename: fileName+'.pdf',
        image: { type: 'jpeg', quality: 0.98 },
        html2canvas: { scale: 1, width: $(window).width()},
        jsPDF: { unit: 'in', format: 'a0', orientation: 'portrait' }
    };
    html2pdf().from(invoice).set(opt).save();
}

1
每当html2canvas更改您的元素的宽度和高度时,您需要更改'card'元素。您应该使用scale: 1,然后html2Canvas将使用您在第一次设置的宽度和高度。
const options = { scale: 1 }
html2canvas(card, options).then(function(canvas) { /*your code*/ }

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