From f310f079873adf252c349cb357b15d6c2e0836aa Mon Sep 17 00:00:00 2001 From: Rodrigo Martins Date: Mon, 21 Apr 2025 19:52:13 -0300 Subject: [PATCH] tenta fix pdfservice.js --- src/server/services/PdfService.ts | 89 ++++++++++++++++++++----------- 1 file changed, 59 insertions(+), 30 deletions(-) diff --git a/src/server/services/PdfService.ts b/src/server/services/PdfService.ts index 370ff99..3d4c740 100644 --- a/src/server/services/PdfService.ts +++ b/src/server/services/PdfService.ts @@ -286,30 +286,33 @@ export class PdfService { // Função para remover todas as tags HTML, exceto as de formatação suportadas function stripUnsupportedTags(html: string): string { - // Remove todas as tags, exceto , , , , ,
,

, - // Remove atributos de exceto text-indent + // Remove todas as tags, exceto , , , , ,
,

, , + // Remove atributos de exceto text-indent e text-align return html - // Remove spans que não são recuo - .replace(/])*?>/gi, '') + // Mantém apenas com text-indent ou text-align:center + .replace(/])*?>/gi, '') // Remove atributos de , , , , ,

.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 + // Remove spans sem text-indent ou text-align .replace(/(.*?)<\/span>/gi, '$1') // Remove comentários HTML .replace(//g, ''); } // Processar variáveis do template e decodificar entidades HTML - // Mantém tags , , , , ,
,

, + // Mantém tags , , , , ,
,

, , const texto = decodeHtmlEntities( stripUnsupportedTags( this.processarTemplate(conteudo, escritorio) .replace(//gi, '\n') .replace(/<\/p>/gi, '\n\n') .replace(/]*>/gi, '') // Remove apenas a tag de abertura

- .replace(/]*text-indent[^>]*>/gi, '§§INDENT§§') // Marca recuo de parágrafo + // Marca recuo de parágrafo + .replace(/]*text-indent[^>]*>/gi, '§§INDENT§§') + // Marca centralização + .replace(/]*text-align\s*:\s*center[^>]*>/gi, '§§CENTER§§') .replace(/<\/span>/gi, '') .replace(/\r\n/g, '\n') .replace(/\r/g, '\n') @@ -325,15 +328,20 @@ export class PdfService { function wrapTextStyled(text: string, font: any, fontSize: number, maxWidth: number) { // Mantém quebras de linha simples para espaçamento const rawLines = text.split('\n'); - const lines: { text: string, bold: boolean, italic: boolean, underline: boolean, indent: boolean }[] = []; + const lines: { text: string, bold: boolean, italic: boolean, underline: boolean, indent: boolean, center: boolean }[] = []; for (const rawLine of rawLines) { let line = rawLine; - let bold = false, italic = false, underline = false, indent = false; + let bold = false, italic = false, underline = false, indent = false, center = false; // Detecta recuo de parágrafo if (line.startsWith('§§INDENT§§')) { indent = true; line = line.replace('§§INDENT§§', '').trimStart(); } + // Detecta centralização + if (line.startsWith('§§CENTER§§')) { + center = true; + line = line.replace('§§CENTER§§', '').trimStart(); + } // Detecta negrito, itálico, sublinhado (apenas no início e fim da linha) if (/^|^/.test(line)) { bold = true; line = line.replace(/^|^/, ''); } if (/^|^/.test(line)) { italic = true; line = line.replace(/^|^/, ''); } @@ -346,17 +354,19 @@ export class PdfService { // Quebra em palavras para justificar const words = line.split(' '); let currentLine = ''; - for (const word of words) { - const testLine = currentLine ? currentLine + ' ' + word : word; + for (let i = 0; i < words.length; i++) { + const word = words[i]; + // Garante que múltiplos espaços sejam preservados + const testLine = currentLine ? currentLine + (words[i - 1] === '' ? ' ' : ' ') + word : word; const width = font.widthOfTextAtSize(testLine, fontSize); if (width > maxWidth && currentLine) { - lines.push({ text: currentLine, bold, italic, underline, indent }); + lines.push({ text: currentLine, bold, italic, underline, indent, center }); currentLine = word; } else { currentLine = testLine; } } - if (currentLine) lines.push({ text: currentLine, bold, italic, underline, indent }); + if (currentLine) lines.push({ text: currentLine, bold, italic, underline, indent, center }); } return lines; } @@ -381,8 +391,23 @@ export class PdfService { pdfDoc = await PDFDocument.create(); } - // Fonte - const font = await pdfDoc.embedFont(StandardFonts.Helvetica); + // Fonte Fira Sans (se disponível), senão Helvetica + let font = await pdfDoc.embedFont(StandardFonts.Helvetica); + let fontBold = font, fontItalic = font; + try { + // Tenta carregar Fira Sans se estiver disponível no projeto + const firaPath = path.join(process.cwd(), 'public', 'fonts', 'FiraSans-Regular.ttf'); + const firaBoldPath = path.join(process.cwd(), 'public', 'fonts', 'FiraSans-Bold.ttf'); + const firaItalicPath = path.join(process.cwd(), 'public', 'fonts', 'FiraSans-Italic.ttf'); + const [fira, firaBold, firaItalic] = await Promise.all([ + fs.readFile(firaPath).catch(() => null), + fs.readFile(firaBoldPath).catch(() => null), + fs.readFile(firaItalicPath).catch(() => null), + ]); + if (fira) font = await pdfDoc.embedFont(fira); + if (firaBold) fontBold = await pdfDoc.embedFont(firaBold); + if (firaItalic) fontItalic = await pdfDoc.embedFont(firaItalic); + } catch { /* fallback para Helvetica */ } // Quebrar o texto em páginas let currentPar = 0; @@ -414,23 +439,27 @@ export class PdfService { currentLine = lineIdx; break; } - // Justificado: calcula espaçamento extra entre palavras (exceto última linha do parágrafo) - let { text, bold, italic, underline, indent } = styledLines[lineIdx]; + let { text, bold, italic, underline, indent, center } = styledLines[lineIdx]; let x = margens.left + (indent ? FONT_SIZE * 2 : 0); + let usedFont = bold ? fontBold : italic ? fontItalic : font; let options: any = { x, y, size: FONT_SIZE, - font: bold ? await pdfDoc.embedFont(StandardFonts.HelveticaBold) - : italic ? await pdfDoc.embedFont(StandardFonts.HelveticaOblique) - : font + font: usedFont }; - // Justificar (exceto última linha do parágrafo) - if (text.trim().length > 0 && lineIdx < styledLines.length - 1) { + // Centralizado + if (center) { + const textWidth = usedFont.widthOfTextAtSize(text, FONT_SIZE); + options.x = margens.left + ((MAX_WIDTH - textWidth) / 2); + page.drawText(text, options); + } + // Justificado (exceto última linha do parágrafo e centralizado) + else if (text.trim().length > 0 && lineIdx < styledLines.length - 1 && !center) { const words = text.split(' '); if (words.length > 1) { - const textWidth = options.font.widthOfTextAtSize(text, FONT_SIZE); - const spaceWidth = options.font.widthOfTextAtSize(' ', FONT_SIZE); + const textWidth = usedFont.widthOfTextAtSize(text, FONT_SIZE); + const spaceWidth = usedFont.widthOfTextAtSize(' ', FONT_SIZE); const totalSpaces = words.length - 1; const extraSpace = (MAX_WIDTH - (indent ? FONT_SIZE * 2 : 0) - textWidth) / totalSpaces; let cursor = x; @@ -439,24 +468,24 @@ export class PdfService { x: cursor, y, size: FONT_SIZE, - font: options.font + font: usedFont }); if (w < words.length - 1) { - cursor += options.font.widthOfTextAtSize(words[w], FONT_SIZE) + spaceWidth + extraSpace; + cursor += usedFont.widthOfTextAtSize(words[w], FONT_SIZE) + spaceWidth + extraSpace; } } } else { page.drawText(text, options); } - } else { + } else if (!center) { page.drawText(text, options); } // Sublinhado if (underline) { - const textWidth = options.font.widthOfTextAtSize(text, FONT_SIZE); + const textWidth = usedFont.widthOfTextAtSize(text, FONT_SIZE); page.drawLine({ - start: { x, y: y - 2 }, - end: { x: x + textWidth, y: y - 2 }, + start: { x: options.x, y: y - 2 }, + end: { x: options.x + textWidth, y: y - 2 }, thickness: 0.7, color: rgb(0, 0, 0) });