【问题标题】:Download a react component using jsPdf and html2canvas [closed]使用 jsPdf 和 html2canvas 下载反应组件 [关闭]
【发布时间】:2020-11-16 06:24:52
【问题描述】:

我正在使用 html2canvas 和 jspdf 包来下载一个简单的组件,但是当我点击下载时,我得到一个没有任何内容的空白 pdf 页面,并且屏幕上没有错误, 这是我的代码:

import React, {Component, PropTypes} from 'react';
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
import Pie from './Pie.js';

class Qu extends Component {
  constructor(props) {
    super(props);
  }

  printDocument() {
    const input = document.getElementById('divToPrint');
    html2canvas(input)
      .then((canvas) => {
        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF();
        pdf.addImage(imgData, 'JPEG', 0, 0);
        // pdf.output('dataurlnewwindow');
        pdf.save("download.pdf");
      })
    ;
  }

  render() {
    return (<div>
    
      <div id="divToPrint" className="mt4">
        <div>Title of Component</div> 
        <div><Pie /></div>
        <div className="mb5">
        <button onClick={this.printDocument}>Print</button>
      </div>
      </div>
    </div>);
  }
}
export default Qu;

【问题讨论】:

    标签: reactjs jspdf html2canvas


    【解决方案1】:
    import React, {Component, PropTypes} from 'react';
    import html2canvas from 'html2canvas';
    import jsPDF from 'jspdf';
    import Pie from './Pie.js';
    
    class Qu extends Component {
      constructor(props) {
        super(props);
      }
    
      printDocument() {
        const input = document.getElementById('divToPrint');
        html2canvas(input)
          .then((canvas) => {
            let imgWidth = 208;
            let imgHeight = canvas.height * imgWidth / canvas.width;
            const imgData = canvas.toDataURL('img/png');
            const pdf = new jsPDF('p', 'mm', 'a4');
            pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
            // pdf.output('dataurlnewwindow');
            pdf.save("download.pdf");
          })
        ;
      }
    
      render() {
        return (<div>
        
          <div id="divToPrint" className="mt4">
            <div>Title of Component</div> 
            <div><Pie /></div>
            <div className="mb5">
            <button onClick={this.printDocument}>Print</button>
          </div>
          </div>
        </div>);
      }
    }
    export default Qu;
    

    请试试上面的代码。

    【讨论】:

    • 你好,我已经尝试过这段代码,但仍然有一个空白的 pdf
    • 感谢它在清理缓存后现在工作,但它只打印一个 pdf 页面,如果组件的内容超过一页,它会打印一半页面,任何建议如何制作打印多页?
    • 您需要将图像高度与页面高度进行比较并手动添加页面。如果您使用表格,则有一个支持多页的 jspdf-autotalbe 插件。但是对于文字和图片,就得手动计算了。
    猜你喜欢
    • 2020-03-25
    • 2021-06-05
    • 1970-01-01
    • 2021-11-28
    • 2021-12-26
    • 1970-01-01
    • 2020-12-11
    • 2016-04-05
    相关资源
    最近更新 更多