294 lines
7.5 KiB
TypeScript
294 lines
7.5 KiB
TypeScript
import puppeteer from 'puppeteer';
|
|
import { prisma } from '../prismaClient';
|
|
import { PDFDocument, rgb, StandardFonts } from 'pdf-lib';
|
|
import fs from 'fs/promises';
|
|
import path from 'path';
|
|
|
|
/**
|
|
* Serviço para geração e manipulação de arquivos PDF
|
|
*/
|
|
export class PdfService {
|
|
/**
|
|
* Cria um documento PDF básico
|
|
* @returns Documento PDF
|
|
*/
|
|
async criarDocumento() {
|
|
return await PDFDocument.create();
|
|
}
|
|
|
|
/**
|
|
* Carrega um documento PDF existente
|
|
* @param pdfBytes - Bytes do PDF
|
|
* @returns Documento PDF
|
|
*/
|
|
async carregarDocumento(pdfBytes: Uint8Array) {
|
|
return await PDFDocument.load(pdfBytes);
|
|
}
|
|
|
|
/**
|
|
* Adiciona uma página ao documento
|
|
* @param doc - Documento PDF
|
|
* @param tamanho - Tamanho da página (padrão: A4)
|
|
* @returns Página adicionada
|
|
*/
|
|
adicionarPagina(doc: any, tamanho = [595.28, 841.89]) {
|
|
return doc.addPage(tamanho);
|
|
}
|
|
|
|
/**
|
|
* Salva o documento como buffer
|
|
* @param doc - Documento PDF
|
|
* @returns Buffer do PDF
|
|
*/
|
|
async salvarComoBuffer(doc: any): Promise<Buffer> {
|
|
const pdfBytes = await doc.save();
|
|
return Buffer.from(pdfBytes);
|
|
}
|
|
|
|
/**
|
|
* Carrega uma fonte padrão
|
|
* @param doc - Documento PDF
|
|
* @param fonte - Nome da fonte padrão
|
|
* @returns Fonte carregada
|
|
*/
|
|
async carregarFonte(doc: any, fonte: StandardFonts) {
|
|
return await doc.embedFont(fonte);
|
|
}
|
|
|
|
/**
|
|
* Desenha texto em uma página
|
|
* @param pagina - Página do PDF
|
|
* @param texto - Texto a ser desenhado
|
|
* @param x - Posição X
|
|
* @param y - Posição Y
|
|
* @param fonte - Fonte a ser usada
|
|
* @param tamanho - Tamanho da fonte
|
|
* @param cor - Cor do texto (padrão: preto)
|
|
*/
|
|
desenharTexto(
|
|
pagina: any,
|
|
texto: string,
|
|
x: number,
|
|
y: number,
|
|
fonte: any,
|
|
tamanho: number,
|
|
cor = rgb(0, 0, 0)
|
|
) {
|
|
pagina.drawText(texto, {
|
|
x,
|
|
y,
|
|
font: fonte,
|
|
size: tamanho,
|
|
color: cor,
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Cria um cabeçalho para o documento
|
|
* @param pagina - Página do PDF
|
|
* @param titulo - Título do cabeçalho
|
|
* @param fonte - Fonte a ser usada
|
|
* @param margemSuperior - Margem superior
|
|
* @param margem - Margem lateral
|
|
* @returns Posição Y após o cabeçalho
|
|
*/
|
|
criarCabecalho(
|
|
pagina: any,
|
|
titulo: string,
|
|
fonte: any,
|
|
margemSuperior: number,
|
|
margem: number
|
|
): number {
|
|
const yPos = pagina.getHeight() - margemSuperior;
|
|
|
|
this.desenharTexto(
|
|
pagina,
|
|
titulo,
|
|
margem,
|
|
yPos,
|
|
fonte,
|
|
18,
|
|
rgb(0, 0, 0.7)
|
|
);
|
|
|
|
// Linha separadora
|
|
pagina.drawLine({
|
|
start: { x: margem, y: yPos - 10 },
|
|
end: { x: pagina.getWidth() - margem, y: yPos - 10 },
|
|
thickness: 1,
|
|
color: rgb(0, 0, 0.5),
|
|
});
|
|
|
|
return yPos - 30; // Retorna a posição Y após o cabeçalho
|
|
}
|
|
|
|
/**
|
|
* Cria um rodapé para o documento
|
|
* @param pagina - Página do PDF
|
|
* @param texto - Texto do rodapé
|
|
* @param fonte - Fonte a ser usada
|
|
* @param margem - Margem
|
|
*/
|
|
criarRodape(pagina: any, texto: string, fonte: any, margem: number) {
|
|
const yPos = margem / 2;
|
|
|
|
this.desenharTexto(
|
|
pagina,
|
|
texto,
|
|
margem,
|
|
yPos,
|
|
fonte,
|
|
8,
|
|
rgb(0.5, 0.5, 0.5)
|
|
);
|
|
}
|
|
|
|
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,
|
|
criadoEm: true
|
|
}
|
|
});
|
|
|
|
console.log('Configuração encontrada:', config); // Debug
|
|
|
|
// Retornar configuração padrão se não existir
|
|
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
|
|
};
|
|
} catch (error) {
|
|
console.error('Erro ao buscar configuração:', error);
|
|
throw new Error('Falha ao buscar configuração');
|
|
}
|
|
}
|
|
|
|
private gerarHTML(content: string, config: any) {
|
|
const timbradoUrl = config.timbradoUrl
|
|
? `${process.env.BACKEND_URL || 'http://localhost:5000'}${config.timbradoUrl}`
|
|
: '';
|
|
|
|
console.log('Gerando PDF com timbrado:', 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: 0;
|
|
size: A4;
|
|
}
|
|
|
|
body {
|
|
margin: 0;
|
|
padding: 0;
|
|
font-family: 'Fira Sans', Arial, sans-serif;
|
|
font-size: 11pt;
|
|
line-height: 1.5;
|
|
position: relative;
|
|
min-height: 100vh;
|
|
}
|
|
|
|
.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;
|
|
}
|
|
|
|
.content {
|
|
position: relative;
|
|
z-index: 1;
|
|
}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div class="page">
|
|
<div class="content">
|
|
${content}
|
|
</div>
|
|
</div>
|
|
</body>
|
|
</html>
|
|
`;
|
|
}
|
|
|
|
async gerarPDF(html: string): Promise<Buffer> {
|
|
try {
|
|
console.log('Iniciando geração de PDF com Firefox...');
|
|
|
|
const browser = await puppeteer.launch({
|
|
product: 'firefox',
|
|
headless: true,
|
|
args: ['--no-sandbox'],
|
|
});
|
|
|
|
console.log('Firefox iniciado com sucesso');
|
|
|
|
const page = await browser.newPage();
|
|
await page.setDefaultTimeout(30000);
|
|
|
|
console.log('Configurando conteúdo HTML...');
|
|
await page.setContent(html, {
|
|
waitUntil: 'networkidle0',
|
|
timeout: 30000
|
|
});
|
|
|
|
console.log('Gerando PDF...');
|
|
const pdf = await page.pdf({
|
|
format: 'A4',
|
|
printBackground: true,
|
|
margin: {
|
|
top: '20mm',
|
|
right: '20mm',
|
|
bottom: '20mm',
|
|
left: '20mm'
|
|
}
|
|
});
|
|
|
|
await browser.close();
|
|
console.log('PDF gerado com sucesso');
|
|
|
|
return pdf;
|
|
} catch (error) {
|
|
console.error('Erro detalhado ao gerar PDF:', error);
|
|
throw new Error('Falha ao gerar PDF');
|
|
}
|
|
}
|
|
}
|