首页 > 解决方案 > React 使用多页和 CSS 将 Div 和表格组件转换为 PDF

问题描述

正如标题所说,我需要能够将表​​格转换为带有跨多个页面的标题的pdf(就像我在打印中所做的那样)。

我找到了几个关于如何将反应组件转换为 pdf 文件的资源。但是没有一个涵盖需要跨多个页面分布的组件/表格和导入您拥有的 CSS 的组合。我使用 react-to-print 库将它用于打印,但我似乎找不到任何 pdf 文件。react-pdf 库表单让你不能使用 html 元素。

完整代码 - https://codesandbox.io/s/react-table-to-pdf-m15em?file=/src/App.js

pdf功能...

  exportPdf = () => {
    const state = this.props.listOfStates.find(state => state.id === this.state.selectedStateId);
    const school = this.props.listOfSchools.find(school => school.id === this.state.selectedSchoolId);
    Promise.resolve(this.setState({ ...this.state, selectedStateNamePdf: state.stateName, selectedSchoolNamePdf: school.schoolName }))
    .then(() => {
      const input = document.getElementById('pdf-element');
      html2canvas(input)
        .then((canvas) => {
          const imgData = canvas.toDataURL('image/png');
          const pdf = new jsPDF();
          pdf.addImage(imgData, 'JPEG', 0, 0);
          pdf.addPage();
          pdf.addImage(imgData, 'JPEG', 0, 0);
          pdf.save("download.pdf");
        })
      ;
    })
  }

pdf 组件...

class PdfReportContent extends Component {
  render(){
    const { selectedReportDetails, stateName, schoolName, startDate, endDate } = this.props;
    return (
      <div id="pdf-element" style={{maxWidth: "210mm", width: "100%", height: "100%", position: "relative", margin: "0"}}>
        <div style={{display: "block"}}>
          <div style={{width: "100%", display: "flex", justifyContent: "space-between", padding: "1vh 2.5vh 0"}}>
            <div>
              <h2 className="header-title-one">SCHOOL</h2>
              <h2 className="header-title-two">REPORT</h2>
            </div>
            <div style={{display: "flex"}}>
              <div style={{display: "inline-block", textAlign: "right"}}>
                <h5>{stateName}</h5>
                <h5>{schoolName}</h5>
                <p>{startDate} - {endDate}</p>
              </div>
            </div>
          </div>
          <hr />
          <h3 style={{margin: "10px 0 0 2.5vh"}}>REPORT RESULTS</h3>
        </div>
        <div id="print-list-body">
          {selectedReportDetails.map((classDetails, indexOne) => 
            <div key={indexOne} style={{maxWidth: "200mm", width: "100%", margin: "40px auto 0 auto", boxSizing: "border-box"}}>
              <h2 style={{marginBottom: "10px", color: "#01A3E0"}}>{classDetails.className}</h2>
              {classDetails.classes.map((dateTable, indexTwo, classes) =>
                <table key={indexTwo} className="tbl-reports-list">
                  <tbody>
                    <tr>
                      <th>{dateTable.date}</th>
                      <th>Students</th>
                      <th>Grades</th>
                      <th>Assignment</th>
                      <th>Attendance</th>
                    </tr>
                    {dateTable.instructors.map((instructor, indexThree, instructorRows) =>
                      instructor.students.map((row, indexFour, studentRows) =>
                        indexTwo === classes.length-1 ? 
                        <tr key={indexFour} style={indexFour === studentRows.length-1 ? { borderBottom: "2px solid #01A3E0"} : {}}>
                          {indexFour === 0 ?
                          <td>
                              <h5>{instructor.instructorName}</h5>
                          </td> : <td />
                          }
                          <td style={{backgroundColor: "#ffffff"}}>{row.name}</td>
                          <td style={row.isHonorStudent ? {backgroundColor: "#ffffff"} : {backgroundColor: "#ffedbc"}}>{row.grade}</td>
                          <td style={{backgroundColor: "#ffffff"}}>{row.assignment}</td>
                          <td style={{backgroundColor: "#ffffff"}}>{row.attendance}</td>
                        </tr> : 
                        <tr key={indexFour} style={indexFour === studentRows.length-1 && indexThree !== instructorRows.length-1 ? { borderBottom: "2px solid #01A3E0"} : {}}>
                          {indexFour === 0 ?
                          <td>
                              <h5>{instructor.instructorName}</h5>
                          </td> : <td />
                          }
                          <td style={{backgroundColor: "#ffffff"}}>{row.name}</td>
                          <td style={row.isHonorStudent ? {backgroundColor: "#ffffff"} : {backgroundColor: "#ffedbc"}}>{row.grade}</td>
                          <td style={{backgroundColor: "#ffffff"}}>{row.assignment}</td>
                          <td style={{backgroundColor: "#ffffff"}}>{row.attendance}</td>
                        </tr>
                      )
                    )}
                  </tbody>
                </table>
              )}
            </div>
          )}
        </div>
      </div>
    );
  }
}

重现问题的步骤:

如果有人可以在代码框链接中分叉该项目并向我展示我所缺少的东西,那将不胜感激。

标签: reactjsjspdfhtml2canvas

解决方案


jsPdf 有一个渲染html的方法,您可以使用它而不是使用图像手动创建文档,这是您的代码所需的更改:

   ...
   const input = document.getElementById("pdf-element");
   const pdf = new jsPDF({ unit: "px", format: "letter", userUnit: "px" });
   pdf.html(input, { html2canvas: { scale: 0.57 } }).then(() => {
     pdf.save("test.pdf");
   });
   ...

注意到我在 jsPdf 对象创建中调整了一些配置,并且在调用时.hmtl(),由于某种原因 pdf 被放大,这就是为什么我为 html2canvas 添加了缩放选项(这也可能取决于平台/浏览器)

这是带有更改的分支https://codesandbox.io/s/react-table-to-pdf-forked-2iri9


推荐阅读