Compare commits

...
92 Commits
Author SHA1 Message Date
rodrigo 8488bd7b84 tenta fix pdfservice.js 2025-04-22 16:37:51 -03:00
rodrigo 00a9fb9557 tenta fix pdfservice.js 2025-04-22 16:35:46 -03:00
rodrigo 0908378ca0 tenta fix pdfservice.js 2025-04-22 16:31:56 -03:00
rodrigo 46f538332e tenta fix pdfservice.js 2025-04-22 16:18:53 -03:00
rodrigo 494ad6ef9e tenta fix pdfservice.js 2025-04-22 16:08:41 -03:00
rodrigo 0a48bb414a tenta fix pdfservice.js 2025-04-22 16:04:34 -03:00
rodrigo 06f2d473e3 tenta fix pdfservice.js 2025-04-22 15:51:55 -03:00
rodrigo 5698266d3e tenta fix pdfservice.js 2025-04-22 15:29:53 -03:00
rodrigo 41d3963d67 tenta fix pdfservice.js 2025-04-22 15:24:39 -03:00
rodrigo 9b2e51732f tenta fix pdfservice.js 2025-04-22 15:22:23 -03:00
rodrigo 43cc832274 tenta fix pdfservice.js 2025-04-22 15:19:48 -03:00
rodrigo 4a189f82b2 tenta fix pdfservice.js 2025-04-22 15:16:40 -03:00
rodrigo f1f1ee4826 tenta fix pdfservice.js 2025-04-22 15:13:24 -03:00
rodrigo 705ef97ff8 tenta fix pdfservice.js 2025-04-22 15:09:42 -03:00
rodrigo 5b25414b9c tenta fix pdfservice.js 2025-04-22 15:06:49 -03:00
rodrigo e753ec8718 tenta fix pdfservice.js 2025-04-22 15:02:16 -03:00
rodrigo e208346614 tenta fix pdfservice.js 2025-04-22 15:00:47 -03:00
rodrigo 854531bce0 tenta fix pdfservice.js 2025-04-22 14:59:24 -03:00
rodrigo 597236c525 tenta fix pdfservice.js 2025-04-22 14:49:30 -03:00
rodrigo 6fdfc99e7d tenta fix pdfservice.js 2025-04-22 14:44:00 -03:00
rodrigo 045124be2f tenta fix pdfservice.js 2025-04-22 14:25:13 -03:00
rodrigo 8c3cd7a3bf tenta fix pdfservice.js 2025-04-22 12:17:20 -03:00
rodrigo 566ef2e123 tenta fix pdfservice.js 2025-04-22 12:14:27 -03:00
rodrigo 49dba7c9be tenta fix pdfservice.js 2025-04-22 12:06:42 -03:00
rodrigo 3529bffbbb tenta fix pdfservice.js 2025-04-22 12:04:19 -03:00
rodrigo db0c011b8b tenta fix pdfservice.js 2025-04-22 12:02:12 -03:00
rodrigo 19f0187227 tenta fix pdfservice.js 2025-04-22 11:57:14 -03:00
rodrigo 20b2f0e3c9 tenta fix pdfservice.js 2025-04-22 11:33:45 -03:00
rodrigo bbff8eb317 tenta fix pdfservice.js 2025-04-22 11:25:45 -03:00
rodrigo 06165db8bb tenta fix pdfservice.js 2025-04-22 11:19:59 -03:00
rodrigo 3966728ad4 tenta fix pdfservice.js 2025-04-22 11:14:37 -03:00
rodrigo 4708b9ec82 tenta fix pdfservice.js 2025-04-22 11:05:46 -03:00
rodrigo 1214171946 tenta fix pdfservice.js 2025-04-22 10:59:26 -03:00
rodrigo ce795cba58 tenta fix pdfservice.js 2025-04-22 10:54:57 -03:00
rodrigo 942222df6a tenta fix pdfservice.js 2025-04-22 10:53:11 -03:00
rodrigo 7f3313f3f3 tenta fix pdfservice.js 2025-04-22 10:50:44 -03:00
rodrigo a208caec55 tenta fix pdfservice.js 2025-04-22 10:47:12 -03:00
rodrigo e21dea582c tenta fix pdfservice.js 2025-04-22 10:44:51 -03:00
rodrigo c485960759 tenta fix pdfservice.js 2025-04-22 10:42:13 -03:00
rodrigo 79db5cc065 tenta fix pdfservice.js 2025-04-22 10:25:03 -03:00
rodrigo 92239d0a99 tenta fix pdfservice.js 2025-04-22 10:21:45 -03:00
rodrigo fefc6ce434 tenta fix pdfservice.js 2025-04-22 10:18:45 -03:00
rodrigo ac2891ce0d tenta fix pdfservice.js 2025-04-22 10:16:47 -03:00
rodrigo 07b677be29 tenta fix pdfservice.js 2025-04-22 10:14:11 -03:00
rodrigo bd70c10047 tenta fix pdfservice.js 2025-04-22 10:09:39 -03:00
rodrigo 85977d7229 tenta fix pdfservice.js 2025-04-22 10:04:59 -03:00
rodrigo 3406723bd4 tenta fix pdfservice.js 2025-04-22 10:01:02 -03:00
rodrigo cb47df6e88 tenta fix pdfservice.js 2025-04-22 09:56:28 -03:00
rodrigo 0121f67c65 tenta fix pdfservice.js 2025-04-22 09:51:56 -03:00
rodrigo a2bff3baeb tenta fix pdfservice.js 2025-04-22 09:46:30 -03:00
rodrigo defd9b33f5 tenta fix pdfservice.js 2025-04-21 23:11:33 -03:00
rodrigo 8abf8791be tenta fix pdfservice.js 2025-04-21 23:07:18 -03:00
rodrigo 5798152f7b tenta fix pdfservice.js 2025-04-21 23:05:41 -03:00
rodrigo 4726ce1dfa tenta fix pdfservice.js 2025-04-21 23:01:05 -03:00
rodrigo 00a9e698c6 tenta fix pdfservice.js 2025-04-21 22:57:55 -03:00
rodrigo bb5c9e25e2 tenta fix pdfservice.js 2025-04-21 22:50:08 -03:00
rodrigo a946f86cae tenta fix pdfservice.js 2025-04-21 22:46:09 -03:00
rodrigo 7656ff9807 tenta fix pdfservice.js 2025-04-21 22:42:44 -03:00
rodrigo ad3130a160 tenta fix pdfservice.js 2025-04-21 22:38:21 -03:00
rodrigo eeeae75919 tenta fix pdfservice.js 2025-04-21 22:08:29 -03:00
rodrigo 287ed34abf tenta fix pdfservice.js 2025-04-21 22:04:31 -03:00
rodrigo bd67cf49cc tenta fix pdfservice.js 2025-04-21 22:00:48 -03:00
rodrigo 3d044a962a tenta fix pdfservice.js 2025-04-21 21:58:18 -03:00
rodrigo 2a49dab8d5 tenta fix pdfservice.js 2025-04-21 21:51:48 -03:00
rodrigo 17078adc45 tenta fix pdfservice.js 2025-04-21 21:48:31 -03:00
rodrigo bf277416ff tenta fix pdfservice.js 2025-04-21 21:27:07 -03:00
rodrigo 5705978424 tenta fix pdfservice.js 2025-04-21 21:23:43 -03:00
rodrigo b0b7fba0f6 tenta fix pdfservice.js 2025-04-21 21:12:26 -03:00
rodrigo 0a651f94c0 tenta fix pdfservice.js 2025-04-21 21:09:46 -03:00
rodrigo 8cf2c23774 tenta fix pdfservice.js 2025-04-21 21:07:06 -03:00
rodrigo 2475bc6797 tenta fix pdfservice.js 2025-04-21 21:04:27 -03:00
rodrigo 570f3408c9 tenta fix pdfservice.js 2025-04-21 21:00:52 -03:00
rodrigo 8d12d45621 tenta fix pdfservice.js 2025-04-21 20:58:54 -03:00
rodrigo 3edd6ed317 tenta fix pdfservice.js 2025-04-21 20:55:41 -03:00
rodrigo fb17405fe9 tenta fix pdfservice.js 2025-04-21 20:47:49 -03:00
rodrigo f0fee9d22e tenta fix pdfservice.js 2025-04-21 20:37:34 -03:00
rodrigo f14f7ac3fd tenta fix pdfservice.js 2025-04-21 20:36:43 -03:00
rodrigo 76fa2c91ab tenta fix pdfservice.js 2025-04-21 20:35:21 -03:00
rodrigo 7e16bc8919 tenta fix pdfservice.js 2025-04-21 20:24:54 -03:00
rodrigo f3ff4f8939 tenta fix pdfservice.js 2025-04-21 20:22:23 -03:00
rodrigo e91294df22 tenta fix pdfservice.js 2025-04-21 20:17:45 -03:00
rodrigo 8a09720030 tenta fix pdfservice.js 2025-04-21 20:15:22 -03:00
rodrigo 3ccccc6792 tenta fix pdfservice.js 2025-04-21 20:06:37 -03:00
rodrigo f310f07987 tenta fix pdfservice.js 2025-04-21 19:52:13 -03:00
rodrigo e179fb33d7 tenta fix pdfservice.js 2025-04-21 19:48:27 -03:00
rodrigo 3a3c64f1b3 tenta fix pdfservice.js 2025-04-21 19:46:16 -03:00
rodrigo 73b571be71 tenta fix pdfservice.js 2025-04-21 19:42:27 -03:00
rodrigo 5786af03d5 tenta fix pdfservice.js 2025-04-21 19:39:03 -03:00
rodrigo 926a2934e4 tenta fix pdfservice.js 2025-04-21 19:36:52 -03:00
rodrigo a202bdc445 tenta fix pdfservice.js 2025-04-21 19:34:25 -03:00
rodrigo 6d487b5834 tenta fix pdfservice.js 2025-04-21 19:31:33 -03:00
rodrigo 4c4591fee5 fix atendimentos.ts
Signed-off-by: Rodrigo Martins <rodrigo.sousa.577@gmail.com>
2025-04-13 18:55:34 -03:00
9 changed files with 1122 additions and 305 deletions

