Skip to content

Keep the last word of a paragraph within its column - #1886

Open
docteurzoidberg wants to merge 1 commit into
foliojs:masterfrom
docteurzoidberg:fix-last-word-below-column
Open

docteurzoidberg wants to merge 1 commit into
foliojs:masterfrom
docteurzoidberg:fix-last-word-below-column

Conversation

@docteurzoidberg

Copy link
Copy Markdown

What kind of change does this PR introduce?

Bug fix: the last word of a paragraph could be drawn one line below the bottom of its column or page.

When the last word of a paragraph (the word before a \n) does not fit on the current line, LineWrapper#wrap emits two lines in a row: the current line, then the word alone. It only checks the available height after the second one. If the first line already filled the column, the word is drawn one line too low. Depending on the layout, it ends up past the text's height, under the bottom margin, or over whatever is drawn below the text. The text that follows then starts in the next column as usual, so the columns also come out unbalanced.

const doc = new PDFDocument();
const lh = doc.currentLineHeight(true);
// a paragraph whose last word wraps alone onto the third line of a 100 pt column
let text = 'word';
while (doc.heightOfString(`${text} word`, { width: 100 }) <= 2 * lh) text += ' word';
doc.text(`${text} lastword\nnext`, 72, 72, { width: 210, columns: 2, columnGap: 10, height: 2 * lh });
// before: "lastword" is drawn at y = 72 + 2 * lh in the first column, below the height
// after: it starts the second column, followed by "next"

The fix checks the height between the two lines as well. The existing check that runs after every line is moved to a small helper, so both places share it: the word moves to the next column or page, and is left out when the text has a height and no column remains, as any other line would be.

Checklist:

  • Unit Tests (two tests in tests/unit/line_wrapper.spec.js: next column, new page; both fail without the fix)
  • Documentation N/A
  • Update CHANGELOG.md
  • Ready to be merged

yarn test (697 tests), yarn lint and prettier --check pass.

When the last word of a paragraph does not fit on the current line, the
wrapper emitted two lines in a row (the current one, then the word alone)
and only checked the available height after the second. When the first
one filled the column or the page, the word was drawn one line below its
bottom: past the `height` of the text, under the bottom margin, or over
whatever follows.

Check the height between the two lines too, with the same logic as after
every line, moved to a helper.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant