tenta fix pdfservice.js
This commit is contained in:
1 parent
0908378ca0
commit
00a9fb9557
2 files changed
+227
-7
No files matched your search
@@ -0,0 +1,219 @@
|
||||
import puppeteer from 'puppeteer';
|
||||
import { PDFDocument } from 'pdf-lib';
|
||||
import fs from 'fs/promises';
|
||||
import path from 'path';
|
||||
import { prisma } from '../prismaClient';
|
||||
|
||||
// Função utilitária para converter pixels em milímetros (1px ≈ 0.264583 mm)
|
||||
function pxToMm(px: number | null | undefined): string {
|
||||
if (!px) return '0mm';
|
||||
return (px * 0.264583).toFixed(2) + 'mm';
|
||||
}
|
||||
|
||||
export class PdfService {
|
||||
// Busca configuração do documento, usando apenas campos válidos do schema
|
||||
private async getConfiguracao() {
|
||||
try {
|
||||
const config = await prisma.configuracaoDocumento.findFirst({
|
||||
orderBy: { criadoEm: 'desc' },
|
||||
select: {
|
||||
id: true,
|
||||
timbradoUrl: true,
|
||||
timbradoMarginTop: true,
|
||||
timbradoMarginBottom: true,
|
||||
timbradoMarginLeft: true,
|
||||
timbradoMarginRight: true,
|
||||
templatePadrao: true,
|
||||
margensTemplate: true,
|
||||
criadoEm: true
|
||||
}
|
||||
});
|
||||
// Extrai recuo de primeira linha se existir em margensTemplate
|
||||
let firstLineIndent = '0mm';
|
||||
if (config?.margensTemplate) {
|
||||
try {
|
||||
const margens = typeof config.margensTemplate === 'string' ? JSON.parse(config.margensTemplate) : config.margensTemplate;
|
||||
if (margens && margens.firstLineIndent) {
|
||||
firstLineIndent = `${margens.firstLineIndent}mm`;
|
||||
}
|
||||
} catch (e) {
|
||||
// Se der erro, ignora e usa padrão
|
||||
}
|
||||
}
|
||||
return {
|
||||
timbradoUrl: config?.timbradoUrl || '',
|
||||
timbradoMarginTop: config?.timbradoMarginTop ?? 100,
|
||||
timbradoMarginBottom: config?.timbradoMarginBottom ?? 50,
|
||||
timbradoMarginLeft: config?.timbradoMarginLeft ?? 50,
|
||||
timbradoMarginRight: config?.timbradoMarginRight ?? 50,
|
||||
templatePadrao: config?.templatePadrao || '',
|
||||
firstLineIndent
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Erro ao buscar configuração:', error);
|
||||
throw new Error('Falha ao buscar configuração');
|
||||
}
|
||||
}
|
||||
|
||||
// Gera HTML com timbrado e margens
|
||||
private gerarHTML(content: string, config: any) {
|
||||
// Limpa espaços, quebras de linha e tags vazias do final do conteúdo
|
||||
let cleanContent = content
|
||||
.replace(/(\s|<br\s*\/?>|<p>\s*<\/p>)+$/gi, '')
|
||||
.replace(/(<p>\s*<\/p>)+/gi, '');
|
||||
const timbradoUrl = config.timbradoUrl
|
||||
? `${process.env.FRONTEND_URL || 'http://localhost:5000'}${config.timbradoUrl}`
|
||||
: '';
|
||||
// Adiciona log para debug
|
||||
if (timbradoUrl) {
|
||||
console.log('[PDF] Timbrado inserido no HTML:', timbradoUrl);
|
||||
}
|
||||
return `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<link href="https://fonts.googleapis.com/css2?family=Fira+Sans:wght@400;500;600&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
@page {
|
||||
margin-top: ${pxToMm(config.timbradoMarginTop)};
|
||||
margin-bottom: ${pxToMm(config.timbradoMarginBottom)};
|
||||
margin-left: ${pxToMm(config.timbradoMarginLeft)};
|
||||
margin-right: ${pxToMm(config.timbradoMarginRight)};
|
||||
size: A4;
|
||||
}
|
||||
html, body {
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
font-family: 'Fira Sans', Arial, sans-serif;
|
||||
font-size: 11pt;
|
||||
line-height: 1.5;
|
||||
background: none;
|
||||
}
|
||||
body {
|
||||
position: relative;
|
||||
min-height: 100vh;
|
||||
/* Remove background-image do body para evitar problemas no Puppeteer */
|
||||
}
|
||||
.timbrado-bg {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
z-index: 0;
|
||||
${timbradoUrl ? `background-image: url('${timbradoUrl}'); background-size: cover; background-position: center; background-repeat: no-repeat;` : ''}
|
||||
pointer-events: none;
|
||||
}
|
||||
.content {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
/* Removido padding-top e padding-bottom para evitar recuo duplo com as margens do PDF */
|
||||
padding-left: ${pxToMm(config.timbradoMarginLeft)};
|
||||
padding-right: ${pxToMm(config.timbradoMarginRight)};
|
||||
overflow-wrap: break-word;
|
||||
word-break: break-word;
|
||||
/* Permite múltiplas páginas e evita corte de conteúdo */
|
||||
break-inside: auto;
|
||||
page-break-inside: auto;
|
||||
}
|
||||
.content p {
|
||||
text-indent: ${config.firstLineIndent || '0mm'};
|
||||
}
|
||||
/* Corrige recuo exagerado apenas na primeira linha do primeiro parágrafo da primeira página */
|
||||
.content p:first-child {
|
||||
text-indent: 0mm !important;
|
||||
}
|
||||
/* Corrige recuo exagerado apenas na última linha do último parágrafo da última página */
|
||||
.content p:last-child {
|
||||
margin-bottom: 0 !important;
|
||||
padding-bottom: 0 !important;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
${timbradoUrl ? '<div class="timbrado-bg"></div>' : ''}
|
||||
<div class="content">
|
||||
${cleanContent}
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
}
|
||||
|
||||
// Gera PDF a partir do HTML, depois sobrepõe o timbrado em cada página
|
||||
async gerarPDF(conteudo: string) {
|
||||
try {
|
||||
const config = await this.getConfiguracao();
|
||||
// Usa templatePadrao se não houver conteúdo
|
||||
const html = this.gerarHTML(conteudo || config.templatePadrao, config);
|
||||
const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox'] });
|
||||
const page = await browser.newPage();
|
||||
await page.setContent(html, {
|
||||
waitUntil: ['networkidle0', 'load'],
|
||||
timeout: 30000
|
||||
});
|
||||
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,
|
||||
preferCSSPageSize: true
|
||||
});
|
||||
await browser.close();
|
||||
|
||||
// Se não houver timbrado, retorna direto
|
||||
if (!config.timbradoUrl) {
|
||||
return Buffer.from(pdfBuffer);
|
||||
}
|
||||
|
||||
// Caminho absoluto do PDF de timbrado
|
||||
const timbradoPath = config.timbradoUrl.startsWith('/uploads')
|
||||
? path.join(process.cwd(), 'public', config.timbradoUrl)
|
||||
: path.join(process.cwd(), 'public', 'uploads', path.basename(config.timbradoUrl));
|
||||
let timbradoBytes: Buffer;
|
||||
try {
|
||||
timbradoBytes = await fs.readFile(timbradoPath);
|
||||
} catch (e) {
|
||||
console.error('Timbrado não encontrado:', timbradoPath);
|
||||
return Buffer.from(pdfBuffer);
|
||||
}
|
||||
|
||||
// Mescla cada página do PDF gerado com o timbrado
|
||||
const pdfDoc = await PDFDocument.load(pdfBuffer);
|
||||
const timbradoDoc = await PDFDocument.load(timbradoBytes);
|
||||
const timbradoPage = timbradoDoc.getPage(0);
|
||||
const [timbradoEmbed] = await pdfDoc.embedPages([timbradoPage]);
|
||||
const pageCount = pdfDoc.getPageCount();
|
||||
for (let i = 0; i < pageCount; i++) {
|
||||
const page = pdfDoc.getPage(i);
|
||||
page.drawPage(timbradoEmbed, { x: 0, y: 0, width: page.getWidth(), height: page.getHeight() });
|
||||
}
|
||||
// Remove última página se estiver vazia (sem conteúdo visível)
|
||||
if (pdfDoc.getPageCount() > 1) {
|
||||
const lastPage = pdfDoc.getPage(pdfDoc.getPageCount() - 1);
|
||||
const textContent = lastPage.getTextContent ? await lastPage.getTextContent() : null;
|
||||
// pdf-lib não tem getTextContent, então alternativa: verifica se altura do conteúdo é mínima
|
||||
if (lastPage.getHeight && lastPage.getWidth && lastPage.getHeight() > 0 && lastPage.getWidth() > 0) {
|
||||
// Heurística: verifica se a página tem apenas o timbrado (sem outros objetos)
|
||||
if (lastPage.node.Contents().size() === 0) {
|
||||
pdfDoc.removePage(pdfDoc.getPageCount() - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
const mergedPdf = await pdfDoc.save();
|
||||
return Buffer.from(mergedPdf);
|
||||
} catch (error) {
|
||||
console.error('Erro ao gerar PDF:', error);
|
||||
throw new Error('Falha ao gerar PDF');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -197,18 +197,19 @@ export class PdfService {
|
||||
const page = pdfDoc.getPage(i);
|
||||
page.drawPage(timbradoEmbed, { x: 0, y: 0, width: page.getWidth(), height: page.getHeight() });
|
||||
}
|
||||
// Remove última página se estiver vazia (sem conteúdo visível)
|
||||
// Remove última página se ela for vazia (heurística: largura e altura padrão, nenhum objeto além do fundo)
|
||||
if (pdfDoc.getPageCount() > 1) {
|
||||
const lastPage = pdfDoc.getPage(pdfDoc.getPageCount() - 1);
|
||||
const textContent = lastPage.getTextContent ? await lastPage.getTextContent() : null;
|
||||
// pdf-lib não tem getTextContent, então alternativa: verifica se altura do conteúdo é mínima
|
||||
if (lastPage.getHeight && lastPage.getWidth && lastPage.getHeight() > 0 && lastPage.getWidth() > 0) {
|
||||
// Heurística: verifica se a página tem apenas o timbrado (sem outros objetos)
|
||||
if (lastPage.node.Contents().size() === 0) {
|
||||
// Heurística: se a última página não tem annotations nem xObjects além do fundo, é vazia
|
||||
const annots = lastPage.node.Annots();
|
||||
const xObjects = lastPage.node.Resources().XObject();
|
||||
const hasAnnots = annots && annots.size && annots.size() > 0;
|
||||
const hasXObjects = xObjects && xObjects.size && xObjects.size() > 0;
|
||||
// Se não tem anotações nem xObjects, remove
|
||||
if (!hasAnnots && !hasXObjects) {
|
||||
pdfDoc.removePage(pdfDoc.getPageCount() - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
const mergedPdf = await pdfDoc.save();
|
||||
return Buffer.from(mergedPdf);
|
||||
} catch (error) {
|
||||
|
||||
Reference in new issue
Block a user