Angular2:如何使用pdfmake库
发布时间:2020-12-17 07:35:22 所属栏目:安全 来源:网络整理
导读:尝试在我的Angular 2(version = 4.2.x)项目中使用客户端pdf库 pdfmake. 在.angular-cli.json文件中,我声明了这样的js: "scripts": [ "../node_modules/pdfmake/build/pdfmake.js","../node_modules/pdfmake/build/vfs_fonts.js" ] 然后在app.component.ts中
尝试在我的Angular 2(version = 4.2.x)项目中使用客户端pdf库
pdfmake.
在.angular-cli.json文件中,我声明了这样的js: "scripts": [ "../node_modules/pdfmake/build/pdfmake.js","../node_modules/pdfmake/build/vfs_fonts.js" ] 然后在app.component.ts中,我使用它像这样: import * as pdfMake from 'pdfmake'; @Component({ selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit { pdf: any; downloadPdf() { let item = {firstName: 'Peter',lastName: 'Parker'}; this.pdf = pdfMake; this.pdf.createPdf(buildPdf(item)).open(); } } function buildPdf(value) { var pdfContent = value; var docDefinition = { content: [{ text: 'My name is: ' + pdfContent.firstName + ' ' + pdfContent.lastName + '.' }] } console.log(pdfContent); return docDefinition; } 加载应用时,我在浏览器控制台中遇到以下错误: Uncaught TypeError: fs.readFileSync is not a function at Object.<anonymous> (linebreaker.js:15) at Object.<anonymous> (linebreaker.js:161) at Object.../../../../linebreak/src/linebreaker.js (linebreaker.js:161) at __webpack_require__ (bootstrap b937441…:54) at Object.../../../../pdfmake/src/textTools.js (textTools.js:4) at __webpack_require__ (bootstrap b937441…:54) at Object.../../../../pdfmake/src/docMeasure.js (docMeasure.js:4) at __webpack_require__ (bootstrap b937441…:54) at Object.../../../../pdfmake/src/layoutBuilder.js (layoutBuilder.js:7) at __webpack_require__ (bootstrap b937441…:54) 我解决这个问题的解决方法是: 将pdfmake.js和vfs_fonts.js复制到assets文件夹,然后将其添加到index.html: <script src='assets/pdfmake.min.js'></script> <script src='assets/vfs_fonts.js'></script> 从app.component.ts中删除它 import * as pdfMake from 'pdfmake'; 并将其添加到app.component.ts: declare var pdfMake: any; 最后从.angular-cli.js中删除它: "../node_modules/pdfmake/build/pdfmake.js","../node_modules/pdfmake/build/vfs_fonts.js" 它有效,但它仍然是一种解决方法. 任何人都知道如何以Angular / Typscript方式使用此库? 非常感谢!
按照@benny_boe上面的说明,我已经成功了!让我总结一下如下:
第一, npm install pdfmake --save 其次,在下面添加到typings.d.ts: declare module 'pdfmake/build/pdfmake.js'; declare module 'pdfmake/build/vfs_fonts.js'; 第三,在使用pdfMake的文件中,无论是组件还是服务,添加以下行: import * as pdfMake from 'pdfmake/build/pdfmake.js'; import * as pdfFonts from 'pdfmake/build/vfs_fonts.js'; pdfMake.vfs = pdfFonts.pdfMake.vfs; 最后,像往常一样使用pdfMake.xxx(). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |