diff --git a/src/server/services/PdfService.ts b/src/server/services/PdfService.ts index 9aecc43..d7584f9 100644 --- a/src/server/services/PdfService.ts +++ b/src/server/services/PdfService.ts @@ -1,6 +1,11 @@ import puppeteer from 'puppeteer'; import { prisma } from '../prismaClient'; +// Função utilitária para converter pixels em milímetros (1px ≈ 0.264583 mm) +function pxToMm(px: number): string { + return (px * 0.264583).toFixed(2) + 'mm'; +} + export class PdfService { private async getConfiguracao() { try { @@ -17,12 +22,12 @@ export class PdfService { timbradoMarginBottom: true, timbradoMarginLeft: true, timbradoMarginRight: true, + cabecalhoHtml: true, + rodapeHtml: true, criadoEm: true } }); - console.log('Configuração encontrada:', config); // Debug - // Retornar configuração padrão se não existir return { cabecalhoHtml: config?.cabecalhoHtml || ` @@ -54,8 +59,7 @@ export class PdfService { ? `${process.env.FRONTEND_URL || 'http://localhost:5000'}${config.timbradoUrl}` : ''; - console.log('Gerando PDF com timbrado:', timbradoUrl); - + // CSS para background em todas as páginas return ` @@ -63,33 +67,40 @@ export class PdfService { -
-
- ${content} -
+
+ ${content}
@@ -109,42 +118,33 @@ export class PdfService { async gerarPDF(conteudo: string, escritorio: any) { try { - const config = await prisma.configuracaoDocumento.findFirst({ - orderBy: { criadoEm: 'desc' } - }); - - console.log('Configuração do PDF:', config); - + const config = await this.getConfiguracao(); const html = this.gerarHTML(conteudo, config); - + const browser = await puppeteer.launch({ headless: 'new', args: ['--no-sandbox'] }); - const page = await browser.newPage(); - - await page.setViewport({ - width: 794, // A4 width in pixels (72 dpi) - height: 1123, - deviceScaleFactor: 2 - }); - - await page.setContent(html, { + await page.setContent(html, { waitUntil: ['networkidle0', 'load'], timeout: 30000 }); - + // Margens convertidas para mm + const margin = { + top: pxToMm(config.timbradoMarginTop), + bottom: pxToMm(config.timbradoMarginBottom), + left: pxToMm(config.timbradoMarginLeft), + right: pxToMm(config.timbradoMarginRight) + }; const pdfBuffer = await page.pdf({ format: 'A4', printBackground: true, - margin: { top: '0', right: '0', bottom: '0', left: '0' }, + margin, preferCSSPageSize: true }); - await browser.close(); return Buffer.from(pdfBuffer); - } catch (error) { console.error('Erro ao gerar PDF:', error); throw new Error('Falha ao gerar PDF');