232 lines
8.3 KiB
TypeScript
232 lines
8.3 KiB
TypeScript
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);
|
|
}
|
|
|
|
// Remove página vazia do final ANTES de mesclar o timbrado
|
|
let pdfDoc = await PDFDocument.load(pdfBuffer);
|
|
let pageCountBefore = pdfDoc.getPageCount();
|
|
if (pageCountBefore > 1) {
|
|
const lastPage = pdfDoc.getPage(pageCountBefore - 1);
|
|
const contentStreams = (lastPage as any).node.Contents?.();
|
|
let isBlank = false;
|
|
|
|
if (!contentStreams) {
|
|
isBlank = true;
|
|
} else if (Array.isArray(contentStreams)) {
|
|
isBlank = contentStreams.every(
|
|
(stream: any) =>
|
|
!stream.contents ||
|
|
(typeof stream.contents.length === 'number' && stream.contents.length < 5)
|
|
);
|
|
} else if (contentStreams.contents && typeof contentStreams.contents.length === 'number') {
|
|
isBlank = contentStreams.contents.length < 5;
|
|
}
|
|
|
|
if (isBlank) {
|
|
pdfDoc.removePage(pageCountBefore - 1);
|
|
}
|
|
}
|
|
|
|
// Agora sim, mescle o timbrado nas páginas restantes
|
|
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() });
|
|
}
|
|
|
|
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');
|
|
}
|
|
}
|
|
} |