632 lines
23 KiB
TypeScript
632 lines
23 KiB
TypeScript
import puppeteer from 'puppeteer';
|
|
import { prisma } from '../prismaClient';
|
|
import { PDFDocument, rgb, StandardFonts } from 'pdf-lib';
|
|
import fs from 'fs/promises';
|
|
import path from 'path';
|
|
|
|
/**
|
|
* Serviço para geração e manipulação de arquivos PDF
|
|
*/
|
|
export class PdfService {
|
|
/**
|
|
* Cria um documento PDF básico
|
|
* @returns Documento PDF
|
|
*/
|
|
async criarDocumento() {
|
|
return await PDFDocument.create();
|
|
}
|
|
|
|
/**
|
|
* Carrega um documento PDF existente
|
|
* @param pdfBytes - Bytes do PDF
|
|
* @returns Documento PDF
|
|
*/
|
|
async carregarDocumento(pdfBytes: Uint8Array) {
|
|
return await PDFDocument.load(pdfBytes);
|
|
}
|
|
|
|
/**
|
|
* Adiciona uma página ao documento
|
|
* @param doc - Documento PDF
|
|
* @param tamanho - Tamanho da página (padrão: A4)
|
|
* @returns Página adicionada
|
|
*/
|
|
adicionarPagina(doc: any, tamanho = [595.28, 841.89]) {
|
|
return doc.addPage(tamanho);
|
|
}
|
|
|
|
/**
|
|
* Salva o documento como buffer
|
|
* @param doc - Documento PDF
|
|
* @returns Buffer do PDF
|
|
*/
|
|
async salvarComoBuffer(doc: any): Promise<Buffer> {
|
|
const pdfBytes = await doc.save();
|
|
return Buffer.from(pdfBytes);
|
|
}
|
|
|
|
/**
|
|
* Carrega uma fonte padrão
|
|
* @param doc - Documento PDF
|
|
* @param fonte - Nome da fonte padrão
|
|
* @returns Fonte carregada
|
|
*/
|
|
async carregarFonte(doc: any, fonte: StandardFonts) {
|
|
return await doc.embedFont(fonte);
|
|
}
|
|
|
|
/**
|
|
* Desenha texto em uma página
|
|
* @param pagina - Página do PDF
|
|
* @param texto - Texto a ser desenhado
|
|
* @param x - Posição X
|
|
* @param y - Posição Y
|
|
* @param fonte - Fonte a ser usada
|
|
* @param tamanho - Tamanho da fonte
|
|
* @param cor - Cor do texto (padrão: preto)
|
|
*/
|
|
desenharTexto(
|
|
pagina: any,
|
|
texto: string,
|
|
x: number,
|
|
y: number,
|
|
fonte: any,
|
|
tamanho: number,
|
|
cor = rgb(0, 0, 0)
|
|
) {
|
|
pagina.drawText(texto, {
|
|
x,
|
|
y,
|
|
font: fonte,
|
|
size: tamanho,
|
|
color: cor,
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Cria um cabeçalho para o documento
|
|
* @param pagina - Página do PDF
|
|
* @param titulo - Título do cabeçalho
|
|
* @param fonte - Fonte a ser usada
|
|
* @param margemSuperior - Margem superior
|
|
* @param margem - Margem lateral
|
|
* @returns Posição Y após o cabeçalho
|
|
*/
|
|
criarCabecalho(
|
|
pagina: any,
|
|
titulo: string,
|
|
fonte: any,
|
|
margemSuperior: number,
|
|
margem: number
|
|
): number {
|
|
const yPos = pagina.getHeight() - margemSuperior;
|
|
|
|
this.desenharTexto(
|
|
pagina,
|
|
titulo,
|
|
margem,
|
|
yPos,
|
|
fonte,
|
|
18,
|
|
rgb(0, 0, 0.7)
|
|
);
|
|
|
|
// Linha separadora
|
|
pagina.drawLine({
|
|
start: { x: margem, y: yPos - 10 },
|
|
end: { x: pagina.getWidth() - margem, y: yPos - 10 },
|
|
thickness: 1,
|
|
color: rgb(0, 0, 0.5),
|
|
});
|
|
|
|
return yPos - 30; // Retorna a posição Y após o cabeçalho
|
|
}
|
|
|
|
/**
|
|
* Cria um rodapé para o documento
|
|
* @param pagina - Página do PDF
|
|
* @param texto - Texto do rodapé
|
|
* @param fonte - Fonte a ser usada
|
|
* @param margem - Margem
|
|
*/
|
|
criarRodape(pagina: any, texto: string, fonte: any, margem: number) {
|
|
const yPos = margem / 2;
|
|
|
|
this.desenharTexto(
|
|
pagina,
|
|
texto,
|
|
margem,
|
|
yPos,
|
|
fonte,
|
|
8,
|
|
rgb(0.5, 0.5, 0.5)
|
|
);
|
|
}
|
|
|
|
private async getConfiguracao() {
|
|
try {
|
|
// Buscar configuração ou usar valores padrão
|
|
const config = await prisma.configuracaoDocumento.findFirst({
|
|
orderBy: { criadoEm: 'desc' },
|
|
select: {
|
|
id: true,
|
|
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 e dados do escritório
|
|
* @param conteudo - Conteúdo HTML para o PDF
|
|
* @param escritorio - Dados do escritório para substituir no template
|
|
* @returns Buffer contendo o PDF gerado
|
|
*/
|
|
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;
|
|
|
|
console.log(`Iniciando geração de PDF ${temTimbrado ? 'com' : 'sem'} timbrado...`);
|
|
|
|
// Se temos timbrado, vamos primeiro verificar se ele existe
|
|
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));
|
|
}
|
|
|
|
console.log('Verificando timbrado em:', timbradoPath);
|
|
|
|
try {
|
|
await fs.access(timbradoPath);
|
|
timbradoExists = true;
|
|
console.log('Timbrado encontrado');
|
|
} catch (e) {
|
|
console.error('Timbrado não encontrado:', e);
|
|
}
|
|
}
|
|
|
|
// Margens definidas no template ou padrão
|
|
const margens = config.margensTemplate || {
|
|
top: config.timbradoMarginTop || 100,
|
|
left: config.timbradoMarginLeft || 50,
|
|
right: config.timbradoMarginRight || 50,
|
|
bottom: config.timbradoMarginBottom || 50
|
|
};
|
|
|
|
console.log('Usando margens:', margens);
|
|
|
|
// Abordagem focada em PDF de alta qualidade com formatação precisa
|
|
try {
|
|
console.log('Gerando PDF com formatação avançada...');
|
|
|
|
// 1. Primeiro carregar o timbrado se existir
|
|
let pdfDoc;
|
|
const fontSize = 11;
|
|
const lineHeight = fontSize * 1.5; // Espaçamento entre linhas um pouco maior para melhor legibilidade
|
|
const pageWidth = 595;
|
|
const pageHeight = 842;
|
|
|
|
if (timbradoExists) {
|
|
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');
|
|
|
|
// Verificar se o timbrado tem páginas
|
|
if (pdfDoc.getPageCount() === 0) {
|
|
console.log('Timbrado não contém páginas, adicionando página padrão');
|
|
pdfDoc.addPage([pageWidth, pageHeight]);
|
|
}
|
|
} catch (loadError) {
|
|
console.error('Erro ao carregar timbrado:', loadError);
|
|
// Se falhar ao carregar o timbrado, criar novo documento
|
|
pdfDoc = await PDFDocument.create();
|
|
pdfDoc.addPage([pageWidth, pageHeight]);
|
|
}
|
|
} else {
|
|
console.log('Criando novo documento sem timbrado...');
|
|
pdfDoc = await PDFDocument.create();
|
|
pdfDoc.addPage([pageWidth, pageHeight]);
|
|
}
|
|
|
|
// 2. Carregar fontes
|
|
console.log('Carregando fontes...');
|
|
let font, boldFont, italicFont;
|
|
|
|
try {
|
|
// Verificar se temos a fonte Fira Sans disponível
|
|
const firaSansPath = path.join(process.cwd(), 'public', 'fonts', 'FiraSans-Regular.ttf');
|
|
const firaSansBoldPath = path.join(process.cwd(), 'public', 'fonts', 'FiraSans-Bold.ttf');
|
|
|
|
// Verificar se o arquivo existe
|
|
let firaSansExists = false;
|
|
try {
|
|
await fs.access(firaSansPath);
|
|
firaSansExists = true;
|
|
console.log('Fonte Fira Sans encontrada, utilizando-a para o documento');
|
|
} catch (e) {
|
|
console.log('Fonte Fira Sans não encontrada, usando Helvetica como fallback');
|
|
}
|
|
|
|
if (firaSansExists) {
|
|
// Carregar as fontes Fira Sans
|
|
try {
|
|
const firaSansBytes = await fs.readFile(firaSansPath);
|
|
font = await pdfDoc.embedFont(firaSansBytes);
|
|
|
|
try {
|
|
const firaSansBoldBytes = await fs.readFile(firaSansBoldPath);
|
|
boldFont = await pdfDoc.embedFont(firaSansBoldBytes);
|
|
} catch (e) {
|
|
console.log('Fira Sans Bold não encontrada, usando regular como fallback');
|
|
boldFont = font;
|
|
}
|
|
|
|
// Não temos itálico, usar regular
|
|
italicFont = font;
|
|
} catch (fontError) {
|
|
console.error('Erro ao carregar Fira Sans:', fontError);
|
|
throw fontError; // Forçar fallback para Helvetica
|
|
}
|
|
} else {
|
|
throw new Error('Fira Sans não encontrada');
|
|
}
|
|
} catch (error) {
|
|
// Fallback para Helvetica
|
|
console.log('Usando Helvetica como fallback');
|
|
font = await pdfDoc.embedFont(StandardFonts.Helvetica);
|
|
boldFont = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
|
|
italicFont = await pdfDoc.embedFont(StandardFonts.HelveticaOblique);
|
|
}
|
|
|
|
// 3. Processar e formatar o HTML com preservação de estrutura
|
|
console.log('Processando HTML com preservação de estrutura...');
|
|
|
|
// Processar variáveis
|
|
const processedContent = this.processarTemplate(conteudo, escritorio);
|
|
|
|
// Função melhorada para decodificar entidades HTML
|
|
const decodeHtmlEntities = (text: string): string => {
|
|
// Criar um elemento temporário para decodificar as entidades HTML corretamente
|
|
if (typeof text !== 'string') return '';
|
|
|
|
// Lista ampliada de entidades HTML comuns em português
|
|
const entities: Record<string, string> = {
|
|
" ": " ", "&": "&", "<": "<", ">": ">", """: "\"", "'": "'",
|
|
"¢": "¢", "£": "£", "¥": "¥", "€": "€", "©": "©", "®": "®",
|
|
"À": "À", "à": "à", "Á": "Á", "á": "á",
|
|
"Â": "Â", "â": "â", "Ã": "Ã", "ã": "ã",
|
|
"Ä": "Ä", "ä": "ä", "Å": "Å", "å": "å",
|
|
"Æ": "Æ", "æ": "æ", "Ç": "Ç", "ç": "ç",
|
|
"È": "È", "è": "è", "É": "É", "é": "é",
|
|
"Ê": "Ê", "ê": "ê", "Ë": "Ë", "ë": "ë",
|
|
"Ì": "Ì", "ì": "ì", "Í": "Í", "í": "í",
|
|
"Î": "Î", "î": "î", "Ï": "Ï", "ï": "ï",
|
|
"Ð": "Ð", "ð": "ð", "Ñ": "Ñ", "ñ": "ñ",
|
|
"Ò": "Ò", "ò": "ò", "Ó": "Ó", "ó": "ó",
|
|
"Ô": "Ô", "ô": "ô", "Õ": "Õ", "õ": "õ",
|
|
"Ö": "Ö", "ö": "ö", "Ø": "Ø", "ø": "ø",
|
|
"Ù": "Ù", "ù": "ù", "Ú": "Ú", "ú": "ú",
|
|
"Û": "Û", "û": "û", "Ü": "Ü", "ü": "ü",
|
|
"Ý": "Ý", "ý": "ý", "ÿ": "ÿ", "ß": "ß"
|
|
};
|
|
|
|
// Substituir todas as entidades HTML conhecidas
|
|
let decoded = text;
|
|
for (const [entity, char] of Object.entries(entities)) {
|
|
decoded = decoded.split(entity).join(char);
|
|
}
|
|
|
|
// Usar expressão regular para capturar entidades numéricas
|
|
return decoded.replace(/&#(\d+);/g, (_, dec) => String.fromCharCode(parseInt(dec, 10)));
|
|
};
|
|
|
|
// Uma abordagem completamente nova para processar HTML
|
|
// Usando a biblioteca puppeteer para renderizar HTML com alta fidelidade
|
|
const converterHtmlParaPdf = async (htmlContent: string): Promise<Buffer> => {
|
|
console.log('Usando Puppeteer para renderização de alta fidelidade...');
|
|
|
|
try {
|
|
// Garantir que o HTML tenha metadados de codificação adequados
|
|
const completeHtml = `
|
|
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<style>
|
|
body {
|
|
font-family: Arial, Helvetica, sans-serif;
|
|
font-size: 11pt;
|
|
line-height: 1.5;
|
|
margin: ${margens.top}px ${margens.right}px ${margens.bottom}px ${margens.left}px;
|
|
text-align: justify;
|
|
}
|
|
p {
|
|
margin: 0 0 0.5em 0;
|
|
text-align: justify;
|
|
}
|
|
h1, h2, h3, h4, h5, h6 {
|
|
margin-top: 1em;
|
|
margin-bottom: 0.5em;
|
|
}
|
|
strong, b {
|
|
font-weight: bold;
|
|
}
|
|
em, i {
|
|
font-style: italic;
|
|
}
|
|
u {
|
|
text-decoration: underline;
|
|
}
|
|
.justify {
|
|
text-align: justify;
|
|
}
|
|
.indent {
|
|
text-indent: 2em;
|
|
}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
${htmlContent}
|
|
</body>
|
|
</html>
|
|
`;
|
|
|
|
// Iniciar navegador headless
|
|
const browser = await puppeteer.launch({
|
|
args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage'],
|
|
headless: true
|
|
});
|
|
|
|
try {
|
|
const page = await browser.newPage();
|
|
await page.setContent(completeHtml, { waitUntil: 'networkidle0' });
|
|
|
|
// Definir o tamanho da página para A4
|
|
await page.setViewport({ width: pageWidth, height: pageHeight });
|
|
|
|
// Se tiver timbrado, usamos a abordagem pdf-lib + Puppeteer
|
|
if (timbradoExists) {
|
|
// Gerar PDF temporário sem timbrado
|
|
const tmpPdfBuffer = await page.pdf({
|
|
format: 'A4',
|
|
printBackground: true,
|
|
margin: {
|
|
top: '0',
|
|
right: '0',
|
|
bottom: '0',
|
|
left: '0'
|
|
}
|
|
});
|
|
|
|
// Carregar o PDF gerado pelo Puppeteer
|
|
const contentPdf = await PDFDocument.load(tmpPdfBuffer);
|
|
|
|
// Combinar com o timbrado
|
|
const combinedPdf = await PDFDocument.create();
|
|
|
|
// Para cada página do conteúdo
|
|
for (let i = 0; i < contentPdf.getPageCount(); i++) {
|
|
// Copiar a página do timbrado
|
|
const [timbradoPage] = await combinedPdf.copyPages(pdfDoc, [0]);
|
|
const page = combinedPdf.addPage(timbradoPage);
|
|
|
|
// Copiar o conteúdo sobre o timbrado
|
|
const [contentPage] = await combinedPdf.copyPages(contentPdf, [i]);
|
|
page.drawPage(contentPage, {
|
|
x: 0, y: 0,
|
|
width: page.getWidth(),
|
|
height: page.getHeight(),
|
|
opacity: 1
|
|
});
|
|
}
|
|
|
|
const combinedBytes = await combinedPdf.save();
|
|
return Buffer.from(combinedBytes);
|
|
} else {
|
|
// Gerar PDF direto do Puppeteer
|
|
return await page.pdf({
|
|
format: 'A4',
|
|
printBackground: true,
|
|
margin: {
|
|
top: `${margens.top}px`,
|
|
right: `${margens.right}px`,
|
|
bottom: `${margens.bottom}px`,
|
|
left: `${margens.left}px`
|
|
}
|
|
});
|
|
}
|
|
} finally {
|
|
await browser.close();
|
|
}
|
|
} catch (puppeteerError) {
|
|
console.error('Erro ao renderizar com Puppeteer:', puppeteerError);
|
|
|
|
// Método de fallback simplificado e à prova de falhas
|
|
console.log('Usando método de fallback simplificado...');
|
|
|
|
try {
|
|
// Criar um novo documento PDF do zero
|
|
const fallbackPdf = await PDFDocument.create();
|
|
let fallbackPage = fallbackPdf.addPage([pageWidth, pageHeight]);
|
|
|
|
// Definir variáveis locais para esse método
|
|
const fallbackFont = await fallbackPdf.embedFont(StandardFonts.Helvetica);
|
|
const fallbackBoldFont = await fallbackPdf.embedFont(StandardFonts.HelveticaBold);
|
|
let fallbackY = pageHeight - margens.top;
|
|
const fallbackSize = 11;
|
|
const fallbackLineHeight = fallbackSize * 1.5;
|
|
|
|
// Decodificar e limpar o HTML
|
|
const fallbackText = htmlContent
|
|
.replace(/<[^>]*>/g, ' ')
|
|
.replace(/&[a-zA-Z]+;/g, ' ')
|
|
.replace(/\s+/g, ' ')
|
|
.trim();
|
|
|
|
// Titulo do documento
|
|
fallbackPage.drawText('Documento gerado pelo sistema', {
|
|
x: margens.left,
|
|
y: fallbackY,
|
|
font: fallbackBoldFont,
|
|
size: fallbackSize + 2
|
|
});
|
|
|
|
// Adicionar texto simples em linhas
|
|
let currentY = fallbackY - fallbackLineHeight * 2;
|
|
const maxCharsPerLine = 80;
|
|
|
|
// Dividir texto em linhas sem exceder a largura disponível
|
|
for (let i = 0; i < fallbackText.length; i += maxCharsPerLine) {
|
|
const line = fallbackText.substring(i, i + maxCharsPerLine);
|
|
|
|
// Verificar se ainda há espaço na página
|
|
if (currentY < margens.bottom) {
|
|
const newPage = fallbackPdf.addPage([pageWidth, pageHeight]);
|
|
fallbackPage = newPage;
|
|
currentY = pageHeight - margens.top;
|
|
}
|
|
|
|
fallbackPage.drawText(line, {
|
|
x: margens.left,
|
|
y: currentY,
|
|
font: fallbackFont,
|
|
size: fallbackSize
|
|
});
|
|
|
|
currentY -= fallbackLineHeight;
|
|
}
|
|
|
|
// Adicionar rodapé com data e hora
|
|
fallbackPage.drawText(`Gerado em: ${new Date().toLocaleString('pt-BR')}`, {
|
|
x: margens.left,
|
|
y: margens.bottom,
|
|
font: fallbackFont,
|
|
size: 8,
|
|
color: rgb(0.5, 0.5, 0.5)
|
|
});
|
|
|
|
const fallbackBytes = await fallbackPdf.save();
|
|
return Buffer.from(fallbackBytes);
|
|
} catch (fallbackError) {
|
|
console.error('Erro no método de fallback:', fallbackError);
|
|
|
|
// Último recurso: PDF mínimo com texto simples
|
|
try {
|
|
const minimalPdf = await PDFDocument.create();
|
|
const minimalPage = minimalPdf.addPage();
|
|
const minimalFont = await minimalPdf.embedFont(StandardFonts.Helvetica);
|
|
|
|
minimalPage.drawText('Falha ao gerar documento. Contate o suporte.', {
|
|
x: 50,
|
|
y: minimalPage.getHeight() - 50,
|
|
font: minimalFont,
|
|
size: 12
|
|
});
|
|
|
|
const minimalBytes = await minimalPdf.save();
|
|
return Buffer.from(minimalBytes);
|
|
} catch (criticalError) {
|
|
console.error('Falha crítica na geração do PDF:', criticalError);
|
|
|
|
// Se chegou aqui, vamos retornar um PDF vazio
|
|
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'
|
|
);
|
|
}
|
|
}
|
|
}
|
|
};
|
|
|
|
// Gerar PDF de alta fidelidade com Puppeteer
|
|
const pdfBytes = await converterHtmlParaPdf(processedContent);
|
|
console.log(`PDF gerado com sucesso: ${pdfBytes.length} bytes`);
|
|
return pdfBytes;
|
|
} catch (error) {
|
|
console.error('Erro ao gerar PDF:', error);
|
|
throw error;
|
|
}
|
|
} 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;
|
|
});
|
|
}
|
|
}
|