diff --git a/src/server/services/PdfService.ts b/src/server/services/PdfService.ts index fbee94b..65db0cb 100644 --- a/src/server/services/PdfService.ts +++ b/src/server/services/PdfService.ts @@ -247,6 +247,115 @@ export class PdfService { const LINE_HEIGHT = FONT_SIZE * 1.5; const MAX_WIDTH = PAGE_WIDTH - margens.left - margens.right; + // Função para decodificar entidades HTML comuns (acentuação e outros) + function decodeHtmlEntities(str: string): string { + if (!str) return ''; + return str + // Acentos minúsculos e maiúsculos + .replace(/Á/g, 'Á').replace(/á/g, 'á') + .replace(/É/g, 'É').replace(/é/g, 'é') + .replace(/Í/g, 'Í').replace(/í/g, 'í') + .replace(/Ó/g, 'Ó').replace(/ó/g, 'ó') + .replace(/Ú/g, 'Ú').replace(/ú/g, 'ú') + .replace(/À/g, 'À').replace(/à/g, 'à') + .replace(/È/g, 'È').replace(/è/g, 'è') + .replace(/Ì/g, 'Ì').replace(/ì/g, 'ì') + .replace(/Ò/g, 'Ò').replace(/ò/g, 'ò') + .replace(/Ù/g, 'Ù').replace(/ù/g, 'ù') + .replace(/Â/g, 'Â').replace(/â/g, 'â') + .replace(/Ê/g, 'Ê').replace(/ê/g, 'ê') + .replace(/Î/g, 'Î').replace(/î/g, 'î') + .replace(/Ô/g, 'Ô').replace(/ô/g, 'ô') + .replace(/Û/g, 'Û').replace(/û/g, 'û') + .replace(/Ã/g, 'Ã').replace(/ã/g, 'ã') + .replace(/Õ/g, 'Õ').replace(/õ/g, 'õ') + .replace(/Ç/g, 'Ç').replace(/ç/g, 'ç') + .replace(/Ñ/g, 'Ñ').replace(/ñ/g, 'ñ') + .replace(/Ü/g, 'Ü').replace(/ü/g, 'ü') + // Outras entidades comuns + .replace(/ /gi, ' ') + .replace(/&/gi, '&') + .replace(/"/gi, '"') + .replace(/'/g, "'") + .replace(/</gi, '<') + .replace(/>/gi, '>') + .replace(/–/gi, '–') + .replace(/—/gi, '—') + .replace(/(\d+);/g, (m, code) => String.fromCharCode(code)); + } + + // Função para converter HTML do TinyMCE em uma árvore de blocos com estilos + function parseHtmlToBlocks(html: string): any[] { + // Usa DOMParser se disponível, senão fallback simples + let doc: Document; + try { + const { JSDOM } = require('jsdom'); + doc = new JSDOM(`
${html}`).window.document; + } catch { + // fallback: ignora tags e retorna texto puro + return [{ text: html, tag: 'p', styles: {} }]; + } + const blocks: any[] = []; + function parseNode(node: Node, parentStyles: any = {}) { + if (node.nodeType === 3) { // Text + let text = decodeHtmlEntities(node.textContent || ''); + if (text.trim() !== '' || parentStyles['pre']) { + blocks.push({ text, tag: parentStyles.tag || 'span', styles: { ...parentStyles } }); + } + return; + } + if (node.nodeType !== 1) return; // Element + const el = node as HTMLElement; + let styles = { ...parentStyles }; + let tag = el.tagName.toLowerCase(); + + // TinyMCE: , , + if (el.style) { + if (el.style.fontWeight === 'bold' || tag === 'b' || tag === 'strong') styles.bold = true; + if (el.style.fontStyle === 'italic' || tag === 'i' || tag === 'em') styles.italic = true; + if (el.style.textDecoration?.includes('underline') || tag === 'u') styles.underline = true; + if (el.style.textAlign === 'center' || tag === 'center') styles.align = 'center'; + if (el.style.textAlign === 'right') styles.align = 'right'; + if (el.style.textIndent) styles.indent = true; + if (el.style.fontFamily) styles.fontFamily = el.style.fontFamily; + } + if (tag === 'b' || tag === 'strong') styles.bold = true; + if (tag === 'i' || tag === 'em') styles.italic = true; + if (tag === 'u') styles.underline = true; + if (tag === 'center') styles.align = 'center'; + if (tag === 'pre') styles.pre = true; + if (tag === 'p' && el.style.textAlign === 'center') styles.align = 'center'; + if (tag === 'p' && el.style.textAlign === 'right') styles.align = 'right'; + if (tag === 'p' && el.style.textIndent) styles.indent = true; + if (tag === 'h1' || tag === 'h2' || tag === 'h3' || tag === 'h4' || tag === 'h5' || tag === 'h6') styles.heading = tag; + if (tag === 'ul' || tag === 'ol') styles.list = tag; + if (tag === 'li') styles.listItem = true; + + // Blocos de texto + if (['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li', 'pre', 'div', 'center'].includes(tag)) { + let blockText = ''; + el.childNodes.forEach(child => { + if (child.nodeType === 3) blockText += child.textContent; + }); + if (blockText.trim() !== '' || styles['pre']) { + blocks.push({ text: blockText, tag, styles: { ...styles } }); + } + el.childNodes.forEach(child => parseNode(child, styles)); + if (tag === 'li') blocks.push({ text: '', tag: 'br', styles: {} }); + return; + } + // Quebra de linha + if (tag === 'br') { + blocks.push({ text: '', tag: 'br', styles: { ...styles } }); + return; + } + // Span ou inline + el.childNodes.forEach(child => parseNode(child, styles)); + } + doc.body.childNodes.forEach(node => parseNode(node)); + return blocks; + } + // Carregar o timbrado (se houver) e criar o PDF final let timbradoPdf: PDFDocument | null = null; let timbradoPageCount = 0; @@ -257,6 +366,7 @@ export class PdfService { const timbradoBytes = await fs.readFile(timbradoPath); timbradoPdf = await PDFDocument.load(timbradoBytes); timbradoPageCount = timbradoPdf.getPageCount(); + // Copiar as páginas do timbrado como EMBEDDED PAGE (PDFEmbeddedPage) timbradoPages = []; for (let i = 0; i < timbradoPageCount; i++) { const [embedded] = await pdfDoc.embedPages([timbradoPdf.getPage(i)]); @@ -266,6 +376,7 @@ export class PdfService { // Fonte Fira Sans (se disponível), senão Helvetica let font = null, fontBold = null, fontItalic = null, fontBoldItalic = null; + let useCustomFont = false; try { const firaPath = path.join(process.cwd(), 'public', 'fonts', 'FiraSans-Regular.ttf'); const firaBoldPath = path.join(process.cwd(), 'public', 'fonts', 'FiraSans-Bold.ttf'); @@ -277,7 +388,7 @@ export class PdfService { fs.readFile(firaItalicPath).catch(() => null), fs.readFile(firaBoldItalicPath).catch(() => null), ]); - if (fira) font = await pdfDoc.embedFont(fira); + if (fira) { font = await pdfDoc.embedFont(fira); useCustomFont = true; } if (firaBoldBuf) fontBold = await pdfDoc.embedFont(firaBoldBuf); if (firaItalicBuf) fontItalic = await pdfDoc.embedFont(firaItalicBuf); if (firaBoldItalicBuf) fontBoldItalic = await pdfDoc.embedFont(firaBoldItalicBuf); @@ -287,107 +398,7 @@ export class PdfService { if (!fontItalic) fontItalic = await pdfDoc.embedFont(StandardFonts.HelveticaOblique); if (!fontBoldItalic) fontBoldItalic = fontBold; - // --- PARSER HTML TinyMCE INLINE E BLOCOS (LEGADO MELHORADO) --- - // Suporte a blocos, alinhamento, recuo, negrito, itálico, sublinhado, listas, títulos, font-family, centralização, tags inline - function parseHtmlToBlocks(html: string): any[] { - // Normaliza blocos - html = html.replace(/'); - html = html.replace(/
'); - html = html.replace(/<\/div>/gi, '
'); - html = html.replace(/]*)>(.*?)<\/p>$/i); - if (pMatch) { - let styles: any = {}; - let styleAttr = pMatch[1]; - if (/text-align:\s*center/i.test(styleAttr)) styles.align = 'center'; - if (/text-align:\s*right/i.test(styleAttr)) styles.align = 'right'; - if (/text-indent:\s*2em/i.test(styleAttr)) styles.indent = true; - if (/font-family:\s*['"]?Fira Sans/i.test(styleAttr)) styles.fontFamily = 'Fira Sans'; - blocks.push({ inlines: parseInline(pMatch[2]), tag: 'p', styles }); - continue; - } - // Centralizado - let centerMatch = line.match(/^