在 React 中将 HTML 转换为 PDF 时出现错误 -(未捕获的 TypeError: Object(...) is not a function)

IT技术 reactjs react-router
2021-04-27 21:00:05
//need to change it to the accurate data point
class Child extends Component {

  printDocument() {
    const input = document.getElementById('divToPrint');
    console.log(input);

    html2canvas(input).then((canvas) => {
        document.body.appendChild(canvas);
        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF();
        pdf.addImage(imgData, 'JPEG', 0, 0);
        pdf.save("download.pdf");
    }).catch(e => console.log(e));
  }

  render() {
    const mrrRecord = this.props.mrr;
    return (
      <html>
        <body>
          <div>
            <div id="divToPrint" className="mt4" {...css({
              backgroundColor: '#f5f5f5',
              width: '210mm',
              minHeight: '297mm',
              marginLeft: 'auto',
              marginRight: 'auto'
            })}>
              Note: Here the dimensions of div are same as A4 You Can add any component here
            </div> 
            <button onClick={this.printDocument}>Print</button>
          </div>
        </body>
      </html>
    );
  }
}

**注意:将 html 转换为画布时,我在以下内容中收到错误(Uncaught TypeError: Object(...) is not a function () )。我怀疑是因为 htmlcanvas 的输入是 html 元素,而 htmltocanvas 无法将 html 转换为正确的格式 -

html2canvas(input).then((canvas) => {
        document.body.appendChild(canvas);**
1个回答
  • 尝试使用安装 html2canvas npm install --save html2canvas
  • 然后将其作为 .js 文件导入到您的 js 文件中import * as html2canvas from 'html2canvas'

这对我有用!希望能帮助到你