Jeferson Narvaez
Jeferson Narvaez

Reputation: 21

Generate PDF with NestJS typescript using pdfmake library

I wasn't able to find information about how implement this library in nest js beacuse documentation is incomplete so am letting this here, you need first npm install pdfmake --save and npm install @types/pdfmake --save-dev then this code is working for me using node 20

import { Injectable } from '@nestjs/common';
import pdfFonts from 'pdfmake/build/vfs_fonts';
import * as fs from 'fs';
import pdfMake from 'pdfmake/build/pdfmake';
import { TDocumentDefinitions } from 'pdfmake/interfaces';

@Injectable()
export class AppService {
  constructor() {
    (pdfMake as any).vfs = pdfFonts.pdfMake.vfs;
  }
  getHello() {
    const dd: TDocumentDefinitions = {
      content: [
        'First paragraph',
        'Another paragraph, this time a little bit longer to make sure, this line will be divided into at least two lines',
        {
          text: 'This paragraph will have a bigger font',
          fontSize: 15,
          color: 'blue',
        },
        {
          columns: [
            {
              text: 'This is a column',
            },
            {
              text: 'Another column',
            },
          ],
        },
        { text: 'Tables', style: 'header' },
        'Official documentation is in progress, this document is just a glimpse of what is possible with pdfmake and its layout engine.',
        {
          text: 'A simple table (no headers, no width specified, no spans, no styling)',
          style: 'subheader',
        },
        'The following table has nothing more than a body array',
        {
          style: 'tableExample',
          table: {
            body: [
              ['Column 1', 'Column 2', 'Column 3'],
              ['One value goes here', 'Another one here', 'OK?'],
            ],
          },
        },
      ],
    };

    const pdfDoc = pdfMake.createPdf(dd);

    pdfDoc.getBuffer((buffer) => {
      fs.writeFileSync('pdf/output.pdf', buffer);
      console.log('PDF saved successfully');
    });

    return 'Hello World!';
  }
}

Just to let others the way to implement is a readdly good library to generate pdfs from backend

Upvotes: 0

Views: 570

Answers (1)

In another installation this worked for me with nodejs20 and nest version 10.4.5

import { Injectable } from '@nestjs/common';
import * as pdfFonts from 'pdfmake/build/vfs_fonts';
import * as fs from 'fs';
import * as pdfMake from 'pdfmake/build/pdfmake';
import { TDocumentDefinitions } from 'pdfmake/interfaces';

Upvotes: 0

Related Questions