How to generate PDF using Nest JS

First Create Nest application

nest new generate-pdf
cd generate-pdf

Then install pdfmake NPM plugin

npm install pdfmake

In your controller Import below

import * as fs from ‘fs’;
import * as PdfPrinter from ‘pdfmake’;
import * as uuid from ‘uuid/v4’;

In your function add the below code

@Get('/generatePDF')
  generatePDF() {
    const fonts = {
      Helvetica: {
        normal: 'Helvetica',
        bold: 'Helvetica-Bold',
        italics: 'Helvetica-Oblique',
        bolditalics: 'Helvetica-BoldOblique'
      }
    };
    const printer = new PdfPrinter(fonts);

    const docDefinition = {
      content: [
        { text: 'Heading', fontSize: 25},
        {
          layout: 'lightHorizontalLines', // optional
          table: {
            headerRows: 1,
            widths: [ '*', 'auto', 100, '*' ],

            body: [
              [ 'First', 'Second', 'Third', 'The last one' ],
              [ 'Value 1', 'Value 2', 'Value 3', 'Value 4' ],
              [ 'Val 1','Val 2', 'Val 3', 'Val 4' ]
            ],
          },
        },
        {text: 'google', link: 'http://google.com', pageBreak: 'before',},
        { qr: 'text in QR', foreground: 'green', background: 'white' },
      ],
      defaultStyle: {
        font: 'Helvetica'
      }
    };

    const options = {
    }
    let file_name = 'PDF' + uuid() + '.pdf';
    const pdfDoc = printer.createPdfKitDocument(docDefinition, options);
    pdfDoc.pipe(fs.createWriteStream(file_name));
    pdfDoc.end();
    return {'file_name': file_name};
  }

Reference: http://pdfmake.org/#/

2 thoughts on “How to generate PDF using Nest JS

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create your website with WordPress.com
Get started
%d bloggers like this: