Angular2:如何使用pdfmake库

前端之家收集整理的这篇文章主要介绍了Angular2:如何使用pdfmake库前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
尝试在我的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().

原文链接:https://www.f2er.com/angularjs/142474.html

猜你在找的Angularjs相关文章