Nestjs Reportes Genera Pdfs Desde Node Full -mega- Direct
// 2. Compile with Handlebars const template = handlebars.compile(htmlTemplate); const html = template(data);
// Option 3: Return base64 (for email attachments) @Post('base64') async getBase64(@Body() data: any) const pdfBuffer = await this.pdfService.generateReport('sales', data); return base64: pdfBuffer.toString('base64') ;
res.setHeader('Content-Type', 'application/pdf'); res.setHeader('Content-Disposition', 'attachment; filename=large-report.pdf');
Now go generate those reports! 📄🚀
stream.pipe(res);
✅ Reuse browser instance across requests ✅ Stream large PDFs instead of buffering ✅ Set proper timeouts for slow renders ✅ Use Docker with pre-installed Chrome
// 3. Generate PDF const page = await this.browser.newPage(); await page.setContent(html, waitUntil: 'networkidle0' ); NestJs Reportes Genera PDFs desde Node Full -Mega-
static release(browser: Browser) this.instances.push(browser);
Generating PDFs is a common requirement for invoices, reports, analytics dashboards, and legal documents. NestJS, with its modular architecture, provides a clean way to integrate PDF generation.
async generateWithTimeout(data: any, timeoutMs = 30000) return Promise.race([ this.generateReport(data), new Promise((_, reject) => setTimeout(() => reject(new Error('PDF generation timeout')), timeoutMs) ), ]); Generate PDF const page = await this
return this.instances.pop()!;
handlebars.registerHelper('multiply', (a, b) => a * b); // pdf.controller.ts import Controller, Post, Body, Res, Get, Query from '@nestjs/common'; import Response from 'express'; import PdfService from './pdf.service'; @Controller('reports') export class PdfController { constructor(private readonly pdfService: PdfService) {}
const pdf = await page.pdf( format: 'A4', printBackground: true, margin: top: '20mm', bottom: '20mm', left: '15mm', right: '15mm' , ); waitUntil: 'networkidle0' )
async onModuleDestroy() if (this.browser) await this.browser.close();