/nestjs-pdf

Nest js pdf generator

Primary LanguageTypeScriptMIT LicenseMIT

Nestjs PDF Generator

Nest Logo PDF Logo

A simple PDF generator module for nestjs framework.

Original by: https://github.com/toondaey/nestjs-pdf

Table of content (click to expand)

Installation

Installation is as simple as running:

npm install @pyxlab/nestjs-pdf

or

yarn add @pyxlab/nestjs-pdf.

Usage

A basic usage example:

  1. Register the module as a dependency in the module where pdf will be generated:

app.module.ts

import { Module } from '@nestjs/common';
import { PDFModule } from '@pyxlab/nestjs-pdf';

@Module({
    imports: [
        // ... other modules
        PDFModule.register({
            view: {
                root: '/path/to/template',
                engine: 'pug',
            },
        }),
    ],
})
export class AppModule {}

The module could also be registered asynchronously using the registerAsync method.

Examples below:

  • Using factory provider approach
import { Module } from '@nestjs/common';
import { PDFModule, PDFModuleOptions } from '@pyxlab/nestjs-pdf';

@Module({
    imports: [
        // ... other modules
        PDFModule.registerAsync({
            useFactory: (): PDFModuleOptions => ({
                view: {
                    root: '/path/to/template',
                    engine: 'pug',
                },
            }),
        }),
    ],
})
export class AppModule {}
  • Using class or existing provider approach:

./pdf-config.service.ts

import {
    PDFModuleOptions,
    PDFOptionsFactory,
} from '@pyxlab/nestjs-pdf';
import { Injectable } from '@nestjs/common';

@Injectable()
export class PdfConfigService implements PDFOptionsFactory {
    createPdfOptions(): PDFModuleOptions {
        return {
            view: {
                root: 'path/to/template',
                engine: 'pug',
            },
        };
    }
}

The PdfConfigService SHOULD implement the PDFOptionsFactory, MUST declare the createPdfOptions method and MUST return PDFModuleOptions object.

import { Module } from '@nestjs/common';
import { PDFModule } from '@pyxlab/nestjs-pdf';
import { PdfConfigService } from './pdf-config.service';

@Module({
    imports: [
        // ... other modules
        PDFModule.registerAsync({
            useClass: PdfConfigService,
        }),
    ],
})
export class AppModule {}
  1. Inject into service as a dependency:

app.service.ts

import { Injectable } from '@nestjs/common';
import { PDFService } from '@pyxlab/nestjs-pdf';

@Injectable()
export class AppService {
    constructor(
        // ...other dependencies...
        private readonly pdfService: PDFService,
    ) {}
}

In addition to the above, in situations where all your pdf templates are grouped into a single directory but you expect pdf files to be generated in multiple contexts within your nestjs application, it is advisable to register the PDFModule once in the root module of your application and providing it globally. This can be done by setting isGlobal to true either in the PDFModuleRegisterOptions or PDFModuleRegisterAsyncOptions as below:

@Module({
    imports: [
        PDFModule.register({
            isGlobal: true,
            view: {
                root: '/path/to/template',
                engine: 'pug',
            },
        })
        // or...
        PDFModule.registerAsync({
            isGlobal: true,
            useFactory: (): PDFModuleOptions => ({
                view: {
                    root: '/path/to/template',
                    engine: 'pug',
                },
            }),
        }),
    ]
})
export class RootModule {}

Configuration

Module options

This library uses the html-pdf npm package by marcbachmann under the hood which in turn uses phantomjs by ariya for the html-to-pdf conversion, consolidate by tj as html engine parser allowing users to specify their desired engine, as well as juice by Automattic for inlining resources.

The configuration object received by the register method is as below:

export interface PDFModuleRegisterOptions {
    view: ViewOptions;
    juice?: JuiceOptions;
}

The ViewOptions can be further broken down into:

export interface ViewOptions {
    root: string;
    engine: engine;
    extension?: string;
    engineOptions?: ViewEngineOptions;
}

where:

  • root (required) is the location of the template(s). This MUST be a directory.
  • engine (required) MUST be a string name of the engines supported by the consolidate engine parser listed here.
  • extension (optional) SHOULD be provided where the file extension of the engine used is different from its name. e.g. a swig template would use .html as its file extension which is quite different from the engine name. Detailed example found here
  • engineOptions (optional) is a JavaScript object representation of the configuration options of engine used.

The JuiceOptions is exactly the same as required in the juice package specifications here.

Guide

After completing the configuration(s), you can go ahead and inject the pdf service into your class. The service provides three (3) methods (samples below) which can be used to either generate PDF:

  • to a file on the host machine;
  • as a stream (i.e. Readable); or
  • as a Buffer.
import { Injectable } from '@nestjs/common';
import { PDFService } from '@pyxlab/nestjs-pdf';

@Injectable()
export class YourService {
    constructor(private readonly pdfService: PDFService);

    generatePDFToFile(
        template: string,
        filename: string,
        options?: PDFOptions,
    ) {
        this.pdfService.toFile(template, filename, options); // returns Observable<FileInfo>;
    }

    generatePDFToStream(template: string, options?: PDFOptions) {
        this.pdfService.toStream(template, options); // returns Observable<Readable>;
    }

    generatePDFToBuffer(template: string, options?: PDFOptions) {
        this.pdfService.toBuffer(template, options); // returns Observable<Buffer>;
    }
}

Changelog

3.0.5 / 2022-04-11

  • fix(): fix for failing jest tests

3.0.2 / 2022-04-10

  • docs(): correct documentation

3.0.1 / 2022-04-10

  • feat(): support for nestjs ^6.0.0 || ^7.0.0 || ^8.0.0

2.0.6 / 2020-11-23

  • chore(): dependencies updates
  • docs(): installation guide update

2.0.5 / 2020-11-14

  • chore(): dependencies updates

2.0.4 / 2020-11-13

  • docs(): correction of documentation

2.0.0 / 2020-11-12

  • Removes pdf() as the default service provided by the module.
  • Provides an object of class PDFService as its default service.
  • Removes registeration of module by name.
  • PDFService provides three methods for either generating toFile, toStream or toBuffer.

Contributing

Contributions are welcome. However, please read the contribution's guide.