Skip to content

Instantly share code, notes, and snippets.

@brenopolanski
Last active August 5, 2022 05:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brenopolanski/a316515d1b48f2d5ed6c5f71e638d510 to your computer and use it in GitHub Desktop.
Save brenopolanski/a316515d1b48f2d5ed6c5f71e638d510 to your computer and use it in GitHub Desktop.
Convert HTML to a PDF in React.JS

The idea is to convert : HTML -> Canvas -> PNG (or JPEG) -> PDF

To achieve the above, you'll need :

  1. html2canvas
  2. jsPDF
import React, { Component } from 'react';

export default class Export 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 className="mb5">
        <button onClick={this.printDocument}>Print</button>
      </div>
      <div id="divToPrint" className="mt4" {...css({
        backgroundColor: '#f5f5f5',
        width: '210mm',
        minHeight: '297mm',
        marginLeft: 'auto',
        marginRight: 'auto'
      })}>
        <div>Note: Here the dimensions of div are same as A4</div> 
        <div>You Can add any component here</div>
      </div>
    </div>);
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment