Html2canvas / jspdf cut off image

题意:Html2canvas / jsPDF 截取的图像被裁剪。

问题背景:

I want to make a pdf of an element in my project, but the image keeps getting cut off at the right. I use jspdf and html2canvas

我想制作项目中某个元素的 PDF,但图像在右侧总是被裁剪。我使用的是 jsPDF 和 html2canvas。

This is what I want

这就是我想要的。

And this is what I get in my pdf:

而这就是我在 PDF 中得到的:

As you can see, the image doesn't fit the right width.

正如你所看到的,图像没有适应右侧的宽度。

I have tried the following:

我尝试了以下方法:

Html2Canvas image is getting cut 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 offscreen

But none of these work.

但这些都没有效果。

This is my code:        这是我的代码:

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);
        });

Hopefully someone can help

"希望有人能帮忙"

问题解决:

I have been having a similar issues today. The way I got round it was because of a question you asked on the official github: 

"今天我也遇到了类似的问题。我解决的方法是因为你在官方 GitHub 上问了一个问题:"Canvas size in PDF with custom html2canvas · Issue #39 · eKoopmans/html2pdf.js · GitHub.

By setting the width of html & body tags to 794px BEFORE rendering the page to PDF, the page fits the width nicely. It is working for me so that's good enough for me although it might not be the right answer.

"通过在渲染 PDF 页面之前将 html 和 body 标签的宽度设置为 794px,页面的宽度很好地适配了。这对我来说有效,所以我觉得可以了,尽管这可能不是正确的答案。"

猜你喜欢

转载自blog.csdn.net/suiusoar/article/details/143445998