Pterrat
Pterrat

Reputation: 1710

html2canvas and React to generate pdf doesn't work

I'm using html2canvas and jsPdf to generate Pdf from HTML for one react application.

onClick of my download button I call this function :

printDocument() {
    const input = document.getElementById('divToOfferInfo');
    const pdf = new jsPDF();
    if (pdf) {
      html2canvas(input, {
        useCORS: true
      })
        .then(canvas => {
          const imgData = canvas.toDataURL('image/png');
          console.log(imgData); //Maybe blank, maybe full image, maybe half of image
          pdf.addImage(imgData, 'PNG', 10, 10);
          pdf.save('download.pdf');
        });
    }
}

The result is totally random. The result of canvas is full, half or blank but not right.

I think that issue is about rendering of React.

Thank you for your help.

Upvotes: 0

Views: 8437

Answers (2)

burakkp
burakkp

Reputation: 53

You can use like this. I am using this code and it is working well.

savePDF() {

        const printArea = document.getElementById("printWrapper");

        html2canvas(printArea).then(canvas => {
            const dataURL = canvas.toDataURL();
            const pdf = new jsPDF();

            pdf.addImage(dataURL, 'JPEG', 20, 20, 180, 160);

            pdf.save('saved.pdf')
        })

    }

Upvotes: 3

Pterrat
Pterrat

Reputation: 1710

I found an alternative solution. Instead to use html2canvas lib, we can use dom-to-image lib. It's working with it.

import domtoimage from 'dom-to-image';
...
        printDocument() {
            const input = document.getElementById('divToOfferInfo');
            const pdf = new jsPDF();
            if (pdf) {
              domtoimage.toPng(input)
                .then(imgData => {
                  pdf.addImage(imgData, 'PNG', 10, 10);
                  pdf.save('download.pdf');
                });
            }
        }

Upvotes: 4

Related Questions