I want to export JSON data to pdf with out using any third party plugin.I am having data in Json and need to display data in pdf table structure using JQuery. Please let me know if its possible.
Here is sample JSON
jsonResult.Products[
{PRODUCT_ID: 123, PRODUCT_NUMBER: "00022", PRODUCT_NAME: "HONDA", PRODUCT_TYPE: "VEHICLE "},
{PRODUCT_ID: 783, PRODUCT_NUMBER: "08412394", PRODUCT_NAME: "HONDA", PRODUCT_TYPE: "MOTOR "}.....]
Code snippet using jS PDF-autotable
<script src="~/Scripts/JsPDF-Autotable.js"></script>
$("#btnExportPDF").click(function () {
let table = document.createElement('table');
table.setAttribute("id", "pdfTable");
let thead = document.createElement('thead');
let tbody = document.createElement('tbody');
let thead_tr = document.createElement('tr');
let sample = dataResult.Cases[0];
let columns = [];
let columnData = [];
for (let column in sample) columns.push(column);
for (let i = 0; i < columns.length; i++) {
let th = document.createElement('th');
th.innerText = columns[i];
thead_tr.appendChild(th);
}
thead.appendChild(thead_tr);
for (let i = 0; i < dataResult.Cases.length; i++) {
let tr = document.createElement('tr');
let product = dataResult.Cases[i];
for (let column = 0; column < columns.length; column++) {
let td = document.createElement('td');
td.innerText = product[columns[column]];
columnData.push(product[columns[column]]);
tr.appendChild(td);
}
tbody.appendChild(tr);
}
table.appendChild(thead);
table.appendChild(tbody);
var doc = new jsPDF('p', 'pt');
doc.autoTable(columns, columnData)
doc.save("table.pdf");
});
I tried to export to pdf using jspdf autotable and I am getting below error
JsPDF-Autotable.js:1538 Use of deprecated autoTable initiation
Yes it's definitely possible.
The process is very simple:
Prepare your JSON data
Create a table element filled with your data
Export table with JSPDF
Creating the table
let table = document.createElement('table');
let thead = document.createElement('thead');
let tbody = document.createElement('tbody ');
let thead_tr = document.createElement('tr');
let sample = jsonResult.Products[0];
let columns = [];
for (let column in sample) columns.push(column);
for (let i = 0; i<columns.length;i++){
let th = document.createElement('th');
th.innerText = columns[i];
thead_tr.appendChild(th);
}
thead.appendChild(thead_tr);
for (let i = 0; i<jsonResult.Products.length;i++){
let tr = document.createElement('tr');
let product = jsonResult.Products[i];
for (let column = 0; column < columns.length; column++){
let td = document.createElement('td');
td.innerText = product[columns[column]];
tr.appendChild(td);
}
tbody.appendChild(tr);
}
table.appendChild(thead);
table.appendChild(tbody);
document.body.appendChild(table); // Now this is your table which you are going to export
Follow this SO answer/guide to export the HTML table with JSPDF
Related
function createTable(data_array){
const billing_table_body = document.querySelector('#billing_progile_Table > tbody')
//we loop through object array and have access to each individual JSON
for(var i = 0; i<objarray.length;i++){
console.log("data : ",objarray[i].profileName)
//create row
const tr = document.createElement('tr'); //creating the row
console.log('creating new row');
//append individual tds
const td = document.createElement('td')
td.textContent = objarray[i].profileName//appends data from the json cell
td.className = 'text_td';
tr.appendChild(td);
const td_two = document.createElement('td')
td_two.textContent = objarray[i].cardemail
td.className = 'text_td';
tr.appendChild(td_two);
const td_three = document.createElement('td')
td_two.textContent = objarray[i].cardownername
td.className = 'text_td';
tr.appendChild(td_three);
const td_four = document.createElement('td')
td_two.textContent = objarray[i].cardnumber
td.className = 'text_td';
tr.appendChild(td_four);
//append whole row to tr
billing_table_body.appendChild(tr);
}
}
im trying to append the cells into the table with their data but the table won't allow me to do it and I need to write it like this because im trying to access specific objects of the json array. any help im new to JAVASCRIPT AND JSON
Please stop adding row and cells with createElement() method...!
const billing_table_body = document.querySelector('#billing_progile_Table > tbody')
function createRows(data_array)
{
data_array.forEach(el =>
{
let newRow = billing_table_body.insertRow()
newRow.insertCell().textContent = el.profileName
newRow.insertCell().textContent = el.cardemail
newRow.insertCell().textContent = el.cardownername
newRow.insertCell().textContent = el.cardnumber
newRow.querySelectorAll('td').forEach(td=>td.className='text_td')
})
}
I tried to create table but I can't create td in every tr, td is creating only in first td what is in table, how I can solve the problem?
// Creating div
var main = document.createElement("div")
main.innerHTML = ""
document.body.appendChild(main)
main.setAttribute("id", "main")
//Creating Icons
var puzzleico = document.createElement("div")
puzzleico.innerHTML = ""
document.getElementById("main").appendChild(puzzleico)
puzzleico.setAttribute("id", "puzzleico")
var puzzleico = document.getElementById("puzzleico").onclick = function() {createtable()};
//Creating tr and td
function createtable() {
//Creating Table
var table = document.createElement("table")
table.innerHTML = ""
document.body.appendChild(table)
table.setAttribute("id", "table")
for (var i = 0; i < 50; i++) {
var tr = document.createElement("tr")
tr.innerHTML = ""
document.getElementById("table").appendChild(tr)
tr.setAttribute("id", "tr")
var td = document.createElement("td")
td.innerHTML = ""
document.getElementById("tr").appendChild(td)
}
}
Element id's within a document need to be unique. The issue here is that your document.getElementById("tr") will always return the first element it finds with that id and so, all of your <td> elements will be appended to the first <tr>.
In order to fix it you can remove the tr.setAttribute("id", "tr") line and use the already existing tr variable to append the td child to.
function createtable() {
//Creating Table
var table = document.createElement("table")
table.innerHTML = ""
document.body.appendChild(table)
table.setAttribute("id", "table")
for (var i = 0; i < 50; i++) {
var tr = document.createElement("tr")
tr.innerHTML = ""
document.getElementById("table").appendChild(tr);
var td = document.createElement("td");
td.innerHTML = "test"
tr.appendChild(td)
}
}
createtable();
The above code will work, but using the already declared variables instead of finding them again can also be applied to the table case. Also, table.innerHTML = "" doesn't add any value because the innerHTML is already empty when you create a new element.
function createtable() {
//Creating Table
var table = document.createElement("table");
document.body.appendChild(table);
for (var i = 0; i < 50; i++) {
var tr = document.createElement("tr");
table.appendChild(tr);
var td = document.createElement("td");
td.innerHTML = "test";
tr.appendChild(td);
}
}
You can use this to create the table:
function createTable(){
//Creating And Appending Child
let table = document.createElement('table');
document.body.appendChild(table);
for(let i = 0; i < 50; i++){
let tr = document.createElement('tr');
let td = document.createElement('td');
td.innerHTML = i;
tr.appendChild(td);
table.appendChild(tr);
}
}
Here is the link to my codepen:
https://codepen.io/prabodhpanda/pen/gOPLqYe?editors=1010
id attribute of each element in DOM should be unique. You set same id for each tr element you create. document.getElementById element always returns the first element match by the id. This is the reason of the issue. Your last code snippet should be:
function createtable() {
//Creating Table
var table = document.createElement("table")
table.innerHTML = ""
document.body.appendChild(table)
table.setAttribute("id", "table")
for (var i = 0; i < 50; i++) {
var tr = document.createElement("tr")
tr.innerHTML = ""
document.getElementById("table").appendChild(tr)
tr.setAttribute("id", "tr" + i) // Check this
var td = document.createElement("td")
td.innerHTML = ""
document.getElementById("tr" + i).appendChild(td) // Check this
}
}
tr.appendChild(td) should also work if you don't need ID attribute.
I edited your answer and got what I want.
//Creating tr and td
function createtable() {
//Creating Table
var table = document.createElement("table")
table.innerHTML = ""
document.body.appendChild(table)
table.setAttribute("id", "table")
for (var i = 0; i < 50; i++) {
var tr = document.createElement("tr")
tr.innerHTML = ""
document.getElementById("table").appendChild(tr)
tr.setAttribute("id", "tr")
for (var v = 0; v < 50; v++) {
var td = document.createElement("td")
td.innerHTML = ""
tr.appendChild(td)
}
}
}
I'm trying to add <th> tag to the table, but I am not able to add. I want to add Id, Name and Prof as a table header.
var obj=[{id:"01",name:"Bob",prof:"Soft Engg"},{id:"02",name:"George",prof:"Admin"},{id:"03",name:"Paul",prof:"Front End"}];
var table = document.createElement("table");
table.setAttribute("id","myTable");
document.body.appendChild(table);
for(i=0;i<obj.length;i++) {
var row = document.createElement("tr")
table.appendChild(row);
var head = document.createElement("th");
row.appendChild(head);
for (key in obj[i]) {
var cell = document.createElement("td");
row.appendChild(cell);
cell.innerHTML = obj[i][key];
}
}
You can do something like this
var obj = [{
id: "01",
name: "Bob",
prof: "Soft Engg"
}, {
id: "02",
name: "George",
prof: "Admin"
}, {
id: "03",
name: "Paul",
prof: "Front End"
}];
var table = document.createElement("table");
table.setAttribute("id", "myTable");
document.body.appendChild(table);
// check array length
if (obj.length) {
// create row for table head
var row = document.createElement("tr")
// append it to table
table.appendChild(row);
// get kesys from first object and iterate
Object.keys(obj[0]).forEach(function(v) {
// create th
var cell = document.createElement("th");
// append to tr
row.appendChild(cell);
// update th content as key value
cell.innerHTML = v;
});
}
for (var i = 0; i < obj.length; i++) {
var row = document.createElement("tr")
table.appendChild(row);
for (key in obj[i]) {
var cell = document.createElement("td");
row.appendChild(cell);
cell.innerHTML = obj[i][key];
}
}
I couldn't stop thinking about this post and use it as JS practice, here I go:
var obj=[
{id:"01",name:"Bob",prof:"Soft Engg"},
{id:"02",name:"George",prof:"Admin"},
{id:"03",name:"Paul",prof:"Front End"}
];
var headers=['id','name','prof'];
var table = document.createElement("table");
table.setAttribute("id","myTable");
document.body.appendChild(table);
var tableHeader = document.createElement("thead");
table.appendChild(tableHeader);
tableHeaderRow = document.createElement("tr");
table.appendChild(tableHeaderRow);
for(i=0;i<headers.length;i++){
var tableHeader = document.createElement("th");
tableHeaderRow.appendChild(tableHeader);
tableHeader.innerHTML = headers[i]
}
var tableBody = document.createElement("tbody");
table.appendChild(tableBody);
for(i=0;i<headers.length;i++){
var tbodyrows=document.createElement("tr");
for (key in obj[i]) {
tableBody.appendChild(tbodyrows);
var cell = document.createElement("td");
tbodyrows.appendChild(cell);
cell.innerHTML = obj[i][key];
}
}
Im making a blackjack game for an assignment and have arrays for leaderboard and cards.
I want to print the leader board like this. CARDS(in individual cells)| TOTAL.
help would be appreciated, thanks
function makeTable(leaderBoard) {
var table = document.createElement('table');
for (var i = 0; i < leaderBoard.length; i++) {
var row = document.createElement('tr');
for (var j = 0; j < leaderBoard[i].length; j++) {
var cell = document.createElement('td');
cell.textContent = leaderBoard[i][j];
row.appendChild(cell);
}
table.appendChild(row);
}
document.getElementById('leaderBoard').innerHTML = table;
}
Maybe the example input isn't in the correct format, but reusing a predefined table and html table functions such as insertRow and insertCell (not necessarily better, but they can be easier on the eye than createElement and append) :
<div id="leaderBoard"><table id=leaderTable></table></div>
function updateleaderboard(leaderBoard) {
var table = document.getElementById('leaderTable');
while(table.rows.length > 0) table.deleteRow(0); //remove prev values, if any
for (var i = 0; i < leaderBoard.length; i++) { //If the function is always used on a winner (no ties), the loop isn't really needed
var row =table.insertRow();
var arrCards = leaderBoard[i++];
var total = row.insertCell();
total.className = 'res';
total.textContent = leaderBoard[i];
arrCards.forEach(function(c,ind){
row.insertCell(ind).textContent = c;
});
}
}
var cards = [['Q','4','5'],19];
updateleaderboard(cards);
Fiddle
function makeTable(leaderBoard) {
var table = document.createElement('table');
var row = document.createElement('tr');
for (var i = 0; i < leaderBoard[0].length; i++) {
var cell = document.createElement('td');
cell.textContent = leaderBoard[0][i];
row.appendChild(cell);
}
var cell = document.createElement('td');
cell.textContent = "Total: " + leaderBoard[1];
row.appendChild(cell);
table.appendChild(row);
document.getElementById('leaderBoard').appendChild(table);
}
var userCards = ["Card 1", "Card 2", "Card 3"];
var userTotal = 10;
makeTable([userCards, userTotal]);
http://jsfiddle.net/25kg3nnq/
I have made an html table with java script but not understanding how to add the caption and the thead.
var arr =[
["Period Ends", "Payroll Due", "Payday"],
["06/13/15", "06/19/15", "06/26/15"],
];
var body, tab, th, tr, td, tn, row, col;
body = document.getElementsByTagName('body')[0];
tab = document.createElement('table');
for (row=0; row < arr.length; row++){
tr = document.createElement('tr');
for (col=0; col < arr[row].length; col++){
td = document.createElement('td');
tn = document.createTextNode(arr[row][col]);
td.appendChild(tn);
tr.appendChild(td);
}
tab.appendChild(tr);
}
body.appendChild(tab);
This is the approach that I would use
var arr =[
["Period Ends", "Payroll Due", "Payday"],
["06/13/15", "06/19/15", "06/26/15"],
];
var body = document.getElementsByTagName('body')[0];
var tab = document.createElement('table');
var cap = tab.createCaption();
var tr, td, col;
// set caption
cap.innerHTML = 'My Table Caption';
// start from first row (skip row headings)
for (var row=1; row < arr.length; row++){
tr = tab.insertRow(row-1);
for (col=0; col < arr[row].length; col++){
td = tr.insertCell(col);
td.innerHTML = arr[row][col];
}
}
// add row headings
var header = tab.createTHead()
var headerRow = header.insertRow(0);
for (col=0; col < arr[0].length; col++){
td = headerRow.insertCell(col);
td.innerHTML = arr[0][col];
}
body.appendChild(tab);
This makes use of the HTML-spec methods for creating table elements
createCaption
insertRow
createTHead
insertCell
innerHTML
The only quirk I found was that I had to add the tHead after the body rows
Here's a jsfiddle