fix atendimentos.ts
Signed-off-by: Rodrigo Martins <rodrigo.sousa.577@gmail.com>
This commit is contained in:
1 parent
33d9fe8688
commit
0090e03c03
7 files changed
+854
-170
No files matched your search
+10
-3
@@ -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
|
||||||
|
|||||||
@@ -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
@@ -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"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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}$';
|
||||||
@@ -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
|
||||||
|
// Esta alteração evita interromper o fluxo natural de preenchimento
|
||||||
|
const activeElement = document.activeElement;
|
||||||
|
const isUserTyping =
|
||||||
|
activeElement &&
|
||||||
|
(activeElement.tagName === 'INPUT' || activeElement.tagName === 'SELECT') &&
|
||||||
|
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(() => {
|
setTimeout(() => {
|
||||||
const numeroInput = document.querySelector(
|
const numeroInput = document.querySelector(
|
||||||
'input[name="numero"]'
|
'input[name="numero"]'
|
||||||
) as HTMLInputElement;
|
) as HTMLInputElement;
|
||||||
if (numeroInput) numeroInput.focus();
|
if (numeroInput) numeroInput.focus();
|
||||||
}, 100);
|
}, 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
@@ -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(
|
||||||
(
|
(
|
||||||
|
|||||||
+731
-154
@@ -150,14 +150,13 @@ export class PdfService {
|
|||||||
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
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -166,195 +165,773 @@ export class PdfService {
|
|||||||
|
|
||||||
// Retornar configuração padrão se não existir
|
// Retornar configuração padrão se não existir
|
||||||
return {
|
return {
|
||||||
cabecalhoHtml: config?.cabecalhoHtml || `
|
// Valores padrão
|
||||||
|
cabecalhoHtml: `
|
||||||
<div style="text-align: center; padding: 20px;">
|
<div style="text-align: center; padding: 20px;">
|
||||||
<h2 style="margin:0;font-size:14pt">{{escritorio.nome}}</h2>
|
<h2 style="margin:0;font-size:14pt">{{escritorio.nome}}</h2>
|
||||||
</div>
|
</div>
|
||||||
`,
|
`,
|
||||||
rodapeHtml: config?.rodapeHtml || `
|
rodapeHtml: `
|
||||||
<div style="text-align: center; font-size: 10pt;">
|
<div style="text-align: center; font-size: 10pt;">
|
||||||
{{escritorio.endereco}}<br>
|
{{escritorio.endereco}}<br>
|
||||||
Tel: {{escritorio.telefone}} | Email: {{escritorio.email}}
|
Tel: {{escritorio.telefone}} | Email: {{escritorio.email}}
|
||||||
</div>
|
</div>
|
||||||
`,
|
`,
|
||||||
logoUrl: config?.logoUrl || '',
|
// Campos que existem no modelo
|
||||||
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 || null,
|
||||||
|
margensTemplate: config?.margensTemplate || null
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Erro ao buscar configuração:', error);
|
console.error('Erro ao buscar configuração:', error);
|
||||||
throw new Error('Falha ao buscar configuração');
|
// 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
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private gerarHTML(content: string, config: any) {
|
/**
|
||||||
const timbradoUrl = config.timbradoUrl
|
* Gera um PDF a partir do conteúdo HTML e dados do escritório
|
||||||
? `${process.env.BACKEND_URL || 'http://localhost:5000'}${config.timbradoUrl}`
|
* @param conteudo - Conteúdo HTML para o PDF
|
||||||
: '';
|
* @param escritorio - Dados do escritório para substituir no template
|
||||||
|
* @returns Buffer contendo o PDF gerado
|
||||||
console.log('Gerando PDF com timbrado:', timbradoUrl);
|
*/
|
||||||
|
async gerarPDF(conteudo: string, escritorio: any = {}): Promise<Buffer> {
|
||||||
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 {
|
try {
|
||||||
// 1. Buscar configuração do template
|
console.log('Buscando configurações do documento...');
|
||||||
const config = await prisma.configuracaoDocumento.findFirst({
|
const config = await this.getConfiguracao();
|
||||||
orderBy: { criadoEm: 'desc' }
|
|
||||||
});
|
|
||||||
|
|
||||||
// 2. Gerar PDF do conteúdo
|
// Verificar se temos um timbrado para usar
|
||||||
const browser = await puppeteer.launch({
|
const temTimbrado = !!config.timbradoUrl;
|
||||||
headless: 'new',
|
|
||||||
args: ['--no-sandbox']
|
|
||||||
});
|
|
||||||
|
|
||||||
const page = await browser.newPage();
|
console.log(`Iniciando geração de PDF ${temTimbrado ? 'com' : 'sem'} timbrado...`);
|
||||||
|
|
||||||
// Usar template padrão ou fallback para o template básico
|
// Se temos timbrado, vamos primeiro verificar se ele existe
|
||||||
const template = config?.templatePadrao || `
|
let timbradoPath = '';
|
||||||
<!DOCTYPE html>
|
let timbradoExists = false;
|
||||||
<html>
|
|
||||||
<head>
|
if (temTimbrado) {
|
||||||
<link href="https://fonts.googleapis.com/css2?family=Fira+Sans:wght@400;500;700&display=swap" rel="stylesheet">
|
if (config.timbradoUrl.startsWith('/uploads')) {
|
||||||
<style>
|
timbradoPath = path.join(process.cwd(), 'public', config.timbradoUrl);
|
||||||
body {
|
} else {
|
||||||
font-family: 'Fira Sans', Arial, sans-serif;
|
timbradoPath = path.join(process.cwd(), 'public', 'uploads', path.basename(config.timbradoUrl));
|
||||||
font-size: 11pt;
|
|
||||||
line-height: 1.3;
|
|
||||||
margin: 0;
|
|
||||||
padding: 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.content {
|
console.log('Verificando timbrado em:', timbradoPath);
|
||||||
margin: 0;
|
|
||||||
padding: 0;
|
try {
|
||||||
min-height: calc(100vh - 58mm);
|
await fs.access(timbradoPath);
|
||||||
position: relative;
|
timbradoExists = true;
|
||||||
|
console.log('Timbrado encontrado');
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Timbrado não encontrado:', e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
p { margin: 0.7em 0; }
|
// Margens definidas no template ou padrão
|
||||||
h1, h2, h3 { margin: 0.8em 0; }
|
const margens = config.margensTemplate || {
|
||||||
</style>
|
top: config.timbradoMarginTop || 100,
|
||||||
</head>
|
left: config.timbradoMarginLeft || 50,
|
||||||
<body>
|
right: config.timbradoMarginRight || 50,
|
||||||
<div class="content">
|
bottom: config.timbradoMarginBottom || 50
|
||||||
${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({
|
console.log('Usando margens:', margens);
|
||||||
format: 'A4',
|
|
||||||
margin: margens,
|
|
||||||
displayHeaderFooter: false,
|
|
||||||
printBackground: true
|
|
||||||
});
|
|
||||||
|
|
||||||
await browser.close();
|
// Abordagem focada em PDF de alta qualidade com formatação precisa
|
||||||
|
try {
|
||||||
|
console.log('Gerando PDF com formatação avançada...');
|
||||||
|
|
||||||
// 2. Carregar os PDFs
|
// 1. Primeiro carregar o timbrado se existir
|
||||||
const templatePath = path.join(process.cwd(), 'public', 'uploads', 'Timbrado_2025.pdf');
|
let pdfDoc;
|
||||||
const templateBytes = await fs.readFile(templatePath);
|
const fontSize = 11;
|
||||||
|
const lineHeight = fontSize * 1.5; // Espaçamento entre linhas um pouco maior para melhor legibilidade
|
||||||
|
const pageWidth = 595;
|
||||||
|
const pageHeight = 842;
|
||||||
|
|
||||||
const templateDoc = await PDFDocument.load(templateBytes);
|
if (timbradoExists) {
|
||||||
const contentDoc = await PDFDocument.load(contentPdfBuffer);
|
console.log('Usando timbrado como base do documento...');
|
||||||
|
// Carregar o arquivo de timbrado
|
||||||
|
const timbradoBytes = await fs.readFile(timbradoPath);
|
||||||
|
try {
|
||||||
|
pdfDoc = await PDFDocument.load(timbradoBytes);
|
||||||
|
console.log('Timbrado carregado com sucesso');
|
||||||
|
|
||||||
// 3. Criar documento final
|
// Verificar se o timbrado tem páginas
|
||||||
const pdfDoc = await PDFDocument.create();
|
if (pdfDoc.getPageCount() === 0) {
|
||||||
|
console.log('Timbrado não contém páginas, adicionando página padrão');
|
||||||
// 4. Copiar template e conteúdo
|
pdfDoc.addPage([pageWidth, pageHeight]);
|
||||||
const [templatePage] = await templateDoc.copyPages(templateDoc, [0]);
|
}
|
||||||
const contentPages = await contentDoc.getPages();
|
} catch (loadError) {
|
||||||
|
console.error('Erro ao carregar timbrado:', loadError);
|
||||||
// 5. Para cada página do conteúdo
|
// Se falhar ao carregar o timbrado, criar novo documento
|
||||||
for (let i = 0; i < contentPages.length; i++) {
|
pdfDoc = await PDFDocument.create();
|
||||||
// Primeiro: adicionar template
|
pdfDoc.addPage([pageWidth, pageHeight]);
|
||||||
const page = await pdfDoc.embedPage(templatePage);
|
}
|
||||||
const contentPage = await pdfDoc.embedPage(contentPages[i]);
|
} else {
|
||||||
|
// Criar documento em branco
|
||||||
// Segundo: criar nova página
|
console.log('Criando novo documento sem timbrado...');
|
||||||
const newPage = pdfDoc.addPage([page.width, page.height]);
|
pdfDoc = await PDFDocument.create();
|
||||||
|
pdfDoc.addPage([pageWidth, pageHeight]);
|
||||||
// Terceiro: desenhar template e conteúdo
|
|
||||||
newPage.drawPage(page);
|
|
||||||
newPage.drawPage(contentPage);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 6. Gerar PDF final
|
// 2. Carregar fontes - Como pdf-lib não suporta Fira Sans nativamente, usamos Helvetica
|
||||||
|
// Nota: Em uma implementação mais avançada, poderíamos incorporar a fonte Fira Sans como arquivo TTF
|
||||||
|
const font = await pdfDoc.embedFont(StandardFonts.Helvetica);laridade com Fira Sans
|
||||||
|
const boldFont = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
|
||||||
|
const italicFont = await pdfDoc.embedFont(StandardFonts.HelveticaOblique);
|
||||||
|
// Tentar carregar Fira Sans se estiver disponível no sistema de arquivos
|
||||||
|
// 3. Processar e formatar o HTML com preservação de estrutura
|
||||||
|
console.log('Processando HTML com preservação de estrutura...');
|
||||||
|
try {
|
||||||
|
// Processar variáveisíveis arquivos de fonte Fira Sans
|
||||||
|
const processedContent = this.processarTemplate(conteudo, escritorio);raSans-Regular.ttf');
|
||||||
|
const firaSansBoldPath = path.join(process.cwd(), 'public', 'fonts', 'FiraSans-Bold.ttf');
|
||||||
|
// Função para decodificar entidades HTML melhorada
|
||||||
|
const decodeHtmlEntities = (text: string): string => {
|
||||||
|
// Mapa expandido de entidades HTML
|
||||||
|
const entities: Record<string, string> = {
|
||||||
|
" ": " ",s(firaSansPath);
|
||||||
|
"&": "&",s = true;
|
||||||
|
"<": "<",'Fonte Fira Sans encontrada, utilizando-a para o documento');
|
||||||
|
">": ">",
|
||||||
|
""": "\"",nte Fira Sans não encontrada, usando Helvetica como fallback');
|
||||||
|
"'": "'",
|
||||||
|
"¢": "¢",
|
||||||
|
"£": "£",s) {
|
||||||
|
"¥": "¥",s fontes Fira Sans
|
||||||
|
"€": "€",Bytes = await fs.readFile(firaSansPath);
|
||||||
|
"©": "©",dfDoc.embedFont(firaSansBytes);
|
||||||
|
"®": "®",
|
||||||
|
"™": "™",
|
||||||
|
"À": "À",BoldBytes = await fs.readFile(firaSansBoldPath);
|
||||||
|
"à": "à",it pdfDoc.embedFont(firaSansBoldBytes);
|
||||||
|
"Á": "Á",
|
||||||
|
"á": "á",ira Sans Bold não encontrada, usando regular como fallback');
|
||||||
|
"Â": "Â",nt;
|
||||||
|
"â": "â",
|
||||||
|
"Ã": "Ã",
|
||||||
|
"ã": "ã",lico, usar regular
|
||||||
|
"Ä": "Ä",ont;
|
||||||
|
"ä": "ä",
|
||||||
|
"Å": "Å",ca como fallback
|
||||||
|
"å": "å",fDoc.embedFont(StandardFonts.Helvetica);
|
||||||
|
"Æ": "Æ",t pdfDoc.embedFont(StandardFonts.HelveticaBold);
|
||||||
|
"æ": "æ",ait pdfDoc.embedFont(StandardFonts.HelveticaOblique);
|
||||||
|
"Ç": "Ç",
|
||||||
|
"ç": "ç",{
|
||||||
|
"È": "È",o ao carregar fontes personalizadas:', fontError);
|
||||||
|
"è": "è",elvetica
|
||||||
|
"É": "É",c.embedFont(StandardFonts.Helvetica);
|
||||||
|
"é": "é",dfDoc.embedFont(StandardFonts.HelveticaBold);
|
||||||
|
"Ê": "Ê",t pdfDoc.embedFont(StandardFonts.HelveticaOblique);
|
||||||
|
"ê": "ê",
|
||||||
|
"Ë": "Ë",
|
||||||
|
"ë": "ë",formatar o HTML com preservação de estrutura
|
||||||
|
"Ì": "Ì",ando HTML com preservação de estrutura...');
|
||||||
|
"ì": "ì",
|
||||||
|
"Í": "Í",is
|
||||||
|
"í": "í",nt = this.processarTemplate(conteudo, escritorio);
|
||||||
|
"Î": "Î",
|
||||||
|
"î": "î",dificar entidades HTML melhorada
|
||||||
|
"Ï": "Ï",tities = (text: string): string => {
|
||||||
|
"ï": "ï",o de entidades HTML
|
||||||
|
"Ð": "Ð", Record<string, string> = {
|
||||||
|
"ð": "ð",,
|
||||||
|
"Ñ": "Ñ",
|
||||||
|
"ñ": "ñ",
|
||||||
|
"Ò": "Ò",
|
||||||
|
"ò": "ò",
|
||||||
|
"Ó": "Ó",
|
||||||
|
"ó": "ó",
|
||||||
|
"Ô": "Ô",
|
||||||
|
"ô": "ô",
|
||||||
|
"Õ": "Õ",
|
||||||
|
"õ": "õ",
|
||||||
|
"Ö": "Ö",
|
||||||
|
"ö": "ö",,
|
||||||
|
"Ø": "Ø",
|
||||||
|
"ø": "ø",
|
||||||
|
"Ù": "Ù",
|
||||||
|
"ù": "ù",
|
||||||
|
"Ú": "Ú",
|
||||||
|
"ú": "ú",
|
||||||
|
"Û": "Û",,
|
||||||
|
"û": "û",,
|
||||||
|
"Ü": "Ü",
|
||||||
|
"ü": "ü",
|
||||||
|
"Ý": "Ý",
|
||||||
|
"ý": "ý",
|
||||||
|
"ÿ": "ÿ",,
|
||||||
|
"ß": "ß",
|
||||||
|
"–": "–",,
|
||||||
|
"—": "—",,
|
||||||
|
"‘": "'",,
|
||||||
|
"’": "'",,
|
||||||
|
"‚": "‚",,
|
||||||
|
"“": "\"",
|
||||||
|
"”": "\"",
|
||||||
|
"„": "„",
|
||||||
|
"‹": "‹",
|
||||||
|
"›": "›",
|
||||||
|
"«": "«",,
|
||||||
|
"»": "»",,
|
||||||
|
"…": "…",
|
||||||
|
"•": "•",",
|
||||||
|
"·": "·"
|
||||||
|
};"î": "î",
|
||||||
|
"Ï": "Ï",
|
||||||
|
return text.replace(/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});/gi, (match) => {
|
||||||
|
if (entities[match]) {
|
||||||
|
return entities[match];
|
||||||
|
} else if (match.startsWith('&#x')) {
|
||||||
|
// Hexadecimal Unicode
|
||||||
|
const hex = match.substring(3, match.length - 1);
|
||||||
|
try {e;": "ò",
|
||||||
|
return String.fromCodePoint(parseInt(hex, 16));
|
||||||
|
} catch (e) {,
|
||||||
|
return match;
|
||||||
|
}circ;": "ô",
|
||||||
|
} else if (match.startsWith('&#')) {
|
||||||
|
// Decimal Unicode
|
||||||
|
const decimal = match.substring(2, match.length - 1);
|
||||||
|
try {": "ö",
|
||||||
|
return String.fromCodePoint(parseInt(decimal, 10));
|
||||||
|
} catch (e) {,
|
||||||
|
return match;
|
||||||
|
}grave;": "ù",
|
||||||
|
}Ú": "Ú",
|
||||||
|
return match;ú",
|
||||||
|
});Û": "Û",
|
||||||
|
}; "û": "û",
|
||||||
|
"Ü": "Ü",
|
||||||
|
// Extrair elementos estruturados do HTML para melhor formatação
|
||||||
|
const extractStructuredContent = (html) => {
|
||||||
|
// Limpar o HTML inicial
|
||||||
|
let cleanHtml = html
|
||||||
|
// Remover scripts e styles
|
||||||
|
.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
|
||||||
|
.replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, '')
|
||||||
|
// Normalizar quebras de linha
|
||||||
|
.replace(/\r\n/g, '\n')
|
||||||
|
.replace(/\r/g, '\n');
|
||||||
|
"“": "\"",
|
||||||
|
// Substituir os por espaços regulares mas preservar os consecutivos
|
||||||
|
cleanHtml = cleanHtml.replace(/( ){2,}/g, match => ' '.repeat(match.length / 6));
|
||||||
|
cleanHtml = cleanHtml.replace(/ /g, ' ');
|
||||||
|
"›": "›",
|
||||||
|
// Preservar informações de estilo e formatação
|
||||||
|
const elements = [];
|
||||||
|
"…": "…",
|
||||||
|
// Extrair e processar elementos de cabeçalho
|
||||||
|
const headingRegex = /<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/gi;
|
||||||
|
let headingMatch;
|
||||||
|
while ((headingMatch = headingRegex.exec(cleanHtml)) !== null) {
|
||||||
|
elements.push({ce(/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});/gi, (match) => {
|
||||||
|
type: 'heading',]) {
|
||||||
|
level: parseInt(headingMatch[1]),
|
||||||
|
content: decodeHtmlEntities(headingMatch[2].replace(/<[^>]*>/g, '').trim())
|
||||||
|
});/ Hexadecimal Unicode
|
||||||
|
} const hex = match.substring(3, match.length - 1);
|
||||||
|
try {
|
||||||
|
// Extrair e processar parágrafos(parseInt(hex, 16));
|
||||||
|
const paragraphRegex = /<p[^>]*>([\s\S]*?)<\/p>/gi;
|
||||||
|
let paragraphMatch;
|
||||||
|
while ((paragraphMatch = paragraphRegex.exec(cleanHtml)) !== null) {
|
||||||
|
elements.push({h.startsWith('&#')) {
|
||||||
|
type: 'paragraph',
|
||||||
|
content: decodeHtmlEntities(paragraphMatch[1]th - 1);
|
||||||
|
.replace(/<br\s*\/?>/gi, '\n')
|
||||||
|
.replace(/<[^>]*>/g, '')int(parseInt(decimal, 10));
|
||||||
|
.trim())) {
|
||||||
|
}); return match;
|
||||||
|
} }
|
||||||
|
}
|
||||||
|
// Extrair texto de divs que não foram capturados
|
||||||
|
const divRegex = /<div[^>]*>([\s\S]*?)<\/div>/gi;
|
||||||
|
let divMatch;
|
||||||
|
while ((divMatch = divRegex.exec(cleanHtml)) !== null) {
|
||||||
|
const content = decodeHtmlEntities(divMatch[1]hor formatação
|
||||||
|
.replace(/<br\s*\/?>/gi, '\n')ml) => {
|
||||||
|
.replace(/<[^>]*>/g, '')
|
||||||
|
.trim()); = html
|
||||||
|
// Remover scripts e styles
|
||||||
|
if (content) {ipt\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
|
||||||
|
elements.push({b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, '')
|
||||||
|
type: 'div',ebras de linha
|
||||||
|
contentr\n/g, '\n')
|
||||||
|
});ace(/\r/g, '\n');
|
||||||
|
}
|
||||||
|
}/ Substituir os por espaços regulares mas preservar os consecutivos
|
||||||
|
cleanHtml = cleanHtml.replace(/( ){2,}/g, match => ' '.repeat(match.length / 6));
|
||||||
|
// Se o texto não tiver estrutura clara, extrair todo o texto restante
|
||||||
|
if (elements.length === 0) {
|
||||||
|
const plainText = decodeHtmlEntities(cleanHtml
|
||||||
|
.replace(/<br\s*\/?>/gi, '\n')
|
||||||
|
.replace(/<\/p>\s*<p[^>]*>/gi, '\n\n')
|
||||||
|
.replace(/<\/div>\s*<div[^>]*>/gi, '\n')o
|
||||||
|
.replace(/<[^>]*>/g, '')6])[^>]*>([\s\S]*?)<\/h\1>/gi;
|
||||||
|
.trim());tch;
|
||||||
|
ile ((headingMatch = headingRegex.exec(cleanHtml)) !== null) {
|
||||||
|
// Dividir por linhas vazias para criar parágrafos
|
||||||
|
const paragraphs = plainText.split(/\n\s*\n/);
|
||||||
|
level: parseInt(headingMatch[1]),
|
||||||
|
for (const paragraph of paragraphs) {Match[2].replace(/<[^>]*>/g, '').trim())
|
||||||
|
if (paragraph.trim()) {
|
||||||
|
elements.push({
|
||||||
|
type: 'paragraph',
|
||||||
|
content: paragraph.trim()
|
||||||
|
});agraphRegex = /<p[^>]*>([\s\S]*?)<\/p>/gi;
|
||||||
|
}aragraphMatch;
|
||||||
|
}le ((paragraphMatch = paragraphRegex.exec(cleanHtml)) !== null) {
|
||||||
|
} elements.push({
|
||||||
|
type: 'paragraph',
|
||||||
|
return elements.sort((a, b) => {paragraphMatch[1]
|
||||||
|
// Manter a ordem original dos elementos
|
||||||
|
const aIndex = html.indexOf(a.content);
|
||||||
|
const bIndex = html.indexOf(b.content);
|
||||||
|
return aIndex - bIndex;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
// Extrair texto de divs que não foram capturados
|
||||||
|
// Extrair conteúdo estruturado[\s\S]*?)<\/div>/gi;
|
||||||
|
const structuredContent = extractStructuredContent(processedContent);
|
||||||
|
while ((divMatch = divRegex.exec(cleanHtml)) !== null) {
|
||||||
|
// 4. Renderizar o conteúdo estruturado no PDFh[1]
|
||||||
|
console.log(`Renderizando ${structuredContent.length} elementos...`);
|
||||||
|
.replace(/<[^>]*>/g, '')
|
||||||
|
// Obter primeira página do documento
|
||||||
|
let currentPage = pdfDoc.getPage(0);
|
||||||
|
let y = pageHeight - margens.top; // Posição inicial a partir do topo com margem
|
||||||
|
let pageIndex = 0;h({
|
||||||
|
type: 'div',
|
||||||
|
// Armazenar o timbrado como template para novas páginas, se existir
|
||||||
|
let timbradoTemplate = null;
|
||||||
|
if (timbradoExists && pdfDoc.getPageCount() > 0) {
|
||||||
|
try {
|
||||||
|
// Copiar a primeira página como template para futuras páginas
|
||||||
|
timbradoTemplate = pdfDoc.getPage(0);o restante
|
||||||
|
console.log('Template de timbrado capturado para replicação em novas páginas'); {
|
||||||
|
} catch (e) {t = decodeHtmlEntities(cleanHtml
|
||||||
|
console.error('Erro ao capturar template de timbrado:', e);)
|
||||||
|
}/p>\s*<p[^>]*>/gi, '\n\n')
|
||||||
|
}v>\s*<div[^>]*>/gi, '\n')
|
||||||
|
|
||||||
|
// Função para adicionar nova página quando necessário
|
||||||
|
const addNewPageIfNeeded = (minSpace) => {
|
||||||
|
if (y - minSpace < margens.bottom) { // Dividir por linhas vazias para criar parágrafos
|
||||||
|
try {raphs = plainText.split(/\n\s*\n/);
|
||||||
|
let newPage;
|
||||||
|
for (const paragraph of paragraphs) {
|
||||||
|
if (timbradoExists) {
|
||||||
|
// Se temos timbrado, criar nova página com timbrado
|
||||||
|
console.log('Adicionando nova página com timbrado...');
|
||||||
|
paragraph.trim()
|
||||||
|
if (timbradoTemplate) {
|
||||||
|
// Copiar a página de timbrado
|
||||||
|
const [embeddedPage] = pdfDoc.copyPages(pdfDoc, [0]); }
|
||||||
|
newPage = pdfDoc.addPage(embeddedPage.getSize());
|
||||||
|
|
||||||
|
// Se possível, aplicar o timbrado como imagem de fundo
|
||||||
|
try {os
|
||||||
|
const { width, height } = newPage.getSize();const aIndex = html.indexOf(a.content);
|
||||||
|
const bIndex = html.indexOf(b.content);
|
||||||
|
// Copiar o conteúdo do timbrado para esta nova página
|
||||||
|
newPage.drawPage(embeddedPage, {
|
||||||
|
x: 0,
|
||||||
|
y: 0,
|
||||||
|
width,uturado
|
||||||
|
height,tStructuredContent(processedContent);
|
||||||
|
opacity: 1,
|
||||||
|
xScale: 1,ar o conteúdo estruturado no PDF
|
||||||
|
yScale: 1length} elementos...`);
|
||||||
|
});
|
||||||
|
} catch (drawError) {do documento
|
||||||
|
console.error('Erro ao aplicar timbrado à nova página:', drawError);rentPage = pdfDoc.getPage(0);
|
||||||
|
}Height - margens.top; // Posição inicial a partir do topo com margem
|
||||||
|
} else {
|
||||||
|
// Se não conseguiu capturar o template, usar tamanho padrão
|
||||||
|
newPage = pdfDoc.addPage([pageWidth, pageHeight]);Função para adicionar nova página quando necessário
|
||||||
|
}nst addNewPageIfNeeded = (minSpace) => {
|
||||||
|
} else { margens.bottom) {
|
||||||
|
// Sem timbrado, usar página em branco
|
||||||
|
newPage = pdfDoc.addPage([pageWidth, pageHeight]); // Adicionar nova página
|
||||||
|
} const newPage = pdfDoc.addPage([pageWidth, pageHeight]);
|
||||||
|
ge = newPage;
|
||||||
|
currentPage = newPage; pageIndex++;
|
||||||
|
pageIndex++; y = pageHeight - margens.top;
|
||||||
|
y = pageHeight - margens.top;
|
||||||
|
return true;
|
||||||
|
} catch (error) {onar página:', error);
|
||||||
|
console.error('Erro ao adicionar página:', error);
|
||||||
|
}
|
||||||
|
// Tentar novamente com abordagem simples
|
||||||
|
try {
|
||||||
|
const newPage = pdfDoc.addPage([pageWidth, pageHeight]);
|
||||||
|
currentPage = newPage;
|
||||||
|
pageIndex++;ção para quebrar texto em linhas
|
||||||
|
y = pageHeight - margens.top;Width) => {
|
||||||
|
return true;ndo arrays
|
||||||
|
} catch (fallbackError) {t lines = [];
|
||||||
|
console.error('Falha crítica ao adicionar página:', fallbackError);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}stimativa de largura (pdf-lib não tem método direto para calcular largura de texto)
|
||||||
|
}
|
||||||
|
return false;0.55;
|
||||||
|
};Width;
|
||||||
|
|
||||||
|
// Função para quebrar texto em linhas
|
||||||
|
const wrapTextToLines = (text, maxWidth) => {s) {
|
||||||
|
// Método mais preciso usando arraystLine ? `${currentLine} ${word}` : word;
|
||||||
|
const lines = [];
|
||||||
|
const words = text.split(' ');e) > maxWidth) {
|
||||||
|
let currentLine = '';f (currentLine) {
|
||||||
|
lines.push(currentLine);
|
||||||
|
// Estimativa de largura (pdf-lib não tem método direto para calcular largura de texto)
|
||||||
|
const getApproxWidth = (text) => {
|
||||||
|
const averageCharWidth = fontSize * 0.55;alavra longa demais para uma linha
|
||||||
|
return text.length * averageCharWidth; lines.push(word);
|
||||||
|
}; '';
|
||||||
|
|
||||||
|
for (const word of words) {
|
||||||
|
const testLine = currentLine ? `${currentLine} ${word}` : word;
|
||||||
|
|
||||||
|
if (getApproxWidth(testLine) > maxWidth) {
|
||||||
|
if (currentLine) {
|
||||||
|
lines.push(currentLine);
|
||||||
|
currentLine = word;
|
||||||
|
} else {
|
||||||
|
// Palavra longa demais para uma linha
|
||||||
|
lines.push(word);lines;
|
||||||
|
currentLine = '';
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
currentLine = testLine;st element of structuredContent) {
|
||||||
|
}
|
||||||
|
}t - margens.right;
|
||||||
|
|
||||||
|
if (currentLine) {
|
||||||
|
lines.push(currentLine);eading':
|
||||||
|
}t headingSize = fontSize * (1.8 - (element.level - 1) * 0.2);
|
||||||
|
ines(element.content, availableWidth);
|
||||||
|
return lines;
|
||||||
|
};eçalho
|
||||||
|
eHeight * 0.5;
|
||||||
|
// Renderizar todos os elementos estruturados
|
||||||
|
for (const element of structuredContent) { para o cabeçalho completo
|
||||||
|
// Largura disponível para textoeadingSpace = headingLines.length * lineHeight * 1.2 + lineHeight;
|
||||||
|
const availableWidth = pageWidth - margens.left - margens.right;ewPageIfNeeded(headingSpace);
|
||||||
|
|
||||||
|
switch (element.type) {Desenhar cada linha do cabeçalho
|
||||||
|
case 'heading':r (const line of headingLines) {
|
||||||
|
const headingSize = fontSize * (1.8 - (element.level - 1) * 0.2);, {
|
||||||
|
const headingLines = wrapTextToLines(element.content, availableWidth);
|
||||||
|
|
||||||
|
// Espaço antes do cabeçalho
|
||||||
|
y -= lineHeight * 0.5;
|
||||||
|
);
|
||||||
|
// Espaço necessário para o cabeçalho completo y -= lineHeight * 1.2;
|
||||||
|
const headingSpace = headingLines.length * lineHeight * 1.2 + lineHeight;}
|
||||||
|
addNewPageIfNeeded(headingSpace);
|
||||||
|
ós cabeçalho
|
||||||
|
// Desenhar cada linha do cabeçalhoineHeight * 0.3;
|
||||||
|
for (const line of headingLines) { break;
|
||||||
|
currentPage.drawText(line, {
|
||||||
|
x: margens.left, case 'paragraph':
|
||||||
|
y,
|
||||||
|
font: boldFont,
|
||||||
|
size: headingSizet.split('\n');
|
||||||
|
});
|
||||||
|
y -= lineHeight * 1.2;
|
||||||
|
}ine of textLines) {
|
||||||
|
|
||||||
|
// Espaço adicional após cabeçalhodicionar espaço
|
||||||
|
y -= lineHeight * 0.3;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'paragraph':
|
||||||
|
case 'div': largura
|
||||||
|
// Dividir em linhas para respeitar a quebra de linhatLine, availableWidth);
|
||||||
|
const textLines = element.content.split('\n');
|
||||||
|
let firstParagraphLine = true;dLine of wrappedLines) {
|
||||||
|
a página
|
||||||
|
for (const textLine of textLines) {neHeight)) {
|
||||||
|
if (!textLine.trim()) { // Nova página foi adicionada
|
||||||
|
// Linha vazia - adicionar espaço }
|
||||||
|
y -= lineHeight * 0.5;
|
||||||
|
continue;
|
||||||
|
}drawText(wrappedLine.trim(), {
|
||||||
|
rgens.left,
|
||||||
|
// Quebrar a linha para caber na largura y,
|
||||||
|
const wrappedLines = wrapTextToLines(textLine, availableWidth);nt,
|
||||||
|
|
||||||
|
for (const wrappedLine of wrappedLines) { });
|
||||||
|
// Verificar se precisa de nova página
|
||||||
|
if (addNewPageIfNeeded(lineHeight)) {
|
||||||
|
// Nova página foi adicionada }
|
||||||
|
}
|
||||||
|
if (firstParagraphLine) {
|
||||||
|
// Desenhar a linha de textoLine = false;
|
||||||
|
currentPage.drawText(wrappedLine.trim(), {
|
||||||
|
x: margens.left,re parágrafos distintos
|
||||||
|
y, y -= lineHeight * 0.2;
|
||||||
|
font,
|
||||||
|
size: fontSize
|
||||||
|
});
|
||||||
|
// Espaço após parágrafo
|
||||||
|
y -= lineHeight;
|
||||||
|
} break;
|
||||||
|
|
||||||
|
if (firstParagraphLine) {
|
||||||
|
firstParagraphLine = false;
|
||||||
|
} else {o estiver usando timbrado
|
||||||
|
// Pequeno espaço extra entre parágrafos distintosio.nome || escritorio.endereco || escritorio.telefone || escritorio.email)) {
|
||||||
|
y -= lineHeight * 0.2;
|
||||||
|
}const footerY = margens.bottom - 15;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Espaço após parágrafoitorio.nome) footerText += escritorio.nome;
|
||||||
|
y -= lineHeight * 0.3;torio.endereco) {
|
||||||
|
break;rText) footerText += ' | ';
|
||||||
|
}erText += escritorio.endereco;
|
||||||
|
}
|
||||||
|
if (escritorio.telefone) {
|
||||||
|
// 5. Adicionar rodapé discreto apenas se não estiver usando timbrado
|
||||||
|
if (!timbradoExists && (escritorio.nome || escritorio.endereco || escritorio.telefone || escritorio.email)) {Text += `Tel: ${escritorio.telefone}`;
|
||||||
|
// Adicionar rodapé na última página
|
||||||
|
const footerY = margens.bottom - 15;rio.email) {
|
||||||
|
footerText) footerText += ' | ';
|
||||||
|
let footerText = '';ooterText += escritorio.email;
|
||||||
|
if (escritorio.nome) footerText += escritorio.nome;}
|
||||||
|
if (escritorio.endereco) {
|
||||||
|
if (footerText) footerText += ' | ';
|
||||||
|
footerText += escritorio.endereco; currentPage.drawText(footerText, {
|
||||||
|
}
|
||||||
|
if (escritorio.telefone) {
|
||||||
|
if (footerText) footerText += ' | '; font,
|
||||||
|
footerText += `Tel: ${escritorio.telefone}`;
|
||||||
|
}0.5, 0.5) // Cinza claro para ser discreto
|
||||||
|
if (escritorio.email) {
|
||||||
|
if (footerText) footerText += ' | ';} catch (footerError) {
|
||||||
|
footerText += escritorio.email;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
currentPage.drawText(footerText, {
|
||||||
|
x: margens.left,ole.log('Finalizando e salvando PDF...');
|
||||||
|
y: footerY,fDoc.save();
|
||||||
|
font,
|
||||||
|
size: 8,rom(pdfBytes);
|
||||||
|
color: rgb(0.5, 0.5, 0.5) // Cinza claro para ser discreto{
|
||||||
|
});ror('Erro ao gerar PDF:', error);
|
||||||
|
} catch (footerError) {
|
||||||
|
console.error('Erro ao adicionar rodapé:', footerError);Fallback absolutamente mínimo e à prova de falhas
|
||||||
|
}y {
|
||||||
|
}Usando fallback ultra-minimalista...');
|
||||||
|
|
||||||
|
// 6. Salvar o documento forma mais simples possível
|
||||||
|
console.log('Finalizando e salvando PDF...');FDocument.create();
|
||||||
|
const pdfBytes = await pdfDoc.save();
|
||||||
|
const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
|
||||||
|
return Buffer.from(pdfBytes);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro ao gerar PDF:', error); page.drawText('Documento', {
|
||||||
|
x: 50,
|
||||||
|
// Fallback absolutamente mínimo e à prova de falhas
|
||||||
|
try {
|
||||||
|
console.log('Usando fallback ultra-minimalista...'); font
|
||||||
|
|
||||||
|
// Criar documento do zero da forma mais simples possível
|
||||||
|
const pdfDoc = await PDFDocument.create();tring('pt-BR'), {
|
||||||
|
const page = pdfDoc.addPage(); x: 50,
|
||||||
|
const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
|
||||||
|
|
||||||
|
// Desenhar texto mínimo
|
||||||
|
page.drawText('Documento', { });
|
||||||
|
x: 50,
|
||||||
|
y: 800,exto
|
||||||
|
size: 14,plainText = conteudo.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim();
|
||||||
|
font
|
||||||
|
});ir que não exceda limite seguro
|
||||||
|
t safeText = plainText.substring(0, Math.min(plainText.length, 1000));
|
||||||
|
page.drawText('Gerado em: ' + new Date().toLocaleString('pt-BR'), {
|
||||||
|
x: 50, // Adicionar linhas de texto com posições absolutos
|
||||||
|
y: 780,30;
|
||||||
|
size: 10,
|
||||||
|
font
|
||||||
|
});t i = 0; i < safeText.length && i/lineLength < maxLines; i += lineLength) {
|
||||||
|
ine = safeText.substring(i, i + lineLength);
|
||||||
|
// Extrair e adicionar apenas parte do textonst lineY = 750 - Math.floor(i/lineLength) * 12;
|
||||||
|
const plainText = conteudo.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim();
|
||||||
|
if (lineY < 50) break; // Evitar desenhar fora da página
|
||||||
|
// Garantir que não exceda limite seguro
|
||||||
|
const safeText = plainText.substring(0, Math.min(plainText.length, 1000));
|
||||||
|
x: 50,
|
||||||
|
// Adicionar linhas de texto com posições absolutos
|
||||||
|
const maxLines = 30;
|
||||||
|
const lineLength = 60;
|
||||||
|
|
||||||
|
for (let i = 0; i < safeText.length && i/lineLength < maxLines; i += lineLength) { }
|
||||||
|
const line = safeText.substring(i, i + lineLength);
|
||||||
|
const lineY = 750 - Math.floor(i/lineLength) * 12;
|
||||||
|
|
||||||
|
if (lineY < 50) break; // Evitar desenhar fora da páginafBytes);
|
||||||
|
allbackError) {
|
||||||
|
page.drawText(line, {allback:', fallbackError);
|
||||||
|
x: 50,
|
||||||
|
y: lineY,ar um PDF manualmente como último recurso
|
||||||
|
size: 9,urn Buffer.from('%PDF-1.4\n1 0 obj\n<</Type/Catalog/Pages 2 0 R>>\nendobj\n2 0 obj\n<</Type/Pages/Kids[3 0 R]/Count 1>>\nendobj\n3 0 obj\n<</Type/Page/MediaBox[0 0 595 842]/Parent 2 0 R/Resources<<>>>>\nendobj\nxref\n0 4\n0000000000 65535 f\n0000000015 00000 n\n0000000060 00000 n\n0000000111 00000 n\ntrailer\n<</Size 4/Root 1 0 R>>\nstartxref\n190\n%%EOF');
|
||||||
|
font
|
||||||
|
});
|
||||||
|
}
|
||||||
|
rar PDF:', error);
|
||||||
|
// Salvar PDF
|
||||||
const pdfBytes = await pdfDoc.save();
|
const pdfBytes = await pdfDoc.save();
|
||||||
return Buffer.from(pdfBytes);
|
return Buffer.from(pdfBytes);
|
||||||
|
} catch (fallbackError) { console.log('Usando método de fallback simples...');
|
||||||
|
console.error('Erro no fallback:', fallbackError);
|
||||||
|
const pdfDoc = await PDFDocument.create();
|
||||||
|
// Criar um PDF manualmente como último recurso const page = pdfDoc.addPage([595, 842]);
|
||||||
|
return Buffer.from('%PDF-1.4\n1 0 obj\n<</Type/Catalog/Pages 2 0 R>>\nendobj\n2 0 obj\n<</Type/Pages/Kids[3 0 R]/Count 1>>\nendobj\n3 0 obj\n<</Type/Page/MediaBox[0 0 595 842]/Parent 2 0 R/Resources<<>>>>\nendobj\nxref\n0 4\n0000000000 65535 f\n0000000015 00000 n\n0000000060 00000 n\n0000000111 00000 n\ntrailer\n<</Size 4/Root 1 0 R>>\nstartxref\n190\n%%EOF'); const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
|
||||||
|
}
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Erro ao gerar PDF:', error);
|
console.error('Erro geral ao gerar PDF:', error);
|
||||||
throw new Error('Falha ao gerar PDF');
|
y: 800,
|
||||||
|
// Método de fallback extremamente básico
|
||||||
|
try {
|
||||||
|
console.log('Usando método de fallback simples...');
|
||||||
|
|
||||||
|
const pdfDoc = await PDFDocument.create(); // Mensagem de erro
|
||||||
|
const page = pdfDoc.addPage([595, 842]);mergência.', {
|
||||||
|
const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
|
||||||
|
|
||||||
|
// Título
|
||||||
|
page.drawText('Documento de Emergência', {
|
||||||
|
x: 50,
|
||||||
|
y: 800,
|
||||||
|
size: 16,/ Adicionar parte do conteúdo como texto plano
|
||||||
|
font const plainText = conteudo.replace(/<[^>]*>/g, ' ').slice(0, 1000);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Mensagem de erro const lines = [];
|
||||||
|
page.drawText('Este documento foi gerado em modo de emergência.', { for (let i = 0; i < plainText.length; i += 70) {
|
||||||
|
x: 50, lines.push(plainText.substring(i, i + 70));
|
||||||
|
y: 760, }
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
} } }); return value !== undefined ? value : match; } } break; value = undefined; } else { value = value[part]; if (value && typeof value === 'object' && part in value) { for (const part of keyParts) { // Acessar propriedades aninhadas (ex: escritorio.nome) let value = dados; const keyParts = key.trim().split('.'); return template.replace(/\{\{([^}]+)\}\}/g, (match, key) => { private processarTemplate(template: string, dados: any): string { */ * @returns Template processado * @param dados - Objeto com valores para substituir * @param template - Template HTML com variáveis no formato {{variavel}} * Processa um template HTML substituindo variáveis pelos valores do objeto /** } } } throw new Error('Falha completa ao gerar PDF'); console.error('Falha no fallback:', fallbackError); } catch (fallbackError) { return Buffer.from(pdfBytes); const pdfBytes = await pdfDoc.save(); }); }); font size: 8, y: 720 - (index * 12), x: 50, page.drawText(line, { lines.slice(0, 30).forEach((line, index) => { // Adicionar no máximo 30 linhas } lines.push(plainText.substring(i, i + 70)); for (let i = 0; i < plainText.length; i += 70) { const lines = []; // Quebrar em linhas const plainText = conteudo.replace(/<[^>]*>/g, ' ').slice(0, 1000); // Adicionar parte do conteúdo como texto plano }); font size: 10,
|
||||||
|
// Adicionar no máximo 30 linhas
|
||||||
|
lines.slice(0, 30).forEach((line, index) => {
|
||||||
|
page.drawText(line, {
|
||||||
|
x: 50,
|
||||||
|
y: 720 - (index * 12),
|
||||||
|
size: 8,
|
||||||
|
font
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const pdfBytes = await pdfDoc.save();
|
||||||
|
return Buffer.from(pdfBytes);
|
||||||
|
} catch (fallbackError) {
|
||||||
|
console.error('Falha no fallback:', fallbackError);
|
||||||
|
throw new Error('Falha completa ao gerar PDF');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Processa um template HTML substituindo variáveis pelos valores do objeto
|
||||||
|
* @param template - Template HTML com variáveis no formato {{variavel}}
|
||||||
|
* @param dados - Objeto com valores para substituir
|
||||||
|
* @returns Template processado
|
||||||
|
*/
|
||||||
|
private processarTemplate(template: string, dados: any): string {
|
||||||
|
return template.replace(/\{\{([^}]+)\}\}/g, (match, key) => {
|
||||||
|
const keyParts = key.trim().split('.');
|
||||||
|
let value = dados;
|
||||||
|
|
||||||
|
// Acessar propriedades aninhadas (ex: escritorio.nome)
|
||||||
|
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;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user