Skip to content

Commit de7f7ec

Browse files
fix: update text encoding to handle surrogate pairs in AFMFont and font substitution
1 parent a3940ea commit de7f7ec

File tree

2 files changed

+20
-18
lines changed
  • packages

2 files changed

+20
-18
lines changed

packages/pdfkit/src/font/afm.js

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -206,29 +206,28 @@ class AFMFont {
206206

207207
encodeText(text) {
208208
const res = [];
209-
for (
210-
let i = 0, end = text.length, asc = 0 <= end;
211-
asc ? i < end : i > end;
212-
asc ? i++ : i--
213-
) {
214-
let char = text.charCodeAt(i);
215-
char = WIN_ANSI_MAP[char] || char;
209+
let i = 0;
210+
211+
while (i < text.length) {
212+
const codePoint = text.codePointAt(i);
213+
const char = WIN_ANSI_MAP[codePoint] || codePoint;
216214
res.push(char.toString(16));
215+
216+
i += codePoint > 0xFFFF ? 2 : 1;
217217
}
218218

219219
return res;
220220
}
221221

222222
glyphsForString(string) {
223223
const glyphs = [];
224+
let i = 0;
225+
226+
while (i < string.length) {
227+
const codePoint = string.codePointAt(i);
228+
glyphs.push(this.characterToGlyph(codePoint));
224229

225-
for (
226-
let i = 0, end = string.length, asc = 0 <= end;
227-
asc ? i < end : i > end;
228-
asc ? i++ : i--
229-
) {
230-
const charCode = string.charCodeAt(i);
231-
glyphs.push(this.characterToGlyph(charCode));
230+
i += codePoint > 0xFFFF ? 2 : 1;
232231
}
233232

234233
return glyphs;

packages/textkit/src/engines/fontSubstitution/index.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,9 @@ const fontSubstitution =
4949

5050
const chars = string.slice(run.start, run.end);
5151

52-
for (let j = 0; j < chars.length; j += 1) {
53-
const char = chars[j];
54-
const codePoint = char.codePointAt(0);
52+
let j = 0;
53+
while (j < chars.length) {
54+
const codePoint = chars.codePointAt(j);
5555
// If the default font does not have a glyph and the fallback font does, we use it
5656
const font = pickFontFromFontStack(
5757
codePoint,
@@ -83,7 +83,10 @@ const fontSubstitution =
8383
lastIndex = index;
8484
}
8585

86-
index += char.length;
86+
// Calculate character length based on code point (1 for BMP, 2 for others)
87+
const charLength = codePoint > 0xffff ? 2 : 1;
88+
j += charLength;
89+
index += charLength;
8790
}
8891
}
8992

0 commit comments

Comments
 (0)