CSV Export
A basic way to convert your table to CSV using plain JavaScript could look like this:
function download_csv(csv, filename) {
var csvFile;
var downloadLink;
// CSV FILE
csvFile = new Blob([csv], {type: "text/csv"});
// Download link
downloadLink = document.createElement("a");
// File name
downloadLink.download = filename;
// We have to create a link to the file
downloadLink.href = window.URL.createObjectURL(csvFile);
// Make sure that the link is not displayed
downloadLink.style.display = "none";
// Add the link to your DOM
document.body.appendChild(downloadLink);
// Lanzamos
downloadLink.click();
}
function export_table_to_csv(html, filename) {
var csv = [];
var rows = document.querySelectorAll("table tr");
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll("td, th");
for (var j = 0; j < cols.length; j++)
row.push(cols[j].innerText);
csv.push(row.join(","));
}
download_csv(csv.join("\n"), filename);
}
To use this function, you would do something like:
var html = document.querySelector("table").outerHTML;
export_table_to_csv(html, "table.csv");
PDF Export
Exporting an HTML table to a PDF is a little bit more complex. Here is a basic example using the jsPDF library:
Firstly, include the jsPDF library in your HTML:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js"></script>
Then, you can use jsPDF in your JavaScript like this:
var doc = new jsPDF();
doc.text('Hello world!', 10, 10);
doc.save('a4.pdf');
In the above example, it creates a new PDF file with the text “Hello world!” at the coordinates (10, 10). The save
function is used to download the file.
To convert an HTML table to a PDF file, you might want to consider a library like html2canvas or rasterizeHTML to render your HTML as an image, and then add that image to your PDF. Alternatively, you could manually write the table data to the PDF, but this would likely be more complex and time-consuming.
Note: These methods require the user to trigger the download action due to web browser security policies on automated downloads.
However, if you’re using a library such as DataTables, it comes with the Buttons extension that makes CSV, Excel, PDF export much easier to implement. If possible, I would recommend considering the use of such libraries.