368 lines
9.8 KiB
TypeScript
368 lines
9.8 KiB
TypeScript
import fs from "fs/promises";
|
|
import path from "path";
|
|
|
|
import { PDFDocument, rgb, StandardFonts } from "pdf-lib";
|
|
import puppeteer from "puppeteer";
|
|
|
|
import { prisma } from "../prismaClient";
|
|
|
|
/**
|
|
* 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(conteudo: string, escritorio: any) {
|
|
try {
|
|
// 1. Buscar configuração do template
|
|
const config = await prisma.configuracaoDocumento.findFirst({
|
|
orderBy: { criadoEm: "desc" },
|
|
});
|
|
|
|
// 2. Gerar PDF do conteúdo
|
|
const browser = await puppeteer.launch({
|
|
headless: "new",
|
|
args: ["--no-sandbox"],
|
|
});
|
|
|
|
const page = await browser.newPage();
|
|
|
|
// Usar template padrão ou fallback para o template básico
|
|
const template =
|
|
config?.templatePadrao ||
|
|
`
|
|
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<link href="https://fonts.googleapis.com/css2?family=Fira+Sans:wght@400;500;700&display=swap" rel="stylesheet">
|
|
<style>
|
|
body {
|
|
font-family: 'Fira Sans', Arial, sans-serif;
|
|
font-size: 11pt;
|
|
line-height: 1.3;
|
|
margin: 0;
|
|
padding: 0;
|
|
}
|
|
|
|
.content {
|
|
margin: 0;
|
|
padding: 0;
|
|
min-height: calc(100vh - 58mm);
|
|
position: relative;
|
|
}
|
|
|
|
p { margin: 0.7em 0; }
|
|
h1, h2, h3 { margin: 0.8em 0; }
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div class="content">
|
|
${conteudo}
|
|
</div>
|
|
</body>
|
|
</html>
|
|
`;
|
|
|
|
// Processar o template substituindo variáveis
|
|
const templateProcessado = template.replace(
|
|
/\{\{(.+?)\}\}/g,
|
|
(match, key) => {
|
|
return escritorio[key.trim()] || match;
|
|
},
|
|
);
|
|
|
|
await page.setContent(templateProcessado);
|
|
|
|
const margens = config?.margensTemplate || {
|
|
top: "35mm",
|
|
bottom: "29mm",
|
|
left: "25mm",
|
|
right: "25mm",
|
|
};
|
|
|
|
const contentPdfBuffer = await page.pdf({
|
|
format: "A4",
|
|
margin: margens,
|
|
displayHeaderFooter: false,
|
|
printBackground: true,
|
|
});
|
|
|
|
await browser.close();
|
|
|
|
// 2. Carregar os PDFs
|
|
const templatePath = path.join(
|
|
process.cwd(),
|
|
"public",
|
|
"uploads",
|
|
"Timbrado_2025.pdf",
|
|
);
|
|
const templateBytes = await fs.readFile(templatePath);
|
|
|
|
const templateDoc = await PDFDocument.load(templateBytes);
|
|
const contentDoc = await PDFDocument.load(contentPdfBuffer);
|
|
|
|
// 3. Criar documento final
|
|
const pdfDoc = await PDFDocument.create();
|
|
|
|
// 4. Copiar template e conteúdo
|
|
const [templatePage] = await templateDoc.copyPages(templateDoc, [0]);
|
|
const contentPages = await contentDoc.getPages();
|
|
|
|
// 5. Para cada página do conteúdo
|
|
for (let i = 0; i < contentPages.length; i++) {
|
|
// Primeiro: adicionar template
|
|
const page = await pdfDoc.embedPage(templatePage);
|
|
const contentPage = await pdfDoc.embedPage(contentPages[i]);
|
|
|
|
// Segundo: criar nova página
|
|
const newPage = pdfDoc.addPage([page.width, page.height]);
|
|
|
|
// Terceiro: desenhar template e conteúdo
|
|
newPage.drawPage(page);
|
|
newPage.drawPage(contentPage);
|
|
}
|
|
|
|
// 6. Gerar PDF final
|
|
const pdfBytes = await pdfDoc.save();
|
|
return Buffer.from(pdfBytes);
|
|
} catch (error) {
|
|
console.error("Erro ao gerar PDF:", error);
|
|
throw new Error("Falha ao gerar PDF");
|
|
}
|
|
}
|
|
}
|