In pdf-lib, it is possible to auto-word-wrap text using a technique outlined here: https://stackoverflow.com/a/77436904/1766230
import { PDFDocument, StandardFonts } from 'pdf-lib';
const doc = await PDFDocument.create();
const font = await doc.embedFont(StandardFonts.TimesRoman);
const page = doc.addPage();
// This will word-wrap fine:
page.drawText(someLongText, { font, size: 20, lineHeight: 25, maxWidth: 200, wordBreaks: [' '] });
// But now what?
// page.moveDown(???);
The problem is you may need to either…
- Move the y cursor down so that you can write the next line to the page. (
page.moveDown
) - Detect when a new page might be needed — i.e., the height of this wrapped text would go off the bottom of the page — so that you can split up the text and add a new page (
doc.addPage
).
But there does not seem to be any functions in the documentation that let’s you determine the height of the word-wrapped text you are drawing to the page. font.heightAtSize(size)
just gets the height of the font. What can be done?