Mark_
Mark_

Reputation: 135

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

Upvotes: 3

Views: 13221

Answers (6)

Ani Shadrack
Ani Shadrack

Reputation: 1

const pdfContent = this.createPDFTransactionReceiptContent();
const iframe = document.createElement('iframe');
document.body.appendChild(iframe);

iframe.style.position = 'absolute';
iframe.style.left = '-9999px';

iframe.onload = () => {
  const contentDocument = iframe.contentDocument;
  if (contentDocument) {
    contentDocument.body.style.position = 'relative';

    // Manually set the width and height to fit A4 size
    const pdfWidth = 210; // A4 width in mm
    const pdfHeight = 297; // A4 height in mm

    // Temporarily set the iframe's size to match the A4 ratio for proper scaling
    const aspectRatio = pdfWidth / pdfHeight;
    // const iframeWidth = 1024; // Example width, could be adjusted as needed
    const iframeWidth = 550; // Example width, could be adjusted as needed
    const iframeHeight = iframeWidth / aspectRatio;
    iframe.style.width = `${iframeWidth}px`;
    iframe.style.height = `${iframeHeight}px`;

    setTimeout(() => {
      html2canvas(contentDocument.body, { scale: 3.5 })
        .then((canvas: HTMLCanvasElement) => {
          const imgData = canvas.toDataURL('image/png', 0.7);
          const pdf = new jsPDF('p', 'mm', 'a4');

          const imgProps = pdf.getImageProperties(imgData);
          const canvasWidth = imgProps.width;
          const canvasHeight = imgProps.height;

          // Calculate the new height based on the aspect ratio
          const newPdfHeight = (canvasHeight * pdfWidth) / canvasWidth;

          // Ensure the content fits on a single page
          // pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, newPdfHeight);
            pdf.addImage(
              imgData,
              'SVG',
              0,
              0,
              210,
              newPdfHeight,
              'someAlias',
              'FAST'
            );

          pdf.save('transaction_receipt.pdf');
          document.body.removeChild(iframe);
        })
        .catch((err: Error) => {
          // console.error('Error creating canvas:', err);
          document.body.removeChild(iframe);
        });
    }, 100);
  }
};

const doc = iframe.contentDocument || iframe.contentWindow?.document;
if (doc) {
  doc.open();
  doc.write(pdfContent);
  doc.close();
}

Upvotes: -1

user11072739
user11072739

Reputation: 1

//Before Calling the html2canvas
//change the body width

var html_element = document.getElementByID("div_to_capture");
var ele_width = html_element.scrollWidth; 

//This will help capture the image beyond visible window
document.body.style = "width: " + (ele_width+100) + "px";

html2canvas(html_element).then(function(canvas) {
    //your code
});

Upvotes: -1

Diego Rojas
Diego Rojas

Reputation: 19

I had the same issue, and i solve it by setting up the window width to my main page container and then to the html2canvas width, with the same value.

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

Upvotes: 0

When html2canvas renders the image, it limits the capture to the visible area of the screen. Then, the only thing that worked for me, was to add the following code into my css.

.html2canvas-container { 
    width: 3000px; 
    height: 3000px; 
}

This style code is used to prevent html2canvas limit the rendering to the viewable area.

Upvotes: 2

Colin Wiseman
Colin Wiseman

Reputation: 868

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.

Upvotes: 3

Jean Medes Dinelli
Jean Medes Dinelli

Reputation: 11

Everytime html2canvas changes width and height of your element, in your case, change the 'card' element.

You should use scale: 1, and html2Canvas will be with the width and height that you set on the first place.

const options = { scale: 1 }
html2canvas(card, options).then(function(canvas) { /*your code*/ }

Upvotes: 1

Related Questions