Nestjs Reportes Genera Pdfs Desde Node Full -mega- <No Ads>
npm install @nestjs/core @nestjs/common puppeteer handlebars @types/puppeteer Create a dedicated module:
// 2. Compile with Handlebars const template = handlebars.compile(htmlTemplate); const html = template(data);
<div class="total">Grand Total: $total</div> </body> </html>
async generateWithTimeout(data: any, timeoutMs = 30000) return Promise.race([ this.generateReport(data), new Promise((_, reject) => setTimeout(() => reject(new Error('PDF generation timeout')), timeoutMs) ), ]); NestJs Reportes Genera PDFs desde Node Full -Mega-
async streamLargeReport(res: Response, data: any) const page = await this.browser.newPage(); await page.setContent(await this.renderHtml(data)); const stream = await page.createPDFStream( format: 'A4', printBackground: true, );
✅ Reuse browser instance across requests ✅ Stream large PDFs instead of buffering ✅ Set proper timeouts for slow renders ✅ Use Docker with pre-installed Chrome
static release(browser: Browser) this.instances.push(browser); return this
async onModuleInit() // Launch browser once (reuse across requests) this.browser = await puppeteer.launch( headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox'], );
const pdf = await page.pdf( format: 'A4', printBackground: true, margin: top: '20mm', bottom: '20mm', left: '15mm', right: '15mm' , );
FROM ghcr.io/puppeteer/puppeteer:20.0.0 WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . waitUntil: 'networkidle0' )
return this.instances.pop()!;
// 3. Generate PDF const page = await this.browser.newPage(); await page.setContent(html, waitUntil: 'networkidle0' );