No files matched your search

+10 -3
View File
@@ -1,11 +1,18 @@
FROM node:20-slim FROM node:20-slim
# Configurar Puppeteer para usar o Chromium do sistema
ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true
ENV PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser
# Instalar dependências do sistema # Instalar dependências do sistema
RUN apt-get update && apt-get install -y \ RUN apt-get update && apt-get install -y chromium \
chromium \
libgconf-2-4 \ libgconf-2-4 \
postgresql-client \ postgresql-client \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/* \
&& ln -sf /usr/bin/chromium /usr/bin/chromium-browser
# Verificar a instalação do Chromium
RUN chromium --version
# Criar diretório da aplicação # Criar diretório da aplicação
WORKDIR /usr/src/app WORKDIR /usr/src/app
+13
View File
@@ -0,0 +1,13 @@
version: '3.8'
services:
backend:
build: .
ports:
- "5000:5000"
environment:
- NODE_ENV=production
- CHROME_BIN=/usr/bin/google-chrome-stable
# ... outras variáveis de ambiente existentes ...
volumes:
- .:/usr/src/app
- /usr/src/app/node_modules
+1 -6
View File
@@ -49,6 +49,7 @@
"multer": "^1.4.5-lts.1", "multer": "^1.4.5-lts.1",
"opentimestamps-javascript": "^1.0.1", "opentimestamps-javascript": "^1.0.1",
"pdf-lib": "^1.17.1", "pdf-lib": "^1.17.1",
"pdfkit": "^0.13.0",
"puppeteer": "^24.5.0", "puppeteer": "^24.5.0",
"qrcode": "^1.5.3", "qrcode": "^1.5.3",
"react": "^18.2.0", "react": "^18.2.0",
@@ -111,11 +112,5 @@
"--disable-gpu", "--disable-gpu",
"--window-size=1920x1080" "--window-size=1920x1080"
] ]
},
"puppeteerOptions": {
"browserFetcher": {
"platform": "win32",
"downloadPath": ".cache/puppeteer"
}
} }
} }
+9
View File
@@ -0,0 +1,9 @@
-- Identificar registros com UUID inválido
SELECT id, uuid_column
FROM atendimento
WHERE uuid_column !~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$';
-- Atualizar registros com UUID inválido
UPDATE atendimento
SET uuid_column = gen_random_uuid()
WHERE uuid_column !~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$';
+19 -11
View File
@@ -200,7 +200,7 @@ export const ClienteModal: React.FC<ClienteModalProps> = ({
// Monitorar o valor do CEP para autopreenchimento // Monitorar o valor do CEP para autopreenchimento
const cepValue = watch("cep"); const cepValue = watch("cep");
// Função para buscar dados do CEP - versão com gerenciamento de estados do componente // Função para buscar dados do CEP - versão corrigida
const fetchAddressByCep = useCallback(async (cep: string) => { const fetchAddressByCep = useCallback(async (cep: string) => {
if (!cep || cep.length !== 8) return; if (!cep || cep.length !== 8) return;
@@ -213,7 +213,6 @@ export const ClienteModal: React.FC<ClienteModalProps> = ({
if (response.data && !response.data.erro) { if (response.data && !response.data.erro) {
// Usar estado local para garantir re-renderização imediata // Usar estado local para garantir re-renderização imediata
// Forçar preenchimento dos campos e atualização da interface
const endereco = response.data.logradouro || ""; const endereco = response.data.logradouro || "";
const bairro = response.data.bairro || ""; const bairro = response.data.bairro || "";
const cidade = response.data.localidade || ""; const cidade = response.data.localidade || "";
@@ -225,8 +224,7 @@ export const ClienteModal: React.FC<ClienteModalProps> = ({
setValue("cidade", cidade, { shouldValidate: true }); setValue("cidade", cidade, { shouldValidate: true });
setValue("estado", estado, { shouldValidate: true }); setValue("estado", estado, { shouldValidate: true });
// Garantir re-renderização do componente // Atualizar o estado para re-renderização do componente
// Esta é a parte crucial: forçar o componente a re-renderizar com novo estado
setEnderecoState({ setEnderecoState({
endereco, endereco,
bairro, bairro,
@@ -235,13 +233,23 @@ export const ClienteModal: React.FC<ClienteModalProps> = ({
preenchido: true, preenchido: true,
}); });
// Focar no próximo campo // Focar no próximo campo apenas se o usuário não estiver digitando ativamente
setTimeout(() => { // Esta alteração evita interromper o fluxo natural de preenchimento
const numeroInput = document.querySelector( const activeElement = document.activeElement;
'input[name="numero"]' const isUserTyping =
) as HTMLInputElement; activeElement &&
if (numeroInput) numeroInput.focus(); (activeElement.tagName === 'INPUT' || activeElement.tagName === 'SELECT') &&
}, 100); activeElement !== document.querySelector('input[name="cep"]');
// Só focar no campo número se o usuário não estiver digitando em outro campo
if (!isUserTyping) {
setTimeout(() => {
const numeroInput = document.querySelector(
'input[name="numero"]'
) as HTMLInputElement;
if (numeroInput) numeroInput.focus();
}, 100);
}
} else { } else {
console.error("CEP não encontrado"); console.error("CEP não encontrado");
alert("CEP não encontrado. Por favor, verifique o CEP informado."); alert("CEP não encontrado. Por favor, verifique o CEP informado.");
+77 -2
View File
@@ -55,6 +55,13 @@ const orgaoJulgadorRepository = new OrgaoJulgadorRepository();
const custaProcessualRepository = new CustaProcessualRepository(); const custaProcessualRepository = new CustaProcessualRepository();
const honorarioRepository = new HonorarioRepository(); const honorarioRepository = new HonorarioRepository();
// Atualizar a função isValidUUID para ser mais robusta
const isValidUUID = (uuid: string | null | undefined): boolean => {
if (!uuid) return false;
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
return uuidRegex.test(uuid);
};
// Middleware para extrair usuário do token // Middleware para extrair usuário do token
// Remover este middleware pois já temos o auth.ts // Remover este middleware pois já temos o auth.ts
// const extractUser = (req: any, res: any, next: any) => { ... } // const extractUser = (req: any, res: any, next: any) => { ... }
@@ -1000,9 +1007,9 @@ app.post("/api/atendimentos", authMiddleware, async (req, res) => {
conteudo, conteudo,
cliente: { connect: { id: clienteId } }, cliente: { connect: { id: clienteId } },
usuario: { connect: { id: req.user!.id } }, usuario: { connect: { id: req.user!.id } },
...(processoId && { processo: { connect: { id: processoId } } }), ...(processoId && { processo: { connect: { id: processoId } } }), // Adicionar vírgula aqui
status: 'ATIVO', status: 'ATIVO',
dataAtualizacao: new Date(), dataAtualizacao: new Date()
}, },
include: { include: {
cliente: true, cliente: true,
@@ -1337,6 +1344,74 @@ app.delete("/api/agendamentos/:id", authMiddleware, async (req, res) => {
} }
}); });
// Atualizar a rota de agendamentos
app.get("/api/atendimentos/agendamentos", async (req, res) => {
try {
const { data } = req.query;
if (!data || typeof data !== 'string') {
return res.status(400).json({ error: 'Data inválida' });
}
const dataConsulta = new Date(data);
// Validar se a data é válida
if (isNaN(dataConsulta.getTime())) {
return res.status(400).json({ error: 'Formato de data inválido' });
}
// Definir início e fim do dia
const inicioDia = new Date(dataConsulta.setHours(0, 0, 0, 0));
const fimDia = new Date(dataConsulta.setHours(23, 59, 59, 999));
// Buscar na tabela correta com filtros apropriados
const agendamentos = await prisma.agendamentoAtendimento.findMany({
where: {
data: {
gte: inicioDia,
lte: fimDia
}
},
include: {
cliente: {
select: {
id: true,
nome: true,
cpfCnpj: true,
telefone: true
}
},
usuario: {
select: {
id: true,
nome: true
}
}
},
orderBy: {
data: 'asc'
}
});
// Filtrar apenas agendamentos com UUIDs válidos
const validAgendamentos = agendamentos.filter(agendamento =>
isValidUUID(agendamento.id) &&
isValidUUID(agendamento.clienteId) &&
isValidUUID(agendamento.usuarioId)
);
console.log(`Encontrados ${validAgendamentos.length} agendamentos válidos para ${data}`);
res.json(validAgendamentos);
} catch (error) {
console.error('Erro ao buscar agendamentos:', error);
res.status(500).json({
error: 'Erro ao buscar agendamentos',
details: error instanceof Error ? error.message : 'Erro desconhecido'
});
}
});
// Erro handling middleware // Erro handling middleware
app.use( app.use(
( (
+634
View File
@@ -0,0 +1,634 @@
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,
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
return {
// Valores padrão
cabecalhoHtml: `
<div style="text-align: center; padding: 20px;">
<h2 style="margin:0;font-size:14pt">{{escritorio.nome}}</h2>
</div>
`,
rodapeHtml: `
<div style="text-align: center; font-size: 10pt;">
{{escritorio.endereco}}<br>
Tel: {{escritorio.telefone}} | Email: {{escritorio.email}}
</div>
`,
// Campos que existem no modelo
timbradoUrl: config?.timbradoUrl || '',
timbradoMarginTop: config?.timbradoMarginTop || 100,
timbradoMarginBottom: config?.timbradoMarginBottom || 50,
timbradoMarginLeft: config?.timbradoMarginLeft || 50,
timbradoMarginRight: config?.timbradoMarginRight || 50,
templatePadrao: config?.templatePadrao || null,
margensTemplate: config?.margensTemplate || null
};
} catch (error) {
console.error('Erro ao buscar configuração:', error);
// Retornar configuração padrão para não interromper o fluxo
return {
cabecalhoHtml: `<div style="text-align: center; padding: 20px;"><h2 style="margin:0;font-size:14pt">Documento</h2></div>`,
rodapeHtml: `<div style="text-align: center; font-size: 10pt;">Documento gerado pelo sistema</div>`,
timbradoUrl: '',
timbradoMarginTop: 100,
timbradoMarginBottom: 50,
timbradoMarginLeft: 50,
timbradoMarginRight: 50,
templatePadrao: null,
margensTemplate: null
};
}
}
/**
* Gera um PDF a partir do conteúdo HTML simples (apenas texto) e dados do escritório,
* encaixando o texto sobre o timbrado (PDF de fundo) em todas as páginas.
* Não usa Puppeteer, apenas PDF-LIB.
*/
async gerarPDF(conteudo: string, escritorio: any = {}): Promise<Buffer> {
try {
console.log('Buscando configurações do documento...');
const config = await this.getConfiguracao();
// Verificar se temos um timbrado para usar
const temTimbrado = !!config.timbradoUrl;
let timbradoPath = '';
let timbradoExists = false;
if (temTimbrado) {
if (config.timbradoUrl.startsWith('/uploads')) {
timbradoPath = path.join(process.cwd(), 'public', config.timbradoUrl);
} else {
timbradoPath = path.join(process.cwd(), 'public', 'uploads', path.basename(config.timbradoUrl));
}
try {
await fs.access(timbradoPath);
timbradoExists = true;
} catch (e) {
timbradoExists = false;
}
}
// Margens
const margens = config.margensTemplate || {
top: config.timbradoMarginTop || 100,
left: config.timbradoMarginLeft || 50,
right: config.timbradoMarginRight || 50,
bottom: config.timbradoMarginBottom || 50
};
// Parâmetros de página
const PAGE_WIDTH = 595.28; // A4
const PAGE_HEIGHT = 841.89; // A4
const FONT_SIZE = 12;
const LINE_HEIGHT = FONT_SIZE * 1.5;
const MAX_WIDTH = PAGE_WIDTH - margens.left - margens.right;
// Crie o PDFDocument ANTES de tentar usar pdfDoc para embedFont!
let pdfDoc: PDFDocument = await PDFDocument.create();
// Fonte padrão do pdf-lib: TimesRoman, TimesBold, TimesItalic
const font = await pdfDoc.embedFont('Times-Roman');
const fontBold = await pdfDoc.embedFont('Times-Bold');
const fontItalic = await pdfDoc.embedFont('Times-Italic');
const fontBoldItalic = fontBold;
// Função para decodificar entidades HTML comuns (acentuação, símbolos, º, etc)
function decodeHtmlEntities(str: string): string {
if (!str) return '';
return str
// Acentos minúsculos e maiúsculos
.replace(/&Aacute;/g, 'Á').replace(/&aacute;/g, 'á')
.replace(/&Eacute;/g, 'É').replace(/&eacute;/g, 'é')
.replace(/&Iacute;/g, 'Í').replace(/&iacute;/g, 'í')
.replace(/&Oacute;/g, 'Ó').replace(/&oacute;/g, 'ó')
.replace(/&Uacute;/g, 'Ú').replace(/&uacute;/g, 'ú')
.replace(/&Agrave;/g, 'À').replace(/&agrave;/g, 'à')
.replace(/&Egrave;/g, 'È').replace(/&egrave;/g, 'è')
.replace(/&Igrave;/g, 'Ì').replace(/&igrave;/g, 'ì')
.replace(/&Ograve;/g, 'Ò').replace(/&ograve;/g, 'ò')
.replace(/&Ugrave;/g, 'Ù').replace(/&ugrave;/g, 'ù')
.replace(/&Acirc;/g, 'Â').replace(/&acirc;/g, 'â')
.replace(/&Ecirc;/g, 'Ê').replace(/&ecirc;/g, 'ê')
.replace(/&Icirc;/g, 'Î').replace(/&icirc;/g, 'î')
.replace(/&Ocirc;/g, 'Ô').replace(/&ocirc;/g, 'ô')
.replace(/&Ucirc;/g, 'Û').replace(/&ucirc;/g, 'û')
.replace(/&Atilde;/g, 'Ã').replace(/&atilde;/g, 'ã')
.replace(/&Otilde;/g, 'Õ').replace(/&otilde;/g, 'õ')
.replace(/&Ccedil;/g, 'Ç').replace(/&ccedil;/g, 'ç')
.replace(/&Ntilde;/g, 'Ñ').replace(/&ntilde;/g, 'ñ')
.replace(/&Uuml;/g, 'Ü').replace(/&uuml;/g, 'ü')
// Símbolos comuns
.replace(/&ordm;/gi, 'º')
.replace(/&ordf;/gi, 'ª')
.replace(/&sect;/gi, '§')
.replace(/&deg;/gi, '°')
.replace(/&copy;/gi, '©')
.replace(/&reg;/gi, '®')
.replace(/&para;/gi, '¶')
.replace(/&bull;/gi, '•')
.replace(/&ndash;/gi, '–')
.replace(/&mdash;/gi, '—')
.replace(/&laquo;/gi, '«')
.replace(/&raquo;/gi, '»')
.replace(/&lsquo;/gi, '‘')
.replace(/&rsquo;/gi, '’')
.replace(/&ldquo;/gi, '“')
.replace(/&rdquo;/gi, '”')
.replace(/&euro;/gi, '€')
.replace(/&yen;/gi, '¥')
.replace(/&pound;/gi, '£')
.replace(/&cent;/gi, '¢')
.replace(/&nbsp;/gi, ' ')
.replace(/&amp;/gi, '&')
.replace(/&quot;/gi, '"')
.replace(/&#39;/g, "'")
.replace(/&lt;/gi, '<')
.replace(/&gt;/gi, '>')
// Numéricos
.replace(/&#(\d+);/g, (m, code) => String.fromCharCode(code));
}
// Função para remover todas as tags HTML, exceto as de formatação suportadas
function stripUnsupportedTags(html: string): string {
// Remove todas as tags, exceto <b>, <strong>, <i>, <em>, <u>, <br>, <p>, <span style="text-indent:2em;">, <span style="text-align:center;">
// Remove atributos de <span> exceto text-indent e text-align
return html
// Mantém apenas <span> com text-indent ou text-align:center
.replace(/<span\b(?:(?!text-indent|text-align)[^>])*?>/gi, '')
// Remove atributos de <b>, <strong>, <i>, <em>, <u>, <p>
.replace(/<(b|strong|i|em|u|p)[^>]*>/gi, '<$1>')
// Remove todas as outras tags e atributos
.replace(/<(?!\/?(b|strong|i|em|u|br|p|span)[ >])[^>]+>/gi, '')
// Remove spans sem text-indent ou text-align
.replace(/<span>(.*?)<\/span>/gi, '$1')
// Remove comentários HTML
.replace(/<!--[\s\S]*?-->/g, '');
}
// Função para renderizar texto com formatação inline (negrito, itálico, sublinhado) e controle de quebra de linha e recuo
function renderInlineFormattedParagraph(
page,
text: string,
x: number,
y: number,
font,
fontBold,
fontItalic,
fontBoldItalic,
fontSize: number,
color,
align: string,
maxWidth: number,
indent: boolean,
topMargin: number,
bottomMargin: number,
pageHeight: number
) {
let regex = /(<\/?(b|strong|i|em|u)>)/gi;
let tokens: { text: string, bold: boolean, italic: boolean, underline: boolean }[] = [];
let lastIndex = 0;
let match;
let currentStyle = { bold: false, italic: false, underline: false };
while ((match = regex.exec(text)) !== null) {
if (match.index > lastIndex) {
tokens.push({
text: text.substring(lastIndex, match.index),
bold: currentStyle.bold,
italic: currentStyle.italic,
underline: currentStyle.underline
});
}
if (/^<(b|strong)>$/i.test(match[0])) currentStyle.bold = true;
if (/^<\/(b|strong)>$/i.test(match[0])) currentStyle.bold = false;
if (/^<(i|em)>$/i.test(match[0])) currentStyle.italic = true;
if (/^<\/(i|em)>$/i.test(match[0])) currentStyle.italic = false;
if (/^<u>$/i.test(match[0])) currentStyle.underline = true;
if (/^<\/u>$/i.test(match[0])) currentStyle.underline = false;
lastIndex = regex.lastIndex;
}
if (lastIndex < text.length) {
tokens.push({
text: text.substring(lastIndex),
bold: currentStyle.bold,
italic: currentStyle.italic,
underline: currentStyle.underline
});
}
let words: { text: string, font: any, underline: boolean, bold: boolean, italic: boolean }[] = [];
for (const token of tokens) {
let usedFont = font;
if (token.bold && token.italic) usedFont = fontBoldItalic;
else if (token.bold) usedFont = fontBold;
else if (token.italic) usedFont = fontItalic;
// Corrige: split por espaço, mas preserva espaços como tokens separados
const split = token.text.split(/(\s+)/);
for (const part of split) {
words.push({ text: part, font: usedFont, underline: token.underline, bold: token.bold, italic: token.italic });
}
}
let lines: { tokens: { text: string, font: any, underline: boolean, bold: boolean, italic: boolean }[] }[] = [];
let currentTokens: { text: string, font: any, underline: boolean, bold: boolean, italic: boolean }[] = [];
let currentWidth = 0;
for (const [i, word] of words.entries()) {
const wordWidth = word.font.widthOfTextAtSize(word.text, fontSize);
if (currentWidth + wordWidth > maxWidth && currentTokens.length > 0) {
lines.push({ tokens: currentTokens });
currentTokens = [word];
currentWidth = wordWidth;
} else {
currentTokens.push(word);
currentWidth += wordWidth;
}
}
if (currentTokens.length > 0) {
lines.push({ tokens: currentTokens });
}
// Ajuste: Força alinhamento consistente para todas as linhas do parágrafo
// Se align === 'center', todas as linhas centralizadas
// Se align === 'justify', todas as linhas justificadas (exceto a última ou linhas curtas)
// Se align === 'left' ou outro, todas à esquerda
for (let i = 0; i < lines.length; i++) {
if (y < bottomMargin + fontSize * 1.5) {
return null;
}
let line = lines[i];
let drawX = x;
// Remove espaços no início e fim da linha para não justificar esses espaços
let trimmedTokens = [...line.tokens];
while (trimmedTokens.length && /^\s+$/.test(trimmedTokens[0].text)) trimmedTokens.shift();
while (trimmedTokens.length && /^\s+$/.test(trimmedTokens[trimmedTokens.length - 1].text)) trimmedTokens.pop();
let totalWidth = trimmedTokens.reduce((acc, t) => acc + t.font.widthOfTextAtSize(t.text, fontSize), 0);
// Corrige centralização: centraliza a linha inteira, inclusive se for a única linha do parágrafo
if (align === 'center') {
drawX = x + (maxWidth - totalWidth) / 2;
for (const t of trimmedTokens) {
page.drawText(t.text, {
x: drawX,
y,
size: fontSize,
font: t.font,
color
});
if (t.underline && t.text.trim() !== '') {
const underlineY = y - 1.5;
page.drawLine({
start: { x: drawX, y: underlineY },
end: { x: drawX + t.font.widthOfTextAtSize(t.text, fontSize), y: underlineY },
thickness: 0.75,
color
});
}
drawX += t.font.widthOfTextAtSize(t.text, fontSize);
}
} else if (align === 'justify' && i < lines.length - 1 && trimmedTokens.length > 2) {
// Justify: distribui espaço entre palavras, exceto na última linha ou linhas curtas
const spaces = trimmedTokens.filter(t => /^\s+$/.test(t.text));
const numSpaces = spaces.length;
const lineTextWidth = trimmedTokens.reduce((acc, t) => acc + t.font.widthOfTextAtSize(t.text, fontSize), 0);
const extraSpace = maxWidth - lineTextWidth;
let spaceWidth = 0;
// Só justifica se houver pelo menos 2 espaços e a linha não for muito curta
if (numSpaces > 0 && extraSpace > 0) {
spaceWidth = extraSpace / numSpaces;
}
let localDrawX = x;
for (const t of trimmedTokens) {
page.drawText(t.text, {
x: localDrawX,
y,
size: fontSize,
font: t.font,
color
});
if (t.underline && t.text.trim() !== '') {
const underlineY = y - 1.5;
page.drawLine({
start: { x: localDrawX, y: underlineY },
end: { x: localDrawX + t.font.widthOfTextAtSize(t.text, fontSize), y: underlineY },
thickness: 0.75,
color
});
}
if (/^\s+$/.test(t.text) && spaceWidth > 0) {
localDrawX += t.font.widthOfTextAtSize(t.text, fontSize) + spaceWidth;
} else {
localDrawX += t.font.widthOfTextAtSize(t.text, fontSize);
}
}
} else {
// Alinhamento à esquerda (padrão) ou última linha de parágrafo justificado
for (const t of trimmedTokens) {
page.drawText(t.text, {
x: drawX,
y,
size: fontSize,
font: t.font,
color
});
if (t.underline && t.text.trim() !== '') {
const underlineY = y - 1.5;
page.drawLine({
start: { x: drawX, y: underlineY },
end: { x: drawX + t.font.widthOfTextAtSize(t.text, fontSize), y: underlineY },
thickness: 0.75,
color
});
}
drawX += t.font.widthOfTextAtSize(t.text, fontSize);
}
}
y -= fontSize * 1.5;
}
return y;
}
const texto = decodeHtmlEntities(
stripUnsupportedTags(
this.processarTemplate(conteudo, escritorio)
.replace(/<br\s*\/?>/gi, '\n')
.replace(/<\/p>/gi, '\n\n')
.replace(/<p[^>]*>/gi, '')
.replace(/<span[^>]*text-indent[^>]*>/gi, '§§INDENT§§')
.replace(/<span[^>]*text-align\s*:\s*center[^>]*>/gi, '§§CENTER§§')
.replace(/<\/span>/gi, '')
.replace(/\r\n/g, '\n')
.replace(/\r/g, '\n')
.replace(/\n{3,}/g, '\n\n')
.trim()
)
);
const paragrafos = texto.split(/\n{2,}/).map(p => p.trim()).filter(Boolean);
let timbradoPdf: PDFDocument | null = null;
let timbradoPageCount = 0;
let timbradoPages: any[] = [];
if (timbradoExists) {
const timbradoBytes = await fs.readFile(timbradoPath);
timbradoPdf = await PDFDocument.load(timbradoBytes);
timbradoPageCount = timbradoPdf.getPageCount();
timbradoPages = [];
for (let i = 0; i < timbradoPageCount; i++) {
const [embedded] = await pdfDoc.embedPages([timbradoPdf.getPage(i)]);
timbradoPages.push(embedded);
}
}
let currentPar = 0;
let pageIndex = 0;
while (currentPar < paragrafos.length) {
let page = pdfDoc.addPage([PAGE_WIDTH, PAGE_HEIGHT]);
if (timbradoPages.length > 0) {
const embedded = timbradoPages[pageIndex % timbradoPages.length];
page.drawPage(embedded, {
x: 0,
y: 0,
width: PAGE_WIDTH,
height: PAGE_HEIGHT
});
}
let y = PAGE_HEIGHT - margens.top;
while (currentPar < paragrafos.length) {
let indent = paragrafos[currentPar].startsWith('§§INDENT§§');
let center = paragrafos[currentPar].startsWith('§§CENTER§§');
let align: 'center' | 'justify' | 'left' = center ? 'center' : 'justify';
let text = paragrafos[currentPar].replace(/^§§INDENT§§/, '').replace(/^§§CENTER§§/, '').trim();
// Se o parágrafo for centralizado, força alinhamento center e ignora recuo
if (center) {
indent = false;
align = 'center';
}
text = decodeHtmlEntities(text);
let x = margens.left;
let parWidth = MAX_WIDTH;
let yAfter = renderInlineFormattedParagraph(
page,
text,
x,
y,
font,
fontBold,
fontItalic,
fontBoldItalic,
FONT_SIZE,
rgb(0, 0, 0),
align,
parWidth,
indent,
margens.top,
margens.bottom,
PAGE_HEIGHT
);
if (yAfter === null) {
pageIndex++;
break;
}
y = yAfter - FONT_SIZE * 0.5;
currentPar++;
if (y < margens.bottom + FONT_SIZE * 1.5) break;
}
pageIndex++;
}
const pdfBytes = await pdfDoc.save();
return Buffer.from(pdfBytes);
} catch (error) {
console.error('Erro geral ao gerar PDF:', error);
throw error;
}
}
private processarTemplate(template: string, dados: any): string {
return template.replace(/\{\{([^}]+)\}\}/g, (match, key) => {
const keyParts = key.trim().split('.');
let value = dados;
for (const part of keyParts) {
if (value && typeof value === 'object' && part in value) {
value = value[part];
} else {
value = undefined;
break;
}
}
return value !== undefined ? value : match;
});
}
}
+219
View File
@@ -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');
}
}
}
+140 -283
View File
@@ -1,188 +1,53 @@
import puppeteer from 'puppeteer'; import puppeteer from 'puppeteer';
import { prisma } from '../prismaClient'; import { PDFDocument } from 'pdf-lib';
import { PDFDocument, rgb, StandardFonts } from 'pdf-lib';
import fs from 'fs/promises'; import fs from 'fs/promises';
import path from 'path'; 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';
}
/**
* Serviço para geração e manipulação de arquivos PDF
*/
export class PdfService { export class PdfService {
/** // Busca configuração do documento, usando apenas campos válidos do schema
* 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() { private async getConfiguracao() {
try { try {
// Buscar configuração ou usar valores padrão
const config = await prisma.configuracaoDocumento.findFirst({ const config = await prisma.configuracaoDocumento.findFirst({
orderBy: { criadoEm: 'desc' }, orderBy: { criadoEm: 'desc' },
select: { select: {
id: true, id: true,
headerImageUrl: true,
footerImageUrl: true,
logoUrl: true,
timbradoUrl: true, timbradoUrl: true,
timbradoMarginTop: true, timbradoMarginTop: true,
timbradoMarginBottom: true, timbradoMarginBottom: true,
timbradoMarginLeft: true, timbradoMarginLeft: true,
timbradoMarginRight: true, timbradoMarginRight: true,
templatePadrao: true,
margensTemplate: true,
criadoEm: true criadoEm: true
} }
}); });
// Extrai recuo de primeira linha se existir em margensTemplate
console.log('Configuração encontrada:', config); // Debug let firstLineIndent = '0mm';
if (config?.margensTemplate) {
// Retornar configuração padrão se não existir 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 { 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 || '', timbradoUrl: config?.timbradoUrl || '',
timbradoMarginTop: config?.timbradoMarginTop || 100, timbradoMarginTop: config?.timbradoMarginTop ?? 100,
timbradoMarginBottom: config?.timbradoMarginBottom || 50, timbradoMarginBottom: config?.timbradoMarginBottom ?? 50,
timbradoMarginLeft: config?.timbradoMarginLeft || 50, timbradoMarginLeft: config?.timbradoMarginLeft ?? 50,
timbradoMarginRight: config?.timbradoMarginRight || 50 timbradoMarginRight: config?.timbradoMarginRight ?? 50,
templatePadrao: config?.templatePadrao || '',
firstLineIndent
}; };
} catch (error) { } catch (error) {
console.error('Erro ao buscar configuração:', error); console.error('Erro ao buscar configuração:', error);
@@ -190,13 +55,19 @@ export class PdfService {
} }
} }
// Gera HTML com timbrado e margens
private gerarHTML(content: string, config: any) { private gerarHTML(content: string, config: any) {
const timbradoUrl = config.timbradoUrl // Limpa espaços, quebras de linha e tags vazias do final do conteúdo
? `${process.env.BACKEND_URL || 'http://localhost:5000'}${config.timbradoUrl}` 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
console.log('Gerando PDF com timbrado:', timbradoUrl); if (timbradoUrl) {
console.log('[PDF] Timbrado inserido no HTML:', timbradoUrl);
}
return ` return `
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
@@ -204,157 +75,143 @@ export class PdfService {
<meta charset="UTF-8"> <meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css2?family=Fira+Sans:wght@400;500;600&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Fira+Sans:wght@400;500;600&display=swap" rel="stylesheet">
<style> <style>
@page { @page {
margin: 0; margin-top: ${pxToMm(config.timbradoMarginTop)};
margin-bottom: ${pxToMm(config.timbradoMarginBottom)};
margin-left: ${pxToMm(config.timbradoMarginLeft)};
margin-right: ${pxToMm(config.timbradoMarginRight)};
size: A4; size: A4;
} }
html, body {
body { height: 100%;
margin: 0; margin: 0;
padding: 0; padding: 0;
font-family: 'Fira Sans', Arial, sans-serif; font-family: 'Fira Sans', Arial, sans-serif;
font-size: 11pt; font-size: 11pt;
line-height: 1.5; line-height: 1.5;
background: none;
}
body {
position: relative; position: relative;
min-height: 100vh; min-height: 100vh;
/* Remove background-image do body para evitar problemas no Puppeteer */
} }
.timbrado-bg {
.page { position: fixed;
position: relative; top: 0;
width: 21cm; left: 0;
min-height: 29.7cm; width: 100vw;
padding: ${config.timbradoMarginTop || 100}px ${config.timbradoMarginRight || 50}px ${config.timbradoMarginBottom || 50}px ${config.timbradoMarginLeft || 50}px; height: 100vh;
background: ${timbradoUrl ? `url('${timbradoUrl}')` : 'none'}; z-index: 0;
background-size: cover; ${timbradoUrl ? `background-image: url('${timbradoUrl}'); background-size: cover; background-position: center; background-repeat: no-repeat;` : ''}
background-position: center; pointer-events: none;
background-repeat: no-repeat;
box-sizing: border-box;
} }
.content { .content {
position: relative; position: relative;
z-index: 1; 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> </style>
</head> </head>
<body> <body>
<div class="page"> ${timbradoUrl ? '<div class="timbrado-bg"></div>' : ''}
<div class="content"> <div class="content">
${content} ${cleanContent}
</div>
</div> </div>
</body> </body>
</html> </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 { try {
// 1. Buscar configuração do template const config = await this.getConfiguracao();
const config = await prisma.configuracaoDocumento.findFirst({ // Usa templatePadrao se não houver conteúdo
orderBy: { criadoEm: 'desc' } const html = this.gerarHTML(conteudo || config.templatePadrao, config);
}); const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox'] });
// 2. Gerar PDF do conteúdo
const browser = await puppeteer.launch({
headless: 'new',
args: ['--no-sandbox']
});
const page = await browser.newPage(); const page = await browser.newPage();
await page.setContent(html, {
// Usar template padrão ou fallback para o template básico waitUntil: ['networkidle0', 'load'],
const template = config?.templatePadrao || ` timeout: 30000
<!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;
}); });
const margin = {
await page.setContent(templateProcessado); top: pxToMm(config.timbradoMarginTop),
bottom: pxToMm(config.timbradoMarginBottom),
const margens = config?.margensTemplate || { left: pxToMm(config.timbradoMarginLeft),
top: '35mm', right: pxToMm(config.timbradoMarginRight)
bottom: '29mm',
left: '25mm',
right: '25mm'
}; };
const pdfBuffer = await page.pdf({
const contentPdfBuffer = await page.pdf({
format: 'A4', format: 'A4',
margin: margens, printBackground: true,
displayHeaderFooter: false, margin,
printBackground: true preferCSSPageSize: true
}); });
await browser.close(); await browser.close();
// 2. Carregar os PDFs // Se não houver timbrado, retorna direto
const templatePath = path.join(process.cwd(), 'public', 'uploads', 'Timbrado_2025.pdf'); if (!config.timbradoUrl) {
const templateBytes = await fs.readFile(templatePath); return Buffer.from(pdfBuffer);
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 // Caminho absoluto do PDF de timbrado
const pdfBytes = await pdfDoc.save(); const timbradoPath = config.timbradoUrl.startsWith('/uploads')
return Buffer.from(pdfBytes); ? 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: remove a última página se ela estiver completamente em branco (sem texto)
const lastPage = pdfDoc.getPage(pageCountBefore - 1);
const text = await lastPage.getTextContent?.();
if (!text || (Array.isArray(text.items) && text.items.length === 0)) {
pdfDoc.removePage(pageCountBefore - 1);
}
}
const mergedPdf = await pdfDoc.save();
return Buffer.from(mergedPdf);
} catch (error) { } catch (error) {
console.error('Erro ao gerar PDF:', error); console.error('Erro ao gerar PDF:', error);
throw new Error('Falha ao gerar PDF'); throw new Error('Falha ao gerar PDF');
} }
} }
} }