Greedy word-wrap by an approximate per-char width (Helvetica avg ~0.5em; Courier 0.6em). PURE.
(text: string, size: number, mono: boolean, widthPts: number)
| 52 | |
| 53 | /** Greedy word-wrap by an approximate per-char width (Helvetica avg ~0.5em; Courier 0.6em). PURE. */ |
| 54 | function wrap(text: string, size: number, mono: boolean, widthPts: number): string[] { |
| 55 | const charW = size * (mono ? 0.6 : 0.5); |
| 56 | const maxChars = Math.max(8, Math.floor(widthPts / charW)); |
| 57 | const out: string[] = []; |
| 58 | for (const raw of text.split('\n')) { |
| 59 | if (raw.length <= maxChars) { out.push(raw); continue; } |
| 60 | let line = ''; |
| 61 | for (const word of raw.split(' ')) { |
| 62 | if (line && line.length + 1 + word.length > maxChars) { out.push(line); line = word; } |
| 63 | else line = line ? `${line} ${word}` : word; |
| 64 | } |
| 65 | if (line) out.push(line); |
| 66 | } |
| 67 | return out.length ? out : ['']; |
| 68 | } |
| 69 | |
| 70 | /** |
| 71 | * Build a complete PDF document from text blocks. Returns the PDF as a LATIN-1 string — write it |