From fb17405fe9de06a035fbd8cc8836e38b846051a9 Mon Sep 17 00:00:00 2001 From: Rodrigo Martins Date: Mon, 21 Apr 2025 20:47:49 -0300 Subject: [PATCH] tenta fix pdfservice.js --- src/server/services/PdfService.ts | 148 ++++++++++++++---------------- 1 file changed, 71 insertions(+), 77 deletions(-) diff --git a/src/server/services/PdfService.ts b/src/server/services/PdfService.ts index 3d4c740..c5724e3 100644 --- a/src/server/services/PdfService.ts +++ b/src/server/services/PdfService.ts @@ -324,49 +324,65 @@ export class PdfService { // Quebra o texto em parágrafos (mantendo quebras de linha duplas como parágrafo) const paragrafos = texto.split(/\n{2,}/).map(p => p.trim()).filter(Boolean); + // Fonte Times New Roman (se disponível), senão Helvetica + let font = null, fontBold = null, fontItalic = null, fontBoldItalic = null; + try { + const timesPath = path.join(process.cwd(), 'public', 'fonts', 'TimesNewRoman.ttf'); + const timesBoldPath = path.join(process.cwd(), 'public', 'fonts', 'TimesNewRoman-Bold.ttf'); + const timesItalicPath = path.join(process.cwd(), 'public', 'fonts', 'TimesNewRoman-Italic.ttf'); + const timesBoldItalicPath = path.join(process.cwd(), 'public', 'fonts', 'TimesNewRoman-BoldItalic.ttf'); + const [times, timesBold, timesItalic, timesBoldItalic] = await Promise.all([ + fs.readFile(timesPath).catch(() => null), + fs.readFile(timesBoldPath).catch(() => null), + fs.readFile(timesItalicPath).catch(() => null), + fs.readFile(timesBoldItalicPath).catch(() => null), + ]); + if (times) font = await pdfDoc.embedFont(times); + if (timesBold) fontBold = await pdfDoc.embedFont(timesBold); + if (timesItalic) fontItalic = await pdfDoc.embedFont(timesItalic); + if (timesBoldItalic) fontBoldItalic = await pdfDoc.embedFont(timesBoldItalic); + } catch { /* fallback para Helvetica */ } + if (!font) font = await pdfDoc.embedFont(StandardFonts.TimesRoman); + if (!fontBold) fontBold = await pdfDoc.embedFont(StandardFonts.TimesBold); + if (!fontItalic) fontItalic = await pdfDoc.embedFont(StandardFonts.TimesItalic); + if (!fontBoldItalic) fontBoldItalic = fontBold; + // Função para quebrar texto em linhas respeitando largura máxima e manter quebras de linha simples - function wrapTextStyled(text: string, font: any, fontSize: number, maxWidth: number) { + function wrapTextStyled(text: string, font: any, fontBold: any, fontItalic: any, fontBoldItalic: any, fontSize: number, maxWidth: number, indent: boolean, align: string, bold: boolean, italic: boolean): { text: string, font: any, indent: boolean, align: string, bold: boolean, italic: boolean }[] { // 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, center: boolean }[] = []; + const lines: { text: string, font: any, indent: boolean, align: string, bold: boolean, italic: boolean }[] = []; for (const rawLine of rawLines) { let line = rawLine; - 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(/^|^/, ''); } - if (/^/.test(line)) { underline = true; line = line.replace(/^/, ''); } - if (/<\/b>$|<\/strong>$/.test(line)) { bold = true; line = line.replace(/<\/b>$|<\/strong>$/, ''); } - if (/<\/i>$|<\/em>$/.test(line)) { italic = true; line = line.replace(/<\/i>$|<\/em>$/, ''); } - if (/<\/u>$/.test(line)) { underline = true; line = line.replace(/<\/u>$/, ''); } - // Remove tags intermediárias (não suporta aninhamento) - line = line.replace(/<\/?(b|strong|i|em|u)>/gi, ''); + // Detecta negrito e itálico inline + let isBold = bold, isItalic = italic; + if (/^|^/.test(line)) { isBold = true; line = line.replace(/^|^/, ''); } + if (/^|^/.test(line)) { isItalic = true; line = line.replace(/^|^/, ''); } + if (/<\/b>$|<\/strong>$/.test(line)) { isBold = true; line = line.replace(/<\/b>$|<\/strong>$/, ''); } + if (/<\/i>$|<\/em>$/.test(line)) { isItalic = true; line = line.replace(/<\/i>$|<\/em>$/, ''); } + line = line.replace(/<\/?(b|strong|i|em)>/gi, ''); + + // Seleciona fonte correta + let usedFont = font; + if (isBold && isItalic && fontBoldItalic) usedFont = fontBoldItalic; + else if (isBold && fontBold) usedFont = fontBold; + else if (isItalic && fontItalic) usedFont = fontItalic; + // Quebra em palavras para justificar const words = line.split(' '); let currentLine = ''; 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); + const testLine = currentLine ? currentLine + ' ' + word : word; + const width = usedFont.widthOfTextAtSize(testLine, fontSize); if (width > maxWidth && currentLine) { - lines.push({ text: currentLine, bold, italic, underline, indent, center }); + lines.push({ text: currentLine, font: usedFont, indent, align, bold: isBold, italic: isItalic }); currentLine = word; } else { currentLine = testLine; } } - if (currentLine) lines.push({ text: currentLine, bold, italic, underline, indent, center }); + if (currentLine) lines.push({ text: currentLine, font: usedFont, indent, align, bold: isBold, italic: isItalic }); } return lines; } @@ -391,33 +407,13 @@ export class PdfService { pdfDoc = await PDFDocument.create(); } - // 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; let currentLine = 0; let pageIndex = 0; while (currentPar < paragrafos.length) { - // Adicionar página do timbrado ou em branco let page = pdfDoc.addPage([PAGE_WIDTH, PAGE_HEIGHT]); - // Desenhar o timbrado como fundo (usando embeddedPage) if (timbradoPages.length > 0) { const embedded = timbradoPages[pageIndex % timbradoPages.length]; page.drawPage(embedded, { @@ -429,9 +425,18 @@ export class PdfService { } let y = PAGE_HEIGHT - margens.top; let firstLine = true; - // Escrever texto na página while (currentPar < paragrafos.length) { - const styledLines = wrapTextStyled(paragrafos[currentPar], font, FONT_SIZE, MAX_WIDTH); + // Detecta recuo e alinhamento por marcação + let indent = paragrafos[currentPar].startsWith('§§INDENT§§'); + let center = paragrafos[currentPar].startsWith('§§CENTER§§'); + let align = center ? 'center' : 'justify'; + let text = paragrafos[currentPar].replace(/^§§INDENT§§/, '').replace(/^§§CENTER§§/, '').trim(); + + // Detecta negrito/itálico no parágrafo inteiro + let bold = /^|^/.test(text); + let italic = /^|^/.test(text); + + const styledLines = wrapTextStyled(text, font, fontBold, fontItalic, fontBoldItalic, FONT_SIZE, MAX_WIDTH - (indent ? FONT_SIZE * 2 : 0), indent, align, bold, italic); let lineIdx = 0; if (currentLine > 0) lineIdx = currentLine; for (; lineIdx < styledLines.length; lineIdx++) { @@ -439,23 +444,23 @@ export class PdfService { currentLine = lineIdx; break; } - let { text, bold, italic, underline, indent, center } = styledLines[lineIdx]; + let { text, font: usedFont, indent, align, bold, italic } = 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: usedFont - }; + // Centralizado - if (center) { + if (align === 'center') { const textWidth = usedFont.widthOfTextAtSize(text, FONT_SIZE); - options.x = margens.left + ((MAX_WIDTH - textWidth) / 2); - page.drawText(text, options); + x = margens.left + ((MAX_WIDTH - (indent ? FONT_SIZE * 2 : 0) - textWidth) / 2) + (indent ? FONT_SIZE * 2 : 0); + page.drawText(text, { + x, + y, + size: FONT_SIZE, + font: usedFont, + color: rgb(0, 0, 0) + }); } // Justificado (exceto última linha do parágrafo e centralizado) - else if (text.trim().length > 0 && lineIdx < styledLines.length - 1 && !center) { + else if (text.trim().length > 0 && lineIdx < styledLines.length - 1 && align === 'justify') { const words = text.split(' '); if (words.length > 1) { const textWidth = usedFont.widthOfTextAtSize(text, FONT_SIZE); @@ -475,28 +480,17 @@ export class PdfService { } } } else { - page.drawText(text, options); + page.drawText(text, { x, y, size: FONT_SIZE, font: usedFont }); } - } else if (!center) { - page.drawText(text, options); + } else { + page.drawText(text, { x, y, size: FONT_SIZE, font: usedFont }); } - // Sublinhado - if (underline) { - const textWidth = usedFont.widthOfTextAtSize(text, FONT_SIZE); - page.drawLine({ - start: { x: options.x, y: y - 2 }, - end: { x: options.x + textWidth, y: y - 2 }, - thickness: 0.7, - color: rgb(0, 0, 0) - }); - } - y -= LINE_HEIGHT; + y -= FONT_SIZE * 1.25; // espaçamento entre linhas 1,25 currentLine = 0; firstLine = false; } - // Espaço extra entre parágrafos if (lineIdx >= styledLines.length) { - y -= LINE_HEIGHT * 0.5; + y -= FONT_SIZE * 0.5; } if (lineIdx < styledLines.length) { break;