import { Processor, WorkerHost } from '@nestjs/bullmq'; import { Job } from 'bullmq'; import * as puppeteer from 'puppeteer'; import * as pdfPrinter from 'pdf-to-printer'; import * as path from 'path'; import * as fs from 'fs'; import * as os from 'os'; @Processor('printer') export class PrinterProcessor extends WorkerHost { async process(job: Job): Promise { const data = job.data; const tempFilePath = path.join(os.tmpdir(), `print-${job.id}-${Date.now()}.pdf`); let browser; try { browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox'] }); const page = await browser.newPage(); const width = data.width || '80mm'; const height = data.height; const fullHtml = ` ${data.html} `; await page.setContent(fullHtml, { waitUntil: 'networkidle0' }); const pdfOptions: any = { path: tempFilePath, printBackground: true, width: width, margin: { top: '0px', right: '0px', bottom: '0px', left: '0px' } }; if (height) pdfOptions.height = height; await page.pdf(pdfOptions); await browser.close(); await pdfPrinter.print(tempFilePath, { printer: data.printerName, silent: true }); return { status: 'success', jobId: job.id }; } catch (error) { if (browser) await browser.close(); console.error(`Erro no Job ${job.id}:`, error); throw error; } finally { if (fs.existsSync(tempFilePath)) { fs.unlinkSync(tempFilePath); } } } }