Search code examples
javascripthtmlangulartypescriptpdfmake

How to use pdfMake with dynamic data


I'm new to angular, I'm trying to use pdfMake, I can use it with static data but not able to achieve this with dynamic data, I would appreciate if you can help me achieve this it would be great, as I've searched all over the internet and couldn't quite get how I can achieve this. Thanks in advance.

employees.component.ts

getAllEmployees(){
    this.restService.GetAllEmployees().subscribe((res: any) => {
    this.employees = res.data.employees
    for(var i = 0; i< this.employees.length; i++) {
    this.array = this.employees[i]
    console.log(this.array)
    }
  })
}

generatePdf(){
  const documentDefinition = this.getDocumentDefinition();
  pdfMake.createPdf(documentDefinition).open();
}

getDocumentDefinition() {
  return {
    content: [
        {
        table: {
          headerRows: 4,
          widths: [ '*', 'auto', 100, '*' ],
          body: [
            [ 'Name', 'Second', 'Third', 'The last one' ],
            [ this.array.firstName_FL, 'Value 2', 'Value 3', 'Value 4' ],
          ]
        }
      }
    ]    
  };
}
ExportAsPDF(){
  this.generatePdf();
}

I've tried using this.array.firstName_FL however it comes up with last index only


Solution

  • Try something like this. Please note that this wasn't tested.

    getDocumentDefinition() {
        return {
            content: [
                {
                table: {
                headerRows: 4,
                widths: [ '*', 'auto', 100, '*' ],
                body: [[ 'Name', 'Second', 'Third', 'The last one' ]]
                    .concat(this.employees.map((el, i) => [el.firstName_FL, el['secondPropHere'], el['thirdPropHere'], el['fourthPropHere']]))
                }
            }
            ]    
        };
    }
    

    Sorry for the formatting, let me know if that works. The whole idea behind it is that, in the end, body needs to be an array of arrays:

    • first array would be the header (as in thead/tr/th)
    • second array would be the first data row (as in tbody/tr/td)
    • third array -> the second data row, etc

    Concat will just return a new array containing the header array and followed by arrays of each employee data (the map high order function).

    el['secondPropHere'] - just remove square brackets and use the dot notation to get your desired property for the second prop, like `el.secondProp`.