Search code examples
htmlreactjsrenderhtml-to-pdf

How to export a rendered table data to pdf file or any other format in reactjs


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.

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...


Solution

  • You can convert your dom to canvas and save the canvas as pdf,

    DOM to canvas,

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

    Canvas to 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");  
      });
    ;
    

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

    As suggested ,

    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');