tenta fix pdfservice.js
This commit is contained in:
1 parent
e179fb33d7
commit
f310f07987
1 file changed
+59
-30
@@ -286,30 +286,33 @@ export class PdfService {
|
|||||||
|
|
||||||
// Função para remover todas as tags HTML, exceto as de formatação suportadas
|
// Função para remover todas as tags HTML, exceto as de formatação suportadas
|
||||||
function stripUnsupportedTags(html: string): string {
|
function stripUnsupportedTags(html: string): string {
|
||||||
// Remove todas as tags, exceto <b>, <strong>, <i>, <em>, <u>, <br>, <p>, <span style="text-indent:2em;">
|
// 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
|
// Remove atributos de <span> exceto text-indent e text-align
|
||||||
return html
|
return html
|
||||||
// Remove spans que não são recuo
|
// Mantém apenas <span> com text-indent ou text-align:center
|
||||||
.replace(/<span\b((?!text-indent)[^>])*?>/gi, '')
|
.replace(/<span\b(?:(?!text-indent|text-align)[^>])*?>/gi, '')
|
||||||
// Remove atributos de <b>, <strong>, <i>, <em>, <u>, <p>
|
// Remove atributos de <b>, <strong>, <i>, <em>, <u>, <p>
|
||||||
.replace(/<(b|strong|i|em|u|p)[^>]*>/gi, '<$1>')
|
.replace(/<(b|strong|i|em|u|p)[^>]*>/gi, '<$1>')
|
||||||
// Remove todas as outras tags e atributos
|
// Remove todas as outras tags e atributos
|
||||||
.replace(/<(?!\/?(b|strong|i|em|u|br|p|span)[ >])[^>]+>/gi, '')
|
.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')
|
.replace(/<span>(.*?)<\/span>/gi, '$1')
|
||||||
// Remove comentários HTML
|
// Remove comentários HTML
|
||||||
.replace(/<!--[\s\S]*?-->/g, '');
|
.replace(/<!--[\s\S]*?-->/g, '');
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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;">
|
// 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(
|
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>
|
||||||
.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(/<\/span>/gi, '')
|
||||||
.replace(/\r\n/g, '\n')
|
.replace(/\r\n/g, '\n')
|
||||||
.replace(/\r/g, '\n')
|
.replace(/\r/g, '\n')
|
||||||
@@ -325,15 +328,20 @@ export class PdfService {
|
|||||||
function wrapTextStyled(text: string, font: any, fontSize: number, maxWidth: number) {
|
function wrapTextStyled(text: string, font: any, fontSize: number, maxWidth: number) {
|
||||||
// Mantém quebras de linha simples para espaçamento
|
// Mantém quebras de linha simples para espaçamento
|
||||||
const rawLines = text.split('\n');
|
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) {
|
for (const rawLine of rawLines) {
|
||||||
let line = rawLine;
|
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
|
// Detecta recuo de parágrafo
|
||||||
if (line.startsWith('§§INDENT§§')) {
|
if (line.startsWith('§§INDENT§§')) {
|
||||||
indent = true;
|
indent = true;
|
||||||
line = line.replace('§§INDENT§§', '').trimStart();
|
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)
|
// 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 (/^<b>|^<strong>/.test(line)) { bold = true; line = line.replace(/^<b>|^<strong>/, ''); }
|
||||||
if (/^<i>|^<em>/.test(line)) { italic = true; line = line.replace(/^<i>|^<em>/, ''); }
|
if (/^<i>|^<em>/.test(line)) { italic = true; line = line.replace(/^<i>|^<em>/, ''); }
|
||||||
@@ -346,17 +354,19 @@ export class PdfService {
|
|||||||
// Quebra em palavras para justificar
|
// Quebra em palavras para justificar
|
||||||
const words = line.split(' ');
|
const words = line.split(' ');
|
||||||
let currentLine = '';
|
let currentLine = '';
|
||||||
for (const word of words) {
|
for (let i = 0; i < words.length; i++) {
|
||||||
const testLine = currentLine ? currentLine + ' ' + word : word;
|
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 width = font.widthOfTextAtSize(testLine, fontSize);
|
||||||
if (width > maxWidth && currentLine) {
|
if (width > maxWidth && currentLine) {
|
||||||
lines.push({ text: currentLine, bold, italic, underline, indent });
|
lines.push({ text: currentLine, bold, italic, underline, indent, center });
|
||||||
currentLine = word;
|
currentLine = word;
|
||||||
} else {
|
} else {
|
||||||
currentLine = testLine;
|
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;
|
return lines;
|
||||||
}
|
}
|
||||||
@@ -381,8 +391,23 @@ export class PdfService {
|
|||||||
pdfDoc = await PDFDocument.create();
|
pdfDoc = await PDFDocument.create();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fonte
|
// Fonte Fira Sans (se disponível), senão Helvetica
|
||||||
const font = await pdfDoc.embedFont(StandardFonts.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
|
// Quebrar o texto em páginas
|
||||||
let currentPar = 0;
|
let currentPar = 0;
|
||||||
@@ -414,23 +439,27 @@ export class PdfService {
|
|||||||
currentLine = lineIdx;
|
currentLine = lineIdx;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
// Justificado: calcula espaçamento extra entre palavras (exceto última linha do parágrafo)
|
let { text, bold, italic, underline, indent, center } = styledLines[lineIdx];
|
||||||
let { text, bold, italic, underline, indent } = styledLines[lineIdx];
|
|
||||||
let x = margens.left + (indent ? FONT_SIZE * 2 : 0);
|
let x = margens.left + (indent ? FONT_SIZE * 2 : 0);
|
||||||
|
let usedFont = bold ? fontBold : italic ? fontItalic : font;
|
||||||
let options: any = {
|
let options: any = {
|
||||||
x,
|
x,
|
||||||
y,
|
y,
|
||||||
size: FONT_SIZE,
|
size: FONT_SIZE,
|
||||||
font: bold ? await pdfDoc.embedFont(StandardFonts.HelveticaBold)
|
font: usedFont
|
||||||
: italic ? await pdfDoc.embedFont(StandardFonts.HelveticaOblique)
|
|
||||||
: font
|
|
||||||
};
|
};
|
||||||
// Justificar (exceto última linha do parágrafo)
|
// Centralizado
|
||||||
if (text.trim().length > 0 && lineIdx < styledLines.length - 1) {
|
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(' ');
|
const words = text.split(' ');
|
||||||
if (words.length > 1) {
|
if (words.length > 1) {
|
||||||
const textWidth = options.font.widthOfTextAtSize(text, FONT_SIZE);
|
const textWidth = usedFont.widthOfTextAtSize(text, FONT_SIZE);
|
||||||
const spaceWidth = options.font.widthOfTextAtSize(' ', FONT_SIZE);
|
const spaceWidth = usedFont.widthOfTextAtSize(' ', FONT_SIZE);
|
||||||
const totalSpaces = words.length - 1;
|
const totalSpaces = words.length - 1;
|
||||||
const extraSpace = (MAX_WIDTH - (indent ? FONT_SIZE * 2 : 0) - textWidth) / totalSpaces;
|
const extraSpace = (MAX_WIDTH - (indent ? FONT_SIZE * 2 : 0) - textWidth) / totalSpaces;
|
||||||
let cursor = x;
|
let cursor = x;
|
||||||
@@ -439,24 +468,24 @@ export class PdfService {
|
|||||||
x: cursor,
|
x: cursor,
|
||||||
y,
|
y,
|
||||||
size: FONT_SIZE,
|
size: FONT_SIZE,
|
||||||
font: options.font
|
font: usedFont
|
||||||
});
|
});
|
||||||
if (w < words.length - 1) {
|
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 {
|
} else {
|
||||||
page.drawText(text, options);
|
page.drawText(text, options);
|
||||||
}
|
}
|
||||||
} else {
|
} else if (!center) {
|
||||||
page.drawText(text, options);
|
page.drawText(text, options);
|
||||||
}
|
}
|
||||||
// Sublinhado
|
// Sublinhado
|
||||||
if (underline) {
|
if (underline) {
|
||||||
const textWidth = options.font.widthOfTextAtSize(text, FONT_SIZE);
|
const textWidth = usedFont.widthOfTextAtSize(text, FONT_SIZE);
|
||||||
page.drawLine({
|
page.drawLine({
|
||||||
start: { x, y: y - 2 },
|
start: { x: options.x, y: y - 2 },
|
||||||
end: { x: x + textWidth, y: y - 2 },
|
end: { x: options.x + textWidth, y: y - 2 },
|
||||||
thickness: 0.7,
|
thickness: 0.7,
|
||||||
color: rgb(0, 0, 0)
|
color: rgb(0, 0, 0)
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in new issue
Block a user