如何将渲染的表格数据导出为 pdf 文件或 reactjs 中的任何其他格式 [英] How to export a rendered table data to pdf file or any other format in reactjs

查看:103
本文介绍了如何将渲染的表格数据导出为 pdf 文件或 reactjs 中的任何其他格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Reactjs 将表格数据导出为 pdf 格式.我在 Reactjs 组件 中以 HTML 表格的形式显示 json 数据.

I am working on to export the table data to pdf format using Reactjs. I am showing the json data in the form of a HTML table inside Reactjs component.

我提供了一个名为 Export 的按钮,可以以任何格式导出数据.现在我只工作将数据导出为 PDF 格式.谁能帮我这个.是否有任何要导入的包或任何特定的代码来将数据导出为 PDF 文件.任何事情都可能有用.提前致谢...

I have given a button named as Export to export the data in any format. For now I am working only to export the data to PDF Format. Can anyone help me with this. Is there any Package to import or any specific code to do to export the data to PDF file. Anything can be useful. Thanks in Advance...

推荐答案

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

You can convert your dom to canvas and save the canvas as 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(仅适用于 table 或 jsonarray),

We can also use jspdf-autotable to generate pdf (works only with table or 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');

这篇关于如何将渲染的表格数据导出为 pdf 文件或 reactjs 中的任何其他格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