如何在React.js中将渲染的表格数据导出为pdf文件或任何其他格式

时间:2019-05-20 06:23:53

标签: html reactjs render html-to-pdf

我正在使用<img src="https://www.myrfs.nsw.gov.au/portals/0/beyondblue.png" style="float: right; padding-left: 5px"> <div class="overlap"> <h3>beyondblue</h3> <p>beyondblue provides information and support to help everyone in Australia achieve their best possible mental health, whatever their age and wherever they live.</p> <table style="width: 0px;"> <colgroup><col><col></colgroup> <tbody> <tr> <td><b>Website</b></td> <td><a href="http://www.beyondblue.org.au ">www.beyondblue.org.au</a></td> </tr> <tr> <td><b>Phone numbers</b></td> <td><p><b>Support</b>: <a href="tel:1300224636">1300 22 46 36</a> <br><b>Lifeline</b>: <a href="tel:131114">13 11 14</a> <br><b>Suicide Callback Service</b>: <a href="tel:1300659467">1300 659 467</a></p> <p>If you are in an emergency or at immediate risk of harm to yourself or others, please contact emergency services on <a href="tel:000">Triple Zero (000)</a>.</p></td> </tr> <tr> <td><b>Other services</b></td> <td> <ul> <li><a href="https://www.beyondblue.org.au/get-support/get-immediate-support" target="_blank">Online chat</a></li> <li><a href="www.facebook.com/beyondblue" target="_blank">Facebook</a></li> </ul> </td> </tr> </tbody> </table> </div>将表格数据导出为pdf格式。我正在Reactjs内以HTML表格的形式显示json data

我给了一个名为Reactjs component的按钮来导出任何格式的数据。目前,我仅将数据导出为PDF格式。谁能帮我这个。是否有要导入的数据包或要执行的特定代码以将数据导出到PDF文件。任何东西都可能有用。在此先感谢...

2 个答案:

答案 0 :(得分:1)

您可以将dom转换为画布,并将画布另存为pdf,

DOM到画布,

const input = document.getElementById('mytable');
html2canvas(input)
  .then((canvas) => {
    const imgData = canvas.toDataURL('image/png');
  })
;

画布为pdf

html2canvas(input)
  .then((canvas) => {
    const imgData = canvas.toDataURL('image/png');
    const pdf = new jsPDF();
    pdf.addImage(imgData, 'PNG', 0, 0);
    pdf.save("download.pdf");  
  });
;

引用https://medium.com/@shivekkhurana/how-to-create-pdfs-from-react-components-client-side-solution-7f506d9dfa6d

按照建议,

我们还可以使用jspdf-autotable生成pdf(仅适用于表或jsonarray)

var doc = new jsPDF();
    // You can use html:
    doc.autoTable({html: '#my-table'});

    // Or JavaScript:
    doc.autoTable({
        head: [['Name', 'Email', 'Country']],
        body: [
            ['David', 'david@example.com', 'Sweden'],
            ['Castille', 'castille@example.com', 'Norway'],
            // ...
        ]
    });

    doc.save('table.pdf');

答案 1 :(得分:0)

下载.zip文件并检查演示文件。然后使用它。链接。

tableExport.jquery.plugin-master