I have a code snippet from bpampuch that converts JSON data into a pdf. It worked for me before, but when I linked my own local JSON file it stopped working. I'm not 100% sure of what fixes I need to do to get my own JSON data to be converted---I think it has something to do with the line data.jsonData.forEach
(see below), but I'm not sure what else. Any thoughts on this?
import $ from 'jquery';
import jsonData from "./test.json";
import pdfMake from 'pdfmake/build/pdfmake.min.js';
function _buildTableBody(data, cols) {
let body = [];
body.push(cols);
data.jsonData.forEach(function(row) { // reg obj doesn't have forEach
let dataRow = [];
cols.forEach(function(column) {
dataRow.push(row[column].toString());
})
body.push(dataRow);
});
return body;
}
function _table(data, cols) {
return {
table: {
headerRows: 1,
body: _buildTableBody(data, cols)
}
};
}
function _printFunc() {
var docDefinition = {
content: [
{ text: 'Dynamic Parts', style: 'header' },
_table(jsonData.d.results[0].Title, ['Title'])
]
};
pdfMake.createPdf(docDefinition).download(name + '.pdf');
console.log(docDefinition.content)
}
$("#pdf-trigger").on("click", _printFunc)
{
"d": {
"results": [
{
"FileSystemObjectType": 0,
"Id": 1,
"Title": "TitleHere",
"GoalRange": "3",
"Office": "Somewhere",
"Role": "FPSL",
"IsFilled": false,
"Employee": null,
"IsActive": true,
"Notes": null,
"ID": 1,
"Attachments": false
...etc
Your json file is clearly not in the same format as the demo. Try removing the .jsonData from the line you're having an issue with:
data.forEach(function(row) { // reg obj doesn't have forEach
And further down, you have this line
_table(jsonData.d.results[0].Title, ['Title'])
Leave it as an array
_table(jsonData.d.results, ['Title'])