Search code examples
javascriptreactjsjspdfhtml2canvashtml2pdf

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.


Solution

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