backend: fix PDFService.ts
This commit is contained in:
1 parent
db7446f19a
commit
8f6b708d51
4 files changed
+178
-953
No files matched your search
@@ -1,47 +1,53 @@
|
||||
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 {
|
||||
// Buscar configuração ou usar valores padrão
|
||||
const config = await prisma.configuracaoDocumento.findFirst({
|
||||
orderBy: { criadoEm: 'desc' },
|
||||
select: {
|
||||
id: true,
|
||||
headerImageUrl: true,
|
||||
footerImageUrl: true,
|
||||
logoUrl: true,
|
||||
timbradoUrl: true,
|
||||
timbradoMarginTop: true,
|
||||
timbradoMarginBottom: true,
|
||||
timbradoMarginLeft: true,
|
||||
timbradoMarginRight: true,
|
||||
templatePadrao: true,
|
||||
margensTemplate: true,
|
||||
criadoEm: true
|
||||
}
|
||||
});
|
||||
|
||||
console.log('Configuração encontrada:', config); // Debug
|
||||
|
||||
// Retornar configuração padrão se não existir
|
||||
// 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 {
|
||||
cabecalhoHtml: config?.cabecalhoHtml || `
|
||||
<div style="text-align: center; padding: 20px;">
|
||||
<h2 style="margin:0;font-size:14pt">{{escritorio.nome}}</h2>
|
||||
</div>
|
||||
`,
|
||||
rodapeHtml: config?.rodapeHtml || `
|
||||
<div style="text-align: center; font-size: 10pt;">
|
||||
{{escritorio.endereco}}<br>
|
||||
Tel: {{escritorio.telefone}} | Email: {{escritorio.email}}
|
||||
</div>
|
||||
`,
|
||||
logoUrl: config?.logoUrl || '',
|
||||
timbradoUrl: config?.timbradoUrl || '',
|
||||
timbradoMarginTop: config?.timbradoMarginTop || 100,
|
||||
timbradoMarginBottom: config?.timbradoMarginBottom || 50,
|
||||
timbradoMarginLeft: config?.timbradoMarginLeft || 50,
|
||||
timbradoMarginRight: config?.timbradoMarginRight || 50
|
||||
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);
|
||||
@@ -49,13 +55,19 @@ export class PdfService {
|
||||
}
|
||||
}
|
||||
|
||||
// Gera HTML com timbrado e margens
|
||||
private gerarHTML(content: string, config: any) {
|
||||
const timbradoUrl = config.timbradoUrl
|
||||
? `${process.env.BACKEND_URL || 'http://localhost:5000'}${config.timbradoUrl}`
|
||||
// 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}`
|
||||
: '';
|
||||
|
||||
console.log('Gerando PDF com timbrado:', timbradoUrl);
|
||||
|
||||
// Adiciona log para debug
|
||||
if (timbradoUrl) {
|
||||
console.log('[PDF] Timbrado inserido no HTML:', timbradoUrl);
|
||||
}
|
||||
return `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
@@ -63,91 +75,162 @@ export class PdfService {
|
||||
<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: 0;
|
||||
@page {
|
||||
margin-top: ${pxToMm(config.timbradoMarginTop)};
|
||||
margin-bottom: ${pxToMm(config.timbradoMarginBottom)};
|
||||
margin-left: ${pxToMm(config.timbradoMarginLeft)};
|
||||
margin-right: ${pxToMm(config.timbradoMarginRight)};
|
||||
size: A4;
|
||||
}
|
||||
|
||||
body {
|
||||
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 */
|
||||
}
|
||||
|
||||
.page {
|
||||
position: relative;
|
||||
width: 21cm;
|
||||
min-height: 29.7cm;
|
||||
padding: ${config.timbradoMarginTop || 100}px ${config.timbradoMarginRight || 50}px ${config.timbradoMarginBottom || 50}px ${config.timbradoMarginLeft || 50}px;
|
||||
background: ${timbradoUrl ? `url('${timbradoUrl}')` : 'none'};
|
||||
background-size: cover;
|
||||
background-position: center;
|
||||
background-repeat: no-repeat;
|
||||
box-sizing: border-box;
|
||||
.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>
|
||||
<div class="page">
|
||||
<div class="content">
|
||||
${content}
|
||||
</div>
|
||||
${timbradoUrl ? '<div class="timbrado-bg"></div>' : ''}
|
||||
<div class="content">
|
||||
${cleanContent}
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
}
|
||||
|
||||
async gerarPDF(conteudo: string, escritorio: any) {
|
||||
// Gera PDF a partir do HTML, depois sobrepõe o timbrado em cada página
|
||||
async gerarPDF(conteudo: string) {
|
||||
try {
|
||||
const config = await prisma.configuracaoDocumento.findFirst({
|
||||
orderBy: { criadoEm: 'desc' }
|
||||
});
|
||||
|
||||
console.log('Configuração do PDF:', config);
|
||||
|
||||
const html = this.gerarHTML(conteudo, config);
|
||||
|
||||
const browser = await puppeteer.launch({
|
||||
headless: 'new',
|
||||
args: ['--no-sandbox']
|
||||
});
|
||||
|
||||
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.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
|
||||
});
|
||||
|
||||
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);
|
||||
|
||||
// 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() });
|
||||
}
|
||||
// Após mesclar o timbrado
|
||||
const pageCountBefore = pdfDoc.getPageCount();
|
||||
if (pageCountBefore > 1) {
|
||||
// Heurística aprimorada: remove a última página apenas se estiver realmente vazia (sem texto, imagens ou gráficos)
|
||||
const lastPage = pdfDoc.getPage(pageCountBefore - 1);
|
||||
let isBlank = true;
|
||||
// Verifica se há texto
|
||||
const annotations = lastPage.node.Annots;
|
||||
if (annotations && annotations.length > 0) {
|
||||
isBlank = false;
|
||||
}
|
||||
// Verifica se há objetos gráficos (imagens, paths, etc.)
|
||||
if (isBlank && typeof lastPage.node?.Resources === 'function') {
|
||||
const resourcesDict = lastPage.node.Resources();
|
||||
if (resourcesDict && typeof resourcesDict === 'object') {
|
||||
// Corrige: usa PDFName para acessar o XObject
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const { PDFName } = require('pdf-lib');
|
||||
const xObject = resourcesDict.get(PDFName.of('XObject'));
|
||||
if (xObject && typeof xObject === 'object' && Object.keys(xObject).length > 0) {
|
||||
isBlank = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Só remove se realmente não houver nada
|
||||
if (isBlank) {
|
||||
pdfDoc.removePage(pageCountBefore - 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');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user