关于javascript:html2canvas和React生成pdf不起作用

html2canvas and React to generate pdf doesn't work

我正在使用html2canvas和jsPdf从HTML为一个React应用程序生成Pdf。

点击我的下载按钮后,我将其称为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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');
        });
    }
}

结果是完全随机的。画布的结果为完整,一半或空白,但不正确。

我认为这个问题与React的呈现有关。

感谢您的帮助。


我找到了替代解决方案。代替使用html2canvas lib,我们可以使用dom-to-image lib。正在使用它。

1
2
3
4
5
6
7
8
9
10
11
12
13
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');
                });
            }
        }


您可以这样使用。我正在使用此代码,并且运行良好。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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')
        })

    }