Angular 8使用Pdfmake报null is not a function错误如何解决
Angular集成PDFmake生成PDF时控制台报null is not a function错误
问题表现
- 基于pdfmake库已经可以正常生成、下载符合需求的PDF文件
- 操作过程中控制台固定抛出异常:Unhandled promise rejection TypeError: null is not a function

错误堆栈信息
pdfmake.js:31998 Unhandled promise rejection TypeError: null is not a function at __webpack_modules__.9662.module.exports (pdfmake.js:29878:1) at new Promise (pdfmake.js:36500:1) at ZoneAwarePromise.then (zone.js:1034:1) at pdfmake.js:36565:1 at new Promise (pdfmake.js:36504:1) at ZoneAwarePromise.then (pdfmake.js:36564:1) at push../node_modules/@angular/platform-browser/fesm5/animations.js.AnimationRendererFactory._scheduleCountTask (animations.js:152:1) at animations.js:181:1 at push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:391:1) at push../node_modules/zone.js/dist/zone.js.Zone.run (zone.js:150:1) module.exports @ pdfmake.js:31998 dispatchEvent @ pdfmake.js:36416 (anonymous) @ pdfmake.js:36429 module.exports @ pdfmake.js:33533 (anonymous) @ pdfmake.js:36426 queue.<computed> @ pdfmake.js:34218 run @ pdfmake.js:34194 listener @ pdfmake.js:34205
最小复现代码
const documentDefinition = { content: [ { table: { widths: [100, '*', 200, '*'], body: [ ['width=100', 'star-sized', 'width=200', 'star-sized'], [ 'fixed-width cells have exactly the specified width', { text: 'nothing interesting here', italics: true, color: 'gray' }, { text: 'nothing interesting here', italics: true, color: 'gray' }, { text: 'nothing interesting here', italics: true, color: 'gray' }, ], ], }, }, ], pageSize: 'A4', pageOrientation: 'landscape', pageMargins: [20, 30, 20, 30], }; pdfMake.createPdf(documentDefinition).download(`myPDF.pdf`);
解决方法
报错根因是pdfmake内置的Promise polyfill实现和Angular自带的Zone.js微任务拦截逻辑冲突,异常属于非阻塞类型,不会影响PDF实际生成,有两种可行修复方案:
- 彻底修复方案:将pdfmake的调用逻辑放到Angular区域外执行,避开Zone.js的拦截
首先在对应组件/服务中引入NgZone,将PDF生成逻辑包裹在runOutsideAngular回调中即可:import { NgZone } from '@angular/core'; // 构造函数注入 constructor(private ngZone: NgZone) {} // 原PDF生成逻辑放到区域外执行 this.ngZone.runOutsideAngular(() => { pdfMake.createPdf(documentDefinition).download(`myPDF.pdf`); }); - 快速修复方案:手动捕获Promise抛出的异常,阻断控制台报错
pdfMake.createPdf(documentDefinition).download(`myPDF.pdf`).catch(() => { // 无需额外处理,仅用于吞掉不影响功能的内部异常 });
优先选择第一种方案,不会遗漏pdfmake真实的运行异常,同时可以避免Zone.js带来的不必要性能开销。
内容的提问来源于stack exchange,提问作者Gaurav Nagpure
相关产品推荐
相关产品推荐

