-1

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

ravibagul91
  • 20,072
  • 5
  • 36
  • 59
MOHIT SHARMA
  • 103
  • 4
  • 14

2 Answers2

3

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');
Srinivasan Sekar
  • 2,049
  • 13
  • 22
  • Yes this is a good solution but does not works in my case. It shows only the data that is shown in that particular page. If I have a table that has multiple pages then how to show those multiple data in multiple pages on the pdf? can you help me using the above solution ? – MOHIT SHARMA May 20 '19 at 07:49
  • You cant render a full table in pdf if it is paginated , I would suggest you to dynamically create a table and add all the rows and use it to create the pdf. .You can see in the same article to lean how to generate multiple pages pdf. – Srinivasan Sekar May 20 '19 at 08:23
  • @SrinivasanSekar yeah we can create a table dynamically as suggested in the article that you shared, but I found another easy way to solve it by using "jspdf-autotable" package. In this we can pass the JSON Object that we are displaying in the HTML table. So by passing the whole JSON Object will help us to show the whole data in the PDF rather than showing only the active table page data. – MOHIT SHARMA May 20 '19 at 11:21
  • pdf.addImage(imgData, 'PNG', 0, 0); what does both 0s stands for? – Lex V Nov 26 '19 at 12:19
0

Download the .zip file and check the demo file. then use it. link below.

tableExport.jquery.plugin-master

Amit Bera
  • 41
  • 4