Skip to content

Write two hex digits for standard font character codes below 0x10 - #1822

Merged
blikblum merged 2 commits into
foliojs:masterfrom
ybai08:fix-hex-glyph-codes
Oct 18, 2026
Merged

blikblum merged 2 commits into
foliojs:masterfrom
ybai08:fix-hex-glyph-codes

Conversation

@ybai08

@ybai08 ybai08 commented Oct 17, 2026

Copy link
Copy Markdown
Contributor

What kind of change does this PR introduce?

Bug fix. Fixes #1425, also fixes #606 (and probably #1354, which uses the default Helvetica and a template literal with Windows line endings).

With a standard (AFM) font, AFMFont#encodeText writes each character code with char.toString(16), so a code below 0x10 comes out as a single hex digit. In the <...> string the following digits then pair up wrongly. Per PDF 32000-1 §7.3.4.3 a reader takes the digits two at a time, and assumes a 0 after a trailing odd digit.

The fix pads each code to two digits (padStart(2, '0')), as the embedded font path already does with its 4-digit glyph IDs. Codes 0x10 and above are unchanged, so normal text produces the same bytes (the visual snapshots still pass).

Text extracted with pdfjs-dist (already a dev dependency), doc.text(s, 50, 50, { lineBreak: false }):

input before after
'a\tb' a– a b
'Tab\there' Tab–†W&P Tab here
'line\r' lineÐ line
'x\u0001yz' x — x yz

Not part of this PR: the line wrapper still keeps the \r of a \r\n at the end of the line (now as an invisible 0x0D code instead of Ð). Stripping it the way \n is stripped would be a separate change.

Checklist:

  • Unit Tests
  • Documentation N/A
  • Update CHANGELOG.md
  • Ready to be merged

Tests added:

  • tests/unit/afm.spec.js: encodeText('a\tb\r\x01') returns ['61', '09', '62', '0d', '01']
  • tests/unit/text.spec.js: doc.text('a\tb\rc', { lineBreak: false }) keeps the text a\tb\rc in the content stream

Both fail on master and pass with the fix. Ran yarn test (62 files, 552 tests, unit and visual), yarn lint and yarn prettier, all passing. Did not run test:tools or test:package.

@blikblum
blikblum merged commit 50af0aa into foliojs:master Oct 18, 2026
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.

Extra "Ð" at the end of a line when using text with carriage returns (\r) Strange character "Ð" every time I press "intro"

2 participants