tenta fix pdfservice.js

This commit is contained in:
rodrigo committed 2025-04-22 10:01:02 -03:00
1 parent cb47df6e88
commit 3406723bd4
1 file changed
+18 -12
+18 -12
View File
@@ -414,7 +414,7 @@ export class PdfService {
// Ajuste: Força alinhamento consistente para todas as linhas do parágrafo
// Se align === 'center', todas as linhas centralizadas
// Se align === 'justify', todas as linhas justificadas (inclusive a última)
// Se align === 'justify', todas as linhas justificadas (exceto a última ou linhas curtas)
// Se align === 'left' ou outro, todas à esquerda
for (let i = 0; i < lines.length; i++) {
@@ -423,11 +423,16 @@ export class PdfService {
}
let line = lines[i];
let drawX = x;
let totalWidth = line.tokens.reduce((acc, t) => acc + t.font.widthOfTextAtSize(t.text, fontSize), 0);
// Remove espaços no início e fim da linha para não justificar esses espaços
let trimmedTokens = [...line.tokens];
while (trimmedTokens.length && /^\s+$/.test(trimmedTokens[0].text)) trimmedTokens.shift();
while (trimmedTokens.length && /^\s+$/.test(trimmedTokens[trimmedTokens.length - 1].text)) trimmedTokens.pop();
let totalWidth = trimmedTokens.reduce((acc, t) => acc + t.font.widthOfTextAtSize(t.text, fontSize), 0);
if (align === 'center') {
drawX = x + (maxWidth - totalWidth) / 2;
for (const t of line.tokens) {
for (const t of trimmedTokens) {
page.drawText(t.text, {
x: drawX,
y,
@@ -446,18 +451,19 @@ export class PdfService {
}
drawX += t.font.widthOfTextAtSize(t.text, fontSize);
}
} else if (align === 'justify') {
// Justify: distribui espaço entre palavras em TODAS as linhas
const spaces = line.tokens.filter(t => /^\s+$/.test(t.text));
} else if (align === 'justify' && i < lines.length - 1 && trimmedTokens.length > 2) {
// Justify: distribui espaço entre palavras, exceto na última linha ou linhas curtas
const spaces = trimmedTokens.filter(t => /^\s+$/.test(t.text));
const numSpaces = spaces.length;
const lineTextWidth = line.tokens.reduce((acc, t) => acc + t.font.widthOfTextAtSize(t.text, fontSize), 0);
const lineTextWidth = trimmedTokens.reduce((acc, t) => acc + t.font.widthOfTextAtSize(t.text, fontSize), 0);
const extraSpace = maxWidth - lineTextWidth;
let spaceWidth = 0;
if (numSpaces > 0) {
// Só justifica se houver pelo menos 2 espaços e a linha não for muito curta
if (numSpaces > 0 && extraSpace > 0) {
spaceWidth = extraSpace / numSpaces;
}
let localDrawX = drawX;
for (const t of line.tokens) {
let localDrawX = x;
for (const t of trimmedTokens) {
page.drawText(t.text, {
x: localDrawX,
y,
@@ -481,8 +487,8 @@ export class PdfService {
}
}
} else {
// Alinhamento à esquerda (padrão)
for (const t of line.tokens) {
// Alinhamento à esquerda (padrão) ou última linha de parágrafo justificado
for (const t of trimmedTokens) {
page.drawText(t.text, {
x: drawX,
y,