Search code examples
reactjsjspdfhtml2canvas

Download a react component using jsPdf and html2canvas


i'm using html2canvas and jspdf packages to download a simple component but when i click download i get a blank pdf page without any content and there is no errors in the screen, that's my code:

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;

Solution

  • 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;
    

    Please try the above code.