GithubHelp home page GithubHelp logo

toondaey / nestjs-pdf Goto Github PK

View Code? Open in Web Editor NEW
78.0 5.0 37.0 1.03 MB

Nest js pdf generator

License: MIT License

JavaScript 3.51% TypeScript 92.58% Pug 1.14% Shell 1.68% Batchfile 1.09%
nestjs nestjs-backend nestjs-pdf html-pdf

nestjs-pdf's Introduction

Nestjs PDF Generator

Nest Logo PDF Logo

A simple PDF generator module for nestjs framework.

npm Coveralls github npm version LICENCE CircleCI build

Table of content (click to expand)

Installation

Installation is as simple as running:

npm install @t00nday/nestjs-pdf

or

yarn add @t00nday/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 '@t00nday/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 '@t00nday/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 '@t00nday/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 '@t00nday/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 '@t00nday/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 '@t00nday/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.

nestjs-pdf's People

Contributors

dependabot[bot] avatar renovate[bot] avatar snyk-bot avatar toondaey avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

nestjs-pdf's Issues

Change PDF orientation

Hi there,

I want to change the PDF orientation to use landscape instead of portrait. I've tried to change it using custom styling with CSS, but even so the content is still printed as portrait when I generate the PDF.

I also took a look at the docs, but I didn't found anything about this configuration.

Can you help me, please?

Best regards,
Luiz Sandoval.

unable to resolve dependency tree

hello, i cannot install the project i ve this error:

While resolving: [email protected]
npm ERR! Found: @nestjs/[email protected]
npm ERR! node_modules/@nestjs/common
npm ERR! @nestjs/common@"^8.0.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @nestjs/common@"^6.10.0 || ^7.0.0" from [email protected]
npm ERR! node_modules/nestjs-pdf
npm ERR! nestjs-pdf@"*" from the root project

anyone had this problem? how can i fix it?

No data on return on the observable

I setup the project as specified in the example and try getting the data it return, but each time nothing is being returned

this.pdfService.toBuffer('test.hbs').pipe(
map((data) => {
console.log(data);
return data;
}),
);

ENOTDIR: not a directory, open <root>/<template>/html.ejs

Hi,

I'm having a problem with pdf generation.

Here's the module setup in app.module.ts

    PDFModule.register({
      isGlobal: true,
      view: {
        root: './src/modules/pdf/templates',
        engine: 'ejs',
      },
    }),

And the code that is supposed to create my pdf buffer in my controller

const buffer = await this.pdfService.toBuffer('invoice.html.ejs', {locals: {...}});

I'm getting the following error:

ENOTDIR: not a directory, open 'src/modules/pdf/templates/invoice.html.ejs/html.ejs'

It looks like it's creating a path that appends /html.ejs to my path.

If I just pass invoice as the template parameter, I get this :

Error: ENOENT: no such file or directory, open 'src/modules/pdf/templates/invoice/html.ejs'

I suppose I'm doing something wrong with my configuration, but I can't find what that would be. I can assure the file exists in src/modules/pdf/templates/invoice.html.ejs

Thanks in advance !

Compile Error

Hi,

I got this error

Parameter 'pdf' of constructor from exported class has or is using private name 'PDF'.

Jest failed with latest release

Is there something that needs to be done with the new release?

My test suite failed with the following

Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

     ../node_modules/@t00nday/nestjs-pdf/dist/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export * from './pdf.module';
                                                                                      ^^^^^^

    SyntaxError: Unexpected token 'export'

      at Runtime.createScriptFromCode (../node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (../node_modules/@t00nday/nestjs-pdf/index.js:6:10)
    
    ```

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

How to load local images?

I can't load images stored on the server, i have tried with the juice config webResources, relativeTo and reabaseRelativeTo, but it doesn't work..

Please help.

CSS don't load

I can't load my css

Project structure

src/
templates/
  index/
    css/
      style.css
    html.hbs

app.module.ts

PDFModule.register({
      isGlobal: true,
      view: {
        root: join(__dirname, '..', 'templates'),
        engine: 'handlebars',
        extension: 'hbs',
      },
    }),

html.hbs

<html>
<head>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
  <link href="css/style.css" rel="stylesheet">
</head>
<body>
  <h1 class="red">Hello World</h1>
</body>
</html>

style.css

.red {
  color: red;
}

Forced template naming

This is kind of weird to force specific naming pattern of templates. I had to find it in code to configure it right.

    private getTemplatePath(
        template: string,
        { root, extension, engine }: ViewOptions,
    ): string {
        return join(root, template, `html.${extension || engine}`);
    }

What would be the proper nestjs-pdf method to use in a response?

Thank you for this great library, I love how it totally integrates into the nestjs framework!

So in my case I'm using nestjs-pdf as a service for another app.

The idea is my main app will use this as service as a lamda on my server separately.

e.g.
main-app: main app calls ejs-to-pdf to send data to create pdfs!
ejs-to-pdf: ejs app provides pdfs when main-app calls or another authorized app!

And ultimate;y it goes to a S3 bucket.

nestjs-pdf app

app.controller.ts

@Controller('/ejs-to-pdf')
export class AppController {
	constructor(private readonly pdfService: PdfService) {}
	@Public()
	@Post('/quote-letter-to-pdf')
	async requestQuoteLetter(@Body() data: string): Promise<DSResponse<DSError<any>, any>> {
	        console.log('data ', data);
		const fileName: string = 'Quote-Letter-' + new Date().toUTCString() + '.pdf';
		return new DSResponse(null, await this.pdfService.generatePDFToFile(JSON.stringify(data), fileName));
	}
}

I see the data coming through. and I consoled the response as well.

res  DSResponse {
  status: undefined,
  success: true,
  data: Observable {
    source: Observable {
      source: [Observable],
      operator: [Function (anonymous)]
    },
    operator: [Function (anonymous)]
  },
  error: null,
  token: undefined
}

In the main app I'm seeing the file generated in S3, but I get when I try to open it.

Error
Failed to load PDF document.

In the main-app In the service that calls 'ejs-to-pdf` I see the resp in a console.log:

resp <Buffer 7b 22 73 75 63 63 65 73 73 22 3a 74 72 75 65 2c 22 64 61 74 61 22 3a 7b 22 73 6f 75 72 63 65 22 3a 7b 22 73 6f 75 72 63 65 22 3a 7b 22 73 6f 75 72 63 ... 33 more bytes>

And I see the file:


const resp: any = await this.ejsToPdf.makePDF(JSON.stringify(quoteLetterPayload), this.dsConfig.services.webmerge.testMode, true);
		
console.log('resp ', resp);

const filePost: FileStorageReqInfo = new FileStorageReqInfo();
filePost.bucket = this.dsConfig.aws.s3.bucketName; 
filePost.key = `quote/${quoteId}/${docNameWithExt}`;
filePost.buffer = resp;
filePost.contentEncoding = 'utf-8';
filePost.contentType = this.dsUtil.getContentTypeByFile(filePost.key);
const s3Resp: boolean = await this.dsFileService.uploadFile(filePost);

console.log('JSON.stringify(filePost) ', JSON.stringify(filePost));

Any ideas how to get the pdf to open/render correctly?

Observables<Buffer> to Buffer

I am using the latest version of your package. I'm trying to upload the generated buffer to my aws cloud. it looks like this:

...
    const file = this._pdfService.toBuffer('invoice', { locals: { invoice } });
    await this._fileService.uploadDocumentFile(file);
...
  public async uploadDocumentFile(buffer: any): Promise<string> {
    const date = format(new Date(), 'MM/yyyy');
    const key = `invoices/${date}`;

    await this._s3
      .putObject({
        Bucket: this.configService.get('AWS_PRIVATE_BUCKET_NAME_INVOICES'),
        Body: buffer,
        ACL: 'private',
        Key: key,
      })
      .promise();

    return key;
  }

Error:
InvalidParameterType: Expected params.Body to be a string, Buffer, Stream, Blob, or typed array object

How do I do that? I don't have much experience with RxJs

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Warning

These dependencies are deprecated:

Datasource Name Replacement PR?
npm @types/rimraf Unavailable
npm html-pdf Unavailable

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): update dependency @compodoc/compodoc to v1.1.25
  • chore(deps): update dependency @types/consolidate to v0.14.4
  • chore(deps): update dependency @types/html-pdf to v3.0.3
  • chore(deps): update dependency @types/node to v17.0.45
  • chore(deps): update dependency release-it to v14.14.3
  • chore(deps): update dependency ts-jest to v27.1.5
  • chore(deps): update nest monorepo to v8.4.7 (@nestjs/common, @nestjs/platform-express, @nestjs/testing)
  • chore(deps): update dependency @types/jest to v27.5.2
  • chore(deps): update dependency eslint to v8.57.0
  • chore(deps): update dependency eslint-config-prettier to v8.10.0
  • chore(deps): update dependency eslint-plugin-import to v2.29.1
  • chore(deps): update dependency prettier to v2.8.8
  • chore(deps): update dependency reflect-metadata to v0.2.2
  • chore(deps): update dependency rxjs to v7.8.1
  • fix(deps): update dependency juice to v8.1.0
  • chore(deps): update commitlint monorepo to v19 (major) (@commitlint/cli, @commitlint/config-conventional, @commitlint/prompt-cli)
  • chore(deps): update dependency @types/node to v20
  • chore(deps): update dependency @types/rimraf to v4
  • chore(deps): update dependency dotenv-cli to v7
  • chore(deps): update dependency eslint to v9
  • chore(deps): update dependency eslint-config-prettier to v9
  • chore(deps): update dependency husky to v9
  • chore(deps): update dependency lint-staged to v15
  • chore(deps): update dependency prettier to v3
  • chore(deps): update dependency release-it to v17
  • chore(deps): update dependency renovate to v38
  • chore(deps): update dependency rimraf to v6
  • chore(deps): update dependency typescript to v5
  • chore(deps): update nest monorepo to v10 (major) (@nestjs/common, @nestjs/platform-express, @nestjs/testing)
  • chore(deps): update typescript-eslint monorepo to v8 (major) (@typescript-eslint/eslint-plugin, @typescript-eslint/parser)
  • fix(deps): update dependency consolidate to v1
  • fix(deps): update dependency juice to v10
  • 🔐 Create all rate-limited PRs at once 🔐

Edited/Blocked

These updates have been manually edited so Renovate will no longer make changes. To discard all commits and start over, click on a checkbox.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

npm
package.json
  • consolidate 0.16.0
  • html-pdf 3.0.1
  • juice 8.0.0
  • lodash.merge 4.6.2
  • lodash.omit 4.5.0
  • @commitlint/cli 16.2.3
  • @commitlint/config-conventional 16.2.1
  • @commitlint/prompt-cli 16.2.3
  • @compodoc/compodoc 1.1.19
  • @nestjs/common 8.4.4
  • @nestjs/core 8.4.4
  • @nestjs/platform-express 8.4.4
  • @nestjs/testing 8.4.4
  • @types/consolidate 0.14.1
  • @types/html-pdf 3.0.0
  • @types/jest 27.4.1
  • @types/lodash.merge 4.6.6
  • @types/lodash.omit 4.5.6
  • @types/node 17.0.23
  • @types/rimraf 3.0.2
  • @typescript-eslint/eslint-plugin 5.19.0
  • @typescript-eslint/parser 5.19.0
  • coveralls 3.1.1
  • dotenv-cli 5.1.0
  • eslint 8.13.0
  • eslint-config-prettier 8.5.0
  • eslint-plugin-import 2.26.0
  • husky 7.0.4
  • jest 27.5.1
  • lint-staged 12.3.8
  • prettier 2.6.2
  • pug 3.0.2
  • reflect-metadata 0.1.13
  • release-it 14.14.2
  • renovate 32.17.1
  • rimraf 3.0.2
  • rxjs 7.5.5
  • ts-jest 27.1.4
  • typescript 4.6.3
  • @nestjs/common ^6.10.0 || ^7.0.0 || ^8.0.0
  • reflect-metadata ^0.1.12
  • rxjs ^6.0.0 || ^7.0.0
  • node >=12.22.0
  • npm >=6.14.16

  • Check this box to trigger a request for Renovate to run again on this repository

Passing data

how to send data from service to template engine ( pug, handlebars etc.. )

Please make sure that the argument PdfToken(default) at index [5] is available in the AppModule context...

Hi there! im trying to implement your library by following your instructions but i'm getting this error:

[Nest] 21182   - 06/19/2020, 11:24:57 PM   [ExceptionHandler] Nest can't resolve dependencies of the AppService (ProfilesService, UsersService, MyLogger, RulesService, ConfigService, ?). Please make sure that the argument PdfToken(default) at index [5] is available in the AppModule context.

Potential solutions:
- If PdfToken(default) is a provider, is it part of the current AppModule?
- If PdfToken(default) is exported from a separate @Module, is that module imported within AppModule?
  @Module({
    imports: [ /* the Module containing PdfToken(default) */ ]
  })

Is there anything missing on the exports/imports side?

thank you

Creation PDF simultaneously fails

Use this library in RabbitMQ consumer app and faced with simultaneous PDF Docs generation problem:

Request for 3 docs producess this:
Doc 1. started
Doc 2. started
Doc 3. started

Doc 3. done successfully
Doc 2. [Nest] 811334 - 06/06/2022, 1:12:07 PM ERROR [RpcExceptionsHandler] ENOENT: no such file or directory, open '/tmp/html-pdf-811334.pdf'
Doc 1. [Nest] 811334 - 06/06/2022, 1:12:07 PM ERROR [RpcExceptionsHandler] ENOENT: no such file or directory, open '/tmp/html-pdf-811334.pdf'

As I understand, this is the problem:
in lib/pdf.default.ts

export const defaultCreateOptions = {
    filename: join(tmpdir(), `html-pdf-${process.pid}.pdf`),
};

Think using random name for each file will solve the problem.

margin problem

Hello, Mr developer
I have one problem using this lib.
Currently I generate pdf using PDFService.toBuffer() function in my project. Everythings are ok.
but I don't know how to change margins of pdf page. I googled whole day but still not found the way.
plz give me advice.
Thanks

Problem with pagesize and offset

im having issues with spacing and using the full height of a generated pdf.

ive set up my module for the documents like this (ignore the typeorm stuff):

import { Module, forwardRef } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { PDFModule } from '@t00nday/nestjs-pdf';
import path from 'path';
import { Angebot } from 'src/models/angebot.entity';
import { Kunde } from 'src/models/kunde.entity';
import { KundenModule } from '../kunden/kunden.module';
import { StandorteModule } from '../standorte/standorte.module';
import { AngeboteService } from './angebote.service';
import { DokumenteController } from './dokumente.controller';
import { DokumenteService } from './dokumente.service';
import { StandortToAngebot } from 'src/models/standortToAngebot.entity';
import { Vertrag } from 'src/models/vertrag.entity';
import { Standort } from 'src/models/standort.entity';
import { StandortToVertrag } from 'src/models/standortToVertrag.entity';
import { RechnungService } from './rechnungen.service';
import { Rechnung } from 'src/models/rechnung.entity';
import { StandortToRechnung } from 'src/models/standortToRechnung';
import { Storno } from 'src/models/storno.entity';
import { StornoService } from './storno.service';
import { GutschriftService } from './gutschrift.service';
import { Gutschrift } from 'src/models/gutschrift.entity';
import { CronJobService } from './cron.job';

@Module({
    imports: [
        PDFModule.register({
            isGlobal: true,
            view: {
                root: __dirname,
                engine: 'handlebars',
                extension: 'hbs',
            },
        }),
        KundenModule,
        StandorteModule,
        TypeOrmModule.forFeature([
            Angebot,
            Kunde,
            StandortToAngebot,
            Vertrag,
            Standort,
            StandortToVertrag,
            Rechnung,
            StandortToRechnung,
            Storno,
            Gutschrift
        ]),
    ],
    controllers: [DokumenteController],
    providers: [DokumenteService,GutschriftService,RechnungService, AngeboteService,StornoService,CronJobService],
})
export class DokumenteModule {}

within my service i have this generate function for generating the pdf with the chosen template

private readonly angebotTemplatePath = 'pdf/angebot';
    private readonly angebotOutputPath = `${path.join(
        process.cwd(),
        'pdf/angebote/',
    )}`;

    async generatePDFToFile(
        template: string,
        fileName: string,
        inputData: any,
    ) {
        const pdfOptions = {
            locals: inputData,
            format: 'A4', // Papierformat, z.B. 'A4', 'Letter', 'Legal', etc.
        };

        const outputPath = path.join(this.angebotOutputPath, fileName);

        return this.pdfService.toFile(template, outputPath, pdfOptions);
    }

so far ive created a simple html.hbs file with only this content:

<style>
    .the-div{
        height: 100%;
        width: 100%;
        border: 1px solid red;
    }
</style>

<div class="the-div"></div>
<div class="the-div"></div>
<div class="the-div"></div>
<div class="the-div"></div>

now, when i generate the pdf i can see the red border of the div being offset more and more page by page (look at the file included)

how can i fix that? i need the div to be 100% height on each page

test.pdf

Error create buffer

When trying to create I get this error:
Error: html-pdf: Unknown Error Auto configuration failed 140560640587712:error:0E079065:configuration file routines:DEF_LOAD_BIO:missing equal sign:conf_def.c:362:line 1 at ChildProcess.respond (/*/24/proyectos/p/api/node_modules/html-pdf/lib/pdf.js:134:17) at ChildProcess.emit (node:events:390:28) at Process.ChildProcess._handle.onexit (node:internal/child_process:290:12)

How can I pass data to script js

How can I pass data to script js. By the way I'm using file hbs and I can pass data to code html by using {{}} but in the script is difficult

Creating a stream without file

I would need the created file to put on my AWS S3 bucket. For that, I would have to do something similar to this:

  pdf.create(html, options).toStream(function(err, stream) {
    if (err) return console.log(err)
    uploadToS3(stream, filename)
  });

Is it possible to use this package?

PDFService not found

I was following the documentation and creating an injectable class but PDFService is not found.

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

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

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

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

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

}

---eslint error hint----
import PDFService

Module '"../../../node_modules/nestjs-pdf"' has no exported member 'PDFService'.

I am I missing something ?

Is it possible to add a new pdf page?

I'm creating invoices, but sometimes is required to add another page when the invoice lines exceed some number.
So, is there a way to do this using this library?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.