import type { PDFFont, PDFPage, PDFPageDrawTextOptions } from 'pdf-lib' import { safeText } from '../text' /** * Every string reaches pdf-lib through these three helpers, so a glyph the * standard fonts cannot encode never throws at draw or measure time. */ export function measure(font: PDFFont, text: string, size: number): number { return font.widthOfTextAtSize(safeText(text), size) } export function drawText( page: PDFPage, text: string, options: PDFPageDrawTextOptions, ): void { page.drawText(safeText(text), options) } /** * Greedy word-wrap: splits `text` into lines whose rendered width at * `size` points stays within `max` for the given font. Whitespace of any * kind separates words first, then each word is made safe. */ export function wrapLines( text: string, font: PDFFont, size: number, max: number, ): string[] { const words = text.split(/\s+/).map(safeText) const lines: string[] = [] let line = '' for (const w of words) { const test = line ? `${line} ${w}` : w if (measure(font, test, size) > max && line) { lines.push(line) line = w } else { line = test } } if (line) lines.push(line) return lines }