tenta fix pdfservice.js

This commit is contained in:
rodrigo committed 2025-04-21 19:52:13 -03:00
1 parent e179fb33d7
commit f310f07987
1 file changed
+59 -30
+59 -30
View File
@@ -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 <b>, <strong>, <i>, <em>, <u>, <br>, <p>, <span style="text-indent:2em;">
// Remove atributos de <span> exceto text-indent
// Remove todas as tags, exceto <b>, <strong>, <i>, <em>, <u>, <br>, <p>, <span style="text-indent:2em;">, <span style="text-align:center;">
// Remove atributos de <span> exceto text-indent e text-align
return html
// Remove spans que não são recuo
.replace(/<span\b((?!text-indent)[^>])*?>/gi, '')
// Mantém apenas <span> com text-indent ou text-align:center
.replace(/<span\b(?:(?!text-indent|text-align)[^>])*?>/gi, '')
// Remove atributos de <b>, <strong>, <i>, <em>, <u>, <p>
.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>(.*?)<\/span>/gi, '$1')
// Remove comentários HTML
.replace(/<!--[\s\S]*?-->/g, '');
}
// Processar variáveis do template e decodificar entidades HTML
// Mantém tags <b>, <strong>, <i>, <em>, <u>, <br>, <p>, <span style="text-indent:2em;">
// Mantém tags <b>, <strong>, <i>, <em>, <u>, <br>, <p>, <span style="text-indent:2em;">, <span style="text-align:center;">
const texto = decodeHtmlEntities(
stripUnsupportedTags(
this.processarTemplate(conteudo, escritorio)
.replace(/<br\s*\/?>/gi, '\n')
.replace(/<\/p>/gi, '\n\n')
.replace(/<p[^>]*>/gi, '') // Remove apenas a tag de abertura <p>
.replace(/<span[^>]*text-indent[^>]*>/gi, '§§INDENT§§') // Marca recuo de parágrafo
// Marca recuo de parágrafo
.replace(/<span[^>]*text-indent[^>]*>/gi, '§§INDENT§§')
// Marca centralização
.replace(/<span[^>]*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 (/^<b>|^<strong>/.test(line)) { bold = true; line = line.replace(/^<b>|^<strong>/, ''); }
if (/^<i>|^<em>/.test(line)) { italic = true; line = line.replace(/^<i>|^<em>/, ''); }
@@ -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)
});