在React-Table中导出为PDF

时间:2019-06-25 10:36:33

标签: reactjs pdf react-table

react-table中有10行值。我需要转换为PDF格式吗?.ss是否可以转换?

1 个答案:

答案 0 :(得分:0)

使用jsPDFjspdf-autotable完成此操作。看看下面的代码:

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;

这应生成如下PDF文件:

enter image description here

希望这会有所帮助。