Reputation: 301
I'm trying to convert HTML5 table using jspdf (Similar to Export HTML table to pdf using jspdf) . However, the elements in my table are generated dynamically
function createTable(){
var reportDiv = document.getElementById('customers');
var table = document.createElement('table');
table.id = 'tab_customers';
table.className = 'table table-striped';
var thead = document.createElement('thead');
var tableHeader = document.createElement('th');
tableHeader.innerHTML = "Name";
thead.appendChild(tableHeader);
var tableHeader = document.createElement('th');
tableHeader.innerHTML = "Status";
thead.appendChild(tableHeader);
table.appendChild(thead);
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "json";
cell2.innerHTML = "fail";
reportDiv.appendChild(table);
return reportDiv;
}
PDF gets created, but the problem is it fails to show the table header. However if I create the table manually ( copy - paste) from the above dom, table header is rendered. Any help on this would be highly appreciated. Thanks
Upvotes: 0
Views: 1168
Reputation: 894
th element has to be wrapped around tr element. Then tr is appended to thead, finally to table element.
function createTable(){
var reportDiv = document.getElementById('customers1');
var table = document.createElement('table');
table.id = 'tab_customers1';
table.className = 'table table-striped';
var thead = document.createElement('thead');
var tr = document.createElement('tr');
var tableHeader = document.createElement('th');
tableHeader.innerHTML = "Name";
tr.appendChild(tableHeader);
var tableHeader = document.createElement('th');
tableHeader.innerHTML = "Status";
tr.appendChild(tableHeader);
thead.appendChild(tr);
table.appendChild(thead);
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "json";
cell2.innerHTML = "fail";
reportDiv.appendChild(table);
return reportDiv;
}
Upvotes: 1