tenta fix pdfservice.js

This commit is contained in:
rodrigo committed 2025-04-21 20:06:37 -03:00
1 parent f310f07987
commit 3ccccc6792
1 file changed
+180 -184
+180 -184
View File
@@ -284,92 +284,121 @@ export class PdfService {
.replace(/&#(\d+);/g, (m, code) => String.fromCharCode(code)); .replace(/&#(\d+);/g, (m, code) => String.fromCharCode(code));
} }
// Função para remover todas as tags HTML, exceto as de formatação suportadas // Função para converter HTML do TinyMCE em uma árvore de blocos com estilos
function stripUnsupportedTags(html: string): string { function parseHtmlToBlocks(html: string): any[] {
// Remove todas as tags, exceto <b>, <strong>, <i>, <em>, <u>, <br>, <p>, <span style="text-indent:2em;">, <span style="text-align:center;"> // Usa DOMParser se disponível, senão fallback simples
// Remove atributos de <span> exceto text-indent e text-align let doc: Document;
return html try {
// Mantém apenas <span> com text-indent ou text-align:center const { JSDOM } = require('jsdom');
.replace(/<span\b(?:(?!text-indent|text-align)[^>])*?>/gi, '') doc = new JSDOM(`<body>${html}</body>`).window.document;
// Remove atributos de <b>, <strong>, <i>, <em>, <u>, <p> } catch {
.replace(/<(b|strong|i|em|u|p)[^>]*>/gi, '<$1>') // fallback: ignora tags e retorna texto puro
// Remove todas as outras tags e atributos return [{ text: html, tag: 'p', styles: {} }];
.replace(/<(?!\/?(b|strong|i|em|u|br|p|span)[ >])[^>]+>/gi, '') }
// Remove spans sem text-indent ou text-align const blocks: any[] = [];
.replace(/<span>(.*?)<\/span>/gi, '$1') function parseNode(node: Node, parentStyles: any = {}) {
// Remove comentários HTML if (node.nodeType === 3) { // Text
.replace(/<!--[\s\S]*?-->/g, ''); 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: <span style="font-weight:bold">, <span style="font-style:italic">, <span style="text-decoration:underline">
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;
} }
// Processar variáveis do template e decodificar entidades HTML // Processar variáveis do template e decodificar entidades HTML
// Mantém tags <b>, <strong>, <i>, <em>, <u>, <br>, <p>, <span style="text-indent:2em;">, <span style="text-align:center;"> // Mantém tags <b>, <strong>, <i>, <em>, <u>, <br>, <p>, <span style="text-indent:2em;">, <span style="text-align:center;">
const texto = decodeHtmlEntities( const texto = decodeHtmlEntities(
stripUnsupportedTags( this.processarTemplate(conteudo, escritorio)
this.processarTemplate(conteudo, escritorio) .replace(/<br\s*\/?>/gi, '\n')
.replace(/<br\s*\/?>/gi, '\n') .replace(/<\/p>/gi, '\n\n')
.replace(/<\/p>/gi, '\n\n') .replace(/<p[^>]*>/gi, '') // Remove apenas a tag de abertura <p>
.replace(/<p[^>]*>/gi, '') // Remove apenas a tag de abertura <p> // Marca recuo de parágrafo
// Marca recuo de parágrafo .replace(/<span[^>]*text-indent[^>]*>/gi, '§§INDENT§§')
.replace(/<span[^>]*text-indent[^>]*>/gi, '§§INDENT§§') // Marca centralização
// Marca centralização .replace(/<span[^>]*text-align\s*:\s*center[^>]*>/gi, '§§CENTER§§')
.replace(/<span[^>]*text-align\s*:\s*center[^>]*>/gi, '§§CENTER§§') .replace(/<\/span>/gi, '')
.replace(/<\/span>/gi, '') .replace(/\r\n/g, '\n')
.replace(/\r\n/g, '\n') .replace(/\r/g, '\n')
.replace(/\r/g, '\n') .replace(/\n{3,}/g, '\n\n')
.replace(/\n{3,}/g, '\n\n') .trim()
.trim()
)
); );
// Quebra o texto em parágrafos (mantendo quebras de linha duplas como parágrafo) // 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); const paragrafos = texto.split(/\n{2,}/).map(p => p.trim()).filter(Boolean);
// Função para quebrar texto em linhas respeitando largura máxima e manter quebras de linha simples // Fonte Fira Sans (se disponível), senão Helvetica
function wrapTextStyled(text: string, font: any, fontSize: number, maxWidth: number) { let font = await pdfDoc.embedFont(StandardFonts.Helvetica);
// Mantém quebras de linha simples para espaçamento let fontBold = font, fontItalic = font, fontBoldItalic = font;
const rawLines = text.split('\n'); try {
const lines: { text: string, bold: boolean, italic: boolean, underline: boolean, indent: boolean, center: boolean }[] = []; const firaPath = path.join(process.cwd(), 'public', 'fonts', 'FiraSans-Regular.ttf');
for (const rawLine of rawLines) { const firaBoldPath = path.join(process.cwd(), 'public', 'fonts', 'FiraSans-Bold.ttf');
let line = rawLine; const firaItalicPath = path.join(process.cwd(), 'public', 'fonts', 'FiraSans-Italic.ttf');
let bold = false, italic = false, underline = false, indent = false, center = false; const firaBoldItalicPath = path.join(process.cwd(), 'public', 'fonts', 'FiraSans-BoldItalic.ttf');
// Detecta recuo de parágrafo const [fira, firaBold, firaItalic, firaBoldItalic] = await Promise.all([
if (line.startsWith('§§INDENT§§')) { fs.readFile(firaPath).catch(() => null),
indent = true; fs.readFile(firaBoldPath).catch(() => null),
line = line.replace('§§INDENT§§', '').trimStart(); fs.readFile(firaItalicPath).catch(() => null),
} fs.readFile(firaBoldItalicPath).catch(() => null),
// Detecta centralização ]);
if (line.startsWith('§§CENTER§§')) { if (fira) font = await pdfDoc.embedFont(fira);
center = true; if (firaBold) fontBold = await pdfDoc.embedFont(firaBold);
line = line.replace('§§CENTER§§', '').trimStart(); if (firaItalic) fontItalic = await pdfDoc.embedFont(firaItalic);
} if (firaBoldItalic) fontBoldItalic = await pdfDoc.embedFont(firaBoldItalic);
// Detecta negrito, itálico, sublinhado (apenas no início e fim da linha) } catch { /* fallback para Helvetica */ }
if (/^<b>|^<strong>/.test(line)) { bold = true; line = line.replace(/^<b>|^<strong>/, ''); }
if (/^<i>|^<em>/.test(line)) { italic = true; line = line.replace(/^<i>|^<em>/, ''); } // Parse TinyMCE HTML para blocos estilizados
if (/^<u>/.test(line)) { underline = true; line = line.replace(/^<u>/, ''); } const blocks = parseHtmlToBlocks(conteudo);
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, '');
// 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);
if (width > maxWidth && currentLine) {
lines.push({ text: currentLine, bold, italic, underline, indent, center });
currentLine = word;
} else {
currentLine = testLine;
}
}
if (currentLine) lines.push({ text: currentLine, bold, italic, underline, indent, center });
}
return lines;
}
// Carregar o timbrado (se houver) e criar o PDF final // Carregar o timbrado (se houver) e criar o PDF final
let pdfDoc: PDFDocument; let pdfDoc: PDFDocument;
@@ -391,119 +420,86 @@ export class PdfService {
pdfDoc = await PDFDocument.create(); pdfDoc = await PDFDocument.create();
} }
// Fonte Fira Sans (se disponível), senão Helvetica // Renderização dos blocos no PDF
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; let pageIndex = 0;
let y = PAGE_HEIGHT - margens.top;
let page = pdfDoc.addPage([PAGE_WIDTH, PAGE_HEIGHT]);
if (timbradoPages && timbradoPages.length > 0) {
const embedded = timbradoPages[pageIndex % timbradoPages.length];
page.drawPage(embedded, {
x: 0,
y: 0,
width: PAGE_WIDTH,
height: PAGE_HEIGHT
});
}
while (currentPar < paragrafos.length) { for (const block of blocks) {
// Adicionar página do timbrado ou em branco if (block.tag === 'br') {
let page = pdfDoc.addPage([PAGE_WIDTH, PAGE_HEIGHT]); y -= LINE_HEIGHT * 0.5;
// Desenhar o timbrado como fundo (usando embeddedPage) continue;
if (timbradoPages.length > 0) { }
const embedded = timbradoPages[pageIndex % timbradoPages.length]; let usedFont = font;
page.drawPage(embedded, { if (block.styles.bold && block.styles.italic && fontBoldItalic) usedFont = fontBoldItalic;
x: 0, else if (block.styles.bold && fontBold) usedFont = fontBold;
y: 0, else if (block.styles.italic && fontItalic) usedFont = fontItalic;
width: PAGE_WIDTH,
height: PAGE_HEIGHT let blockFontSize = FONT_SIZE;
if (block.styles.heading === 'h1') blockFontSize = 22;
if (block.styles.heading === 'h2') blockFontSize = 18;
if (block.styles.heading === 'h3') blockFontSize = 16;
let x = margens.left + (block.styles.indent ? FONT_SIZE * 2 : 0);
let width = usedFont.widthOfTextAtSize(block.text, blockFontSize);
// Centralização
if (block.styles.align === 'center' || block.styles.heading === 'h1') {
x = margens.left + ((MAX_WIDTH - width) / 2);
}
if (block.styles.align === 'right') {
x = margens.left + (MAX_WIDTH - width);
}
// Quebra de página se necessário
if (y < margens.bottom + blockFontSize * 1.2) {
pageIndex++;
page = pdfDoc.addPage([PAGE_WIDTH, PAGE_HEIGHT]);
if (timbradoPages && timbradoPages.length > 0) {
const embedded = timbradoPages[pageIndex % timbradoPages.length];
page.drawPage(embedded, {
x: 0,
y: 0,
width: PAGE_WIDTH,
height: PAGE_HEIGHT
});
}
y = PAGE_HEIGHT - margens.top;
}
// Renderiza o texto
page.drawText(block.text, {
x,
y,
size: blockFontSize,
font: usedFont,
color: rgb(0, 0, 0)
});
// Sublinhado
if (block.styles.underline) {
page.drawLine({
start: { x, y: y - 2 },
end: { x: x + width, y: y - 2 },
thickness: 0.7,
color: rgb(0, 0, 0)
}); });
} }
let y = PAGE_HEIGHT - margens.top;
let firstLine = true; y -= blockFontSize * 1.5;
// Escrever texto na página // Espaço extra entre parágrafos
while (currentPar < paragrafos.length) { if (block.tag === 'p' || block.styles.heading) {
const styledLines = wrapTextStyled(paragrafos[currentPar], font, FONT_SIZE, MAX_WIDTH); y -= blockFontSize * 0.3;
let lineIdx = 0;
if (currentLine > 0) lineIdx = currentLine;
for (; lineIdx < styledLines.length; lineIdx++) {
if (y < margens.bottom + LINE_HEIGHT) {
currentLine = lineIdx;
break;
}
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: usedFont
};
// 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 = 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;
for (let w = 0; w < words.length; w++) {
page.drawText(words[w], {
x: cursor,
y,
size: FONT_SIZE,
font: usedFont
});
if (w < words.length - 1) {
cursor += usedFont.widthOfTextAtSize(words[w], FONT_SIZE) + spaceWidth + extraSpace;
}
}
} else {
page.drawText(text, options);
}
} else if (!center) {
page.drawText(text, options);
}
// 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;
currentLine = 0;
firstLine = false;
}
// Espaço extra entre parágrafos
if (lineIdx >= styledLines.length) {
y -= LINE_HEIGHT * 0.5;
}
if (lineIdx < styledLines.length) {
break;
}
currentPar++;
} }
pageIndex++;
} }
const pdfBytes = await pdfDoc.save(); const pdfBytes = await pdfDoc.save();