GregoryHouseMD
GregoryHouseMD

Reputation: 2378

Making pdfMake work with Angular 4 and webpack

I want to use pdfMake in my Angular 4 app so I tried this, but since I'm using webpack, webpack gave me this error:

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

So, I added the scripts to my vendor.ts list

import 'pdfmake/build/pdfmake';
import 'pdfmake/build/vfs_fonts';

changed my ProvidePlugin to the following:

new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery',
        Popper: ['popper.js', 'default'],
        pdfMake: 'pdfmake'
    }),

and did this in the component where I wanna use pdfMake

//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();
    }

}

This gave me the ReferenceError: pdfFonts is not defined error, but if I comment out the first line in the constructor and the declaration, I get this error:

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

which is a pdfMake error.

My question would be how to declare the fonts from the vfs_fonts file so I can use them?

Upvotes: 1

Views: 3328

Answers (3)

Psycho99
Psycho99

Reputation: 16

In Vs code the console propose to do this:

npm i --save-dev @types/pdfmake

This solved my import for the dev build and allow me to ng serve my test version.

You must add this line under your imports:

(pdfMake as any).vfs = pdfFonts.pdfMake.vfs;

It's right under your import where you want to use pdfMake.

You can't avoid it or else it will generate a blank document not even opened as a PDF document.

Upvotes: 0

xwa130
xwa130

Reputation: 649

I have tested, this works for me.

  1. npm install pdfmake --save
  2. Inside the component or service: import * as pdfMake from 'pdfmake/build/pdfmake'; import * as pdfFonts from 'pdfmake/build/vfs_fonts';
  3. inside constructor: constructor() { pdfMake.vfs = pdfFonts.pdfMake.vfs; }
  4. anywhere you want to use pdfmake: const dd = { content: 'your pdf data' }; pdfMake.createPdf(dd).open();

Upvotes: 2

GregoryHouseMD
GregoryHouseMD

Reputation: 2378

I ended up making a PrinterService that looks like this:

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

I have a function that returns a predefined object with predefined header and footer, page numbers etc. so you don't have to type out the document definition everywhere you need it.

Upvotes: 2

Related Questions