pdfmake 页码和局部变量从内部页脚函数访问

pdfmake page number and local variable access from inside footer function

在使用 PDFMake 生成报告时无法解决特定问题。我的项目使用 Angular 8 作为上下文,因此它位于模态组件内。下面是我用于测试的简单版本的代码。如何在“页脚:函数(currentPage,pageCount)”中定义 this.orderNum?

@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);
   });
 }      
}

控制台错误是:core.js:6014 错误错误:未捕获(承诺):类型错误:无法读取未定义的 属性 'orderNum' 类型错误:无法读取未定义的 属性 'orderNum'

A function 有它自己的 this 属性 所以当你在里面说 this.orderNum 你是页脚函数时,你指的是页脚函数 this 而不是你的 class this.

将页脚函数更改为箭头函数...

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)       
  }
}