Search code examples
aws-lambdapdfkitpdfmake

CDK Lambda NodejsFunction pdfmake ENOENT Error


I'm trying to upgrade Lambda js code that uses pdfmake 0.1.64 to CDK Lambda NodejsFunction typescript code that uses pdfmake 0.2.5.

I'm getting the error: "ENOENT: no such file or directory, open '/var/task/data.trie'"

The error is generated when this line of code is included in the Lambda function:

import PdfPrinter = require('pdfmake');

Searching for this error implies that this is a pdfkit error. My understanding is pdfmake is based on pdfkit.

Docs: "Use pdfmake on server-side" https://pdfmake.github.io/docs/0.1/fonts/standard-14-fonts/

Additional Lambda typescript code (for reference):

import PdfPrinter = require('pdfmake');

const fonts = {
    Courier: {
        normal: 'Courier',
        bold: 'Courier-Bold',
        italics: 'Courier-Oblique',
        bolditalics: 'Courier-BoldOblique'
    },
    Helvetica: {
        normal: 'Helvetica',
        bold: 'Helvetica-Bold',
        italics: 'Helvetica-Oblique',
        bolditalics: 'Helvetica-BoldOblique'
    },
    Times: {
        normal: 'Times-Roman',
        bold: 'Times-Bold',
        italics: 'Times-Italic',
        bolditalics: 'Times-BoldItalic'
    },
    Symbol: {
        normal: 'Symbol'
    },
    ZapfDingbats: {
        normal: 'ZapfDingbats'
    }
};

const docDefinition = {
    content: [
        'First paragraph'
    ],
    defaultStyle: {
        font: 'Helvetica'
    }
};

const printer = new PdfPrinter(fonts);
const doc = printer.createPdfKitDocument(docDefinition);
doc.end();

Solution

  • The following CDK Lambda setting fixed this error.

    new lambdaNJS.NodejsFunction(this, 'MyLambdaFunction', {
        ...
        bundling: {
            ...
            nodeModules: ['pdfmake'], //  List of modules that should NOT be bundled but instead included in the node_modules folder.
        }
    });
    

    In Lambda (force Typescript to ignore the type error). It's not clear how to get types working. The package.json includes @types/pdfmake package.

    // @ts-ignore
    const doc = printer.createPdfKitDocument(definition, options);