74 lines
2.0 KiB
TypeScript
74 lines
2.0 KiB
TypeScript
|
|
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<any>): Promise<any> {
|
||
|
|
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 = `
|
||
|
|
<!DOCTYPE html>
|
||
|
|
<html>
|
||
|
|
<head>
|
||
|
|
<meta charset="UTF-8">
|
||
|
|
<script src="https://cdn.tailwindcss.com"></script>
|
||
|
|
<style>
|
||
|
|
html, body { margin: 0; padding: 0; }
|
||
|
|
body { zoom: 1.4; transform-origin: top left; }
|
||
|
|
@page { size: ${width} ${height || 'auto'}; margin: 0; }
|
||
|
|
</style>
|
||
|
|
</head>
|
||
|
|
<body>${data.html}</body>
|
||
|
|
</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);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|