Search code examples
angularpdfmake

pdfmake page number and local variable access from inside footer function


Having a problem figuring out a specific issue when generating a report using PDFMake. My project uses Angular 8 for context so this is inside a modal component. Code Below of a simple version I'm using for testing. How do I define this.orderNum while inside "footer: function (currentPage, pageCount)"?

@Component({
 selector: 'app-utilities-print-OrderPrintModal',
 templateUrl: './printtemplate.html'
})

export class OrderPrintModal implements OnInit {
  @Input() passedOrderNum: string;
  public orderNum: string;
  public pdf: any;

 ngOnInit() {   
   this.orderNum= this.passedOrderNum;
   this.print();
 }

 print() {
    var dd = {
      pageOrientation: "portrait",
      pageMargins: [20, 10, 20, 40],
      pageSize: "LETTER",
    
    footer: function (currentPage, pageCount) {
    var t = {
      layout: "noBorders",
      fontSize: 8,
      margin: [25, 0, 25, 0],
      table: {
        widths: ["*", "*"], 
        body: [
          [
            { text: "Page  " + currentPage.toString() + " of " + pageCount },
            { text: "orderNum  " + this.orderNum }
          ]
        ]
      }
    };

    return t;
  }
  this.createPDF(dd)       
 }

  createPDF(dd: any) {
     this.pdf = pdfMake.createPdf(dd);
     this.pdf.getDataUrl((dataUrl) => {
     const targetElement = document.querySelector('#iframeContainer');
     const iframe = document.createElement('iframe');
     iframe.src = dataUrl;
     iframe.setAttribute("style", "width:100%; height:100%;");
     targetElement.appendChild(iframe);
   });
 }      
}

Console error is : core.js:6014 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'orderNum' of undefined TypeError: Cannot read property 'orderNum' of undefined


Solution

  • A function has it's own this property so when you say this.orderNum inside you're footer function, you're referring to the footer functions this and not your class this.

    Change your footer function to an arrow function...

    print() {
      var dd = {
        pageOrientation: "portrait",
        pageMargins: [20, 10, 20, 40],
        pageSize: "LETTER",
        
        footer: (currentPage, pageCount) => {
          var t = {
            layout: "noBorders",
            fontSize: 8,
            margin: [25, 0, 25, 0],
            table: {
              widths: ["*", "*"], 
              body: [
                [
                  { text: "Page  " + currentPage.toString() + " of " + pageCount },
                  { text: "orderNum  " + this.orderNum }
                ]
              ]
            }
          };
    
          return t;
        }
        this.createPDF(dd)       
      }
    }