Skip to content

Commit 5cbd478

Browse files
committed
feat: add support for clipping long titles with ellipsis
1 parent d792755 commit 5cbd478

File tree

3 files changed

+44
-10
lines changed

3 files changed

+44
-10
lines changed

src/formatter/pdf_formatter.ts

Lines changed: 38 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -282,18 +282,48 @@ class PdfFormatter extends Formatter {
282282
const availableWidth = position.width || (pageWidth - this.pdfConfiguration.marginleft - this.pdfConfiguration.marginright);
283283
let y = sectionY + position.y;
284284

285-
const lines = this.doc.splitTextToSize(textValue, availableWidth);
285+
if (position.clip) {
286+
if (position.ellipsis) {
287+
let clippedText = textValue;
288+
let textWidth = this.doc.getTextDimensions(clippedText).w;
289+
290+
while (textWidth > availableWidth) {
291+
clippedText = clippedText.slice(0, -1);
292+
textWidth = this.doc.getTextDimensions(clippedText + '...').w;
293+
}
286294

287-
lines.forEach((line: string) => {
288-
const lineWidth = this.doc.getTextDimensions(line).w;
289-
const x = this.calculateX(position.x, lineWidth);
295+
if (clippedText !== textValue) {
296+
clippedText += '...';
297+
}
290298

291-
this.doc.text(line, x, y);
292-
y += style.size * (style.lineHeight ? style.lineHeight : 1.2);
293-
});
294-
}
299+
const x = this.calculateX(position.x, textWidth);
300+
301+
this.doc.text(clippedText, x, y);
302+
} else {
303+
let clippedText = textValue;
304+
let textWidth = this.doc.getTextDimensions(clippedText).w;
305+
306+
while (textWidth > availableWidth) {
307+
clippedText = clippedText.slice(0, -1);
308+
textWidth = this.doc.getTextDimensions(clippedText).w;
309+
}
310+
311+
const x = this.calculateX(position.x, textWidth);
295312

313+
this.doc.text(clippedText, x, y);
314+
}
315+
} else {
316+
const lines = this.doc.splitTextToSize(textValue, availableWidth);
296317

318+
lines.forEach((line: string) => {
319+
const lineWidth = this.doc.getTextDimensions(line).w;
320+
const x = this.calculateX(position.x, lineWidth);
321+
322+
this.doc.text(line, x, y);
323+
y += style.size * (style.lineHeight ?? 1.2);
324+
});
325+
}
326+
}
297327

298328
// Renders individual image items
299329
private renderImage(imageItem: LayoutContentItemWithImage, sectionY: number) {

src/formatter/pdf_formatter/types.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ interface Position {
2020
y: number,
2121
width?: number,
2222
height?: number,
23+
clip?: boolean,
24+
ellipsis?: boolean,
2325
}
2426

2527
interface Dimension {

test/formatter/pdf/pdf-dev.js

Lines changed: 4 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)