Co-authored-by: renee-png <262607627+renee-png@users.noreply.github.com>
This commit is contained in:
gpt-engineer-app[bot]
2026-04-18 18:59:31 +00:00
co-authored by renee-png
parent 2a2b543d8f
commit 75daa735cf
+21 -13
View File
@@ -121,16 +121,24 @@ function layoutTokens(pdf: jsPDF, tokens: Token[], maxWidth: number): Piece[][]
};
const lineWidth = (line: Piece[]) => line.reduce((a, p) => a + p.w, 0);
const pushWord = (word: string, style: Style) => {
if (!word) return;
const w = measure(word, style);
const pushPiece = (text: string, style: Style) => {
if (!text) return;
const cur = lines[lines.length - 1];
if (lineWidth(cur) + w > maxWidth && cur.length > 0) {
while (cur.length && /\s+$/.test(cur[cur.length - 1].text)) cur.pop();
lines.push([{ text: word, style, w }]);
} else {
cur.push({ text: word, style, w });
const isWhitespace = /^\s+$/.test(text);
if (isWhitespace) {
if (cur.length === 0) return;
cur.push({ text, style, w: measure(text, style) });
return;
}
const w = measure(text, style);
if (lineWidth(cur) + w > maxWidth && cur.length > 0) {
while (cur.length && /^\s+$/.test(cur[cur.length - 1].text)) cur.pop();
lines.push([{ text, style, w }]);
return;
}
cur.push({ text, style, w });
};
for (const tok of tokens) {
@@ -138,8 +146,8 @@ function layoutTokens(pdf: jsPDF, tokens: Token[], maxWidth: number): Piece[][]
for (const part of parts) {
if (part === "\n") { lines.push([]); continue; }
if (!part) continue;
const words = part.match(/\S+\s*/g) || [part];
for (const w of words) pushWord(w, tok.style);
const chunks = part.match(/\s+|[^\s]+/g) || [part];
for (const chunk of chunks) pushPiece(chunk, tok.style);
}
}
return lines;
@@ -155,7 +163,7 @@ function drawLine(pdf: jsPDF, line: Piece[], x: number, y: number, align: "left"
if (align === "center") startX = x + (maxWidth - totalW) / 2;
else if (align === "right") startX = x + (maxWidth - totalW);
else if (align === "justify" && !isLast) {
const spaces = trimmed.filter((p) => /\s$/.test(p.text)).length;
const spaces = trimmed.filter((p) => /^\s+$/.test(p.text)).length;
if (spaces > 0) extraSpace = (maxWidth - totalW) / spaces;
}
@@ -164,13 +172,13 @@ function drawLine(pdf: jsPDF, line: Piece[], x: number, y: number, align: "left"
const sz = p.style.superscript ? FONT_SIZE * 0.75 : FONT_SIZE;
setFont(pdf, p.style, sz);
const drawY = p.style.superscript ? y - 4 : y;
pdf.text(p.text, cx, drawY);
if (!/^\s+$/.test(p.text)) pdf.text(p.text, cx, drawY);
if (p.style.underline) {
const tw = p.w;
pdf.setLineWidth(0.5);
pdf.line(cx, y + 1.5, cx + tw, y + 1.5);
}
cx += p.w + (/\s$/.test(p.text) ? extraSpace : 0);
cx += p.w + (/^\s+$/.test(p.text) ? extraSpace : 0);
}
}