Search code examples
javascripttypescriptangularpdfmake

Use pdfMake with data input in Angular 2 / TypeScript


I'm trying to create PDF from data input in an Angular 2 project. To do this, I integrated pdfMake. Creating static PDF works just fine, but the moment I try to print out some values, it goes wrong.

Please have a look at this plunker: https://plnkr.co/edit/7tPFTAjKWwaRp1IbT0Tg?p=preview

I manage to put an object into my buildPdf function and it gets loged to the console. But when I try to add one of my object values to the pdfMake docdefinition, I'm getting the error message:

ORIGINAL EXCEPTION: TypeError: Cannot read property 'firstName' of undefined

var docDefinition = {
    content: [{
        text: 'My name is: ' + pdfContent.firstName  + ' ' + pdfContent.lastName + '.'
    }]
}

I tried to rule out a typing issue by rewriting my buildPdf.js in typescript, which looked something like this:

var buildPdf: (value: {firstName: string, lastName: string}) => any =
function(value: {firstName: string, lastName: string}): any {
    let docDefinition:any = {
        content: [{
            text: 'This is a test.'
        }]
    }
    console.log(value);
    return docDefinition;
}

The result stayed the same, though.

Why am I able to console.log the object but not to access its properties? What have I missed?


Solution

  • Seems to be caused by this line

    buildPdf: any = new buildPdf();
    

    I don't see what you need it for. It throws because it accesses the passed value but here none is passed.

    See https://plnkr.co/edit/NPLHxVgC5LthA4g2WpUx?p=preview for the working Plunker.