javascriptimagepdfjspdfhtml2canvas

Html2canvas / jspdf cut off image


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

This is what I want

My destination

And this is what I get in my pdf:

My current status

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


Solution

  • 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: https://github.com/eKoopmans/html2pdf.js/issues/39.

    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.