Home:ALL Converter>Converting JSON data with pdfMake

Converting JSON data with pdfMake

Ask Time:2019-04-05T22:34:33         Author:Bodrov

Json Formatter

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?

JS snippet:

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)

JSON snippet:

{
  "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

Author:Bodrov,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/55537760/converting-json-data-with-pdfmake
yy