toondaey / nestjs-pdf Goto Github PK
View Code? Open in Web Editor NEWNest js pdf generator
License: MIT License
Nest js pdf generator
License: MIT License
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
Hi,
@t00nday/nestjs-pdf is not recognising in the nest-js library.
below given is the error . any idea on this ?
src/config/pdf/Pdf.service.ts:1:28 - error TS2307: Cannot find module '@t00nday/nestjs-pdf' or its corresponding type declarations.
import { PDFService } from '@t00nday/nestjs-pdf';
how to send data from service to template engine ( pug, handlebars etc.. )
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
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
Hi,
I got this error
Parameter 'pdf' of constructor from exported class has or is using private name 'PDF'.
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.
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
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?
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?
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
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?
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.
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.
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 !
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}`);
}
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
style.css
.red {
color: red;
}
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.
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;
}),
);
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)
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 |
|
npm | html-pdf |
These updates are currently rate-limited. Click on a checkbox below to force their creation now.
@nestjs/common
, @nestjs/platform-express
, @nestjs/testing
)@commitlint/cli
, @commitlint/config-conventional
, @commitlint/prompt-cli
)@nestjs/common
, @nestjs/platform-express
, @nestjs/testing
)@typescript-eslint/eslint-plugin
, @typescript-eslint/parser
)These updates have been manually edited so Renovate will no longer make changes. To discard all commits and start over, click on a checkbox.
@commitlint/cli
, @commitlint/config-conventional
, @commitlint/prompt-cli
)These updates have all been created already. Click a checkbox below to force a retry/rebase of any.
@typescript-eslint/eslint-plugin
, @typescript-eslint/parser
)@types/jest
, jest
, ts-jest
)These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.
.circleci/config.yml
coveralls 1.0.6
cimg/node 12.22.0
cimg/node 14.19
cimg/node 16.14
cimg/node 16.14
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
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?
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 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)
```
When will it be compatible with nestjs version 9 ?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.