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...
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");
});
;
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');