使用Angular 4和Webpack制作pdfMake

Making pdfMake work with Angular 4 and webpack

我想在我的Angular 4应用程序中使用pdfMake,所以我尝试了此操作,但是由于我正在使用webpack,所以webpack给了我这个错误:

1
Could not find a declaration file for module 'pdfmake/build/pdfmake'

因此,我将脚本添加到了vendor.ts列表中

1
2
import 'pdfmake/build/pdfmake';
import 'pdfmake/build/vfs_fonts';

将我的ProvidePlugin更改为以下内容:

1
2
3
4
5
6
7
new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery',
        Popper: ['popper.js', 'default'],
        pdfMake: 'pdfmake'
    }),

,并在我要使用pdfMake

的组件中执行了此操作

1
2
3
4
5
6
7
8
9
10
11
12
13
//imports
declare var pdfMake: any;
declare var pdfFonts: any;

@Component....
export class MyComponent {
    constructor () {
         pdfMake.vfs = pdfFonts.pdfMake.vfs;
         var dd = { content: 'your pdf dataaaaaaaa' };
         pdfMake.createPdf(dd).download();
    }

}

这给了我ReferenceError: pdfFonts is not defined错误,但是如果我注释掉了构造函数和声明中的第一行,就会得到这个错误:

1
ERROR Error: File 'Roboto-Regular.ttf' not found in virtual file system

,这是pdfMake错误。

我的问题是如何从vfs_fonts文件声明字体,以便我可以使用它们?


我最终制作了一个如下所示的PrinterService:

1
2
3
4
5
6
7
8
9
10
11
@Injectable()
export class PrinterService {
    private readonly pdfFonts: any;
    pdfMake: any;

    constructor() {
        this.pdfMake = require('pdfmake/build/pdfmake.js');
        this.pdfFonts = require('pdfmake/build/vfs_fonts.js');
        this.pdfMake.vfs = this.pdfFonts.pdfMake.vfs;
    }
}

我有一个函数可以返回带有预定义页眉和页脚,页码等的预定义对象,因此您不必在需要的任何地方键入文档定义。


我已经测试过,这对我有用。

  • npm install pdfmake --save
  • 在组件或服务内部:

    import * as pdfMake from 'pdfmake/build/pdfmake';
    import * as pdfFonts from 'pdfmake/build/vfs_fonts';
  • 内部构造函数:

    constructor() { pdfMake.vfs = pdfFonts.pdfMake.vfs; }
  • 您想使用pdfmake的任何地方:

    const dd = { content: 'your pdf data' };
    pdfMake.createPdf(dd).open();