Export to PDF in React-Table

16,795

Use jsPDF and jspdf-autotable to accomplish this. Check out the code below:

import React from 'react';
import jsPDF from "jspdf";
import "jspdf-autotable";
import './App.css';

class App extends React.Component {

  constructor() {
    super();
    this.state = {
      people: [
        { name: "Keanu Reeves", profession: "Actor" },
        { name: "Lionel Messi", profession: "Football Player" },
        { name: "Cristiano Ronaldo", profession: "Football Player" },
        { name: "Jack Nicklaus", profession: "Golf Player" },
      ]
    }
  }

  exportPDF = () => {
    const unit = "pt";
    const size = "A4"; // Use A1, A2, A3 or A4
    const orientation = "portrait"; // portrait or landscape

    const marginLeft = 40;
    const doc = new jsPDF(orientation, unit, size);

    doc.setFontSize(15);

    const title = "My Awesome Report";
    const headers = [["NAME", "PROFESSION"]];

    const data = this.state.people.map(elt=> [elt.name, elt.profession]);

    let content = {
      startY: 50,
      head: headers,
      body: data
    };

    doc.text(title, marginLeft, 40);
    doc.autoTable(content);
    doc.save("report.pdf")
  }

  render() {
    return (
      <div>
        <button onClick={() => this.exportPDF()}>Generate Report</button>
      </div>
    );
  }
}

export default App;

This should generate a PDF like this:

enter image description here

Hope this helps.

Share:
16,795
reckinam deva
Author by

reckinam deva

Updated on June 16, 2022

Comments

  • reckinam deva
    reckinam deva about 2 years

    I have 10 row of values in react-table .I need to convert to PDF format?.ss it possible to convert?

  • Manu Panduu
    Manu Panduu over 3 years
    Thanks very very much
  • lomse
    lomse over 3 years
    Happy to hear ;)
  • piyush172
    piyush172 almost 3 years
    getting this error "Error: Requiring module "node_modules\jspdf\dist\jspdf.es.min.js", which threw an exception: TypeError: undefined is not an object (evaluating 'r.atob.bind')" Pls help @lomse
  • lomse
    lomse almost 3 years
    Have you installed the jspdf module? If not simply install it with the command npm install jspdf
  • Ali Aref
    Ali Aref about 2 years
    need to apply filters on print too, currently it's printing all the data. (my react-table has filtering and sorting options any way to include them?)
  • MogerCS
    MogerCS about 2 years
    @lomse, this works fine for me, but is there any other possibility to export pdf table if each row last column has image.