Skip to content

Commit 2e91eb6

Browse files
authored
refactor(pdfkit): remove font export (#3335)
1 parent cf366d0 commit 2e91eb6

3 files changed

Lines changed: 31 additions & 4 deletions

File tree

.changeset/dry-buttons-boil.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"@react-pdf/font": patch
3+
"@react-pdf/pdfkit": major
4+
---
5+
6+
refactor(pdfkit): remove font export

packages/font/src/standard-font.ts

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// @ts-expect-error ts being silly
2-
import { PDFFont } from '@react-pdf/pdfkit';
2+
import PDFDocument from '@react-pdf/pdfkit';
33
import * as fontkit from 'fontkit';
44
import { Font } from './types';
55

@@ -18,6 +18,18 @@ export const STANDARD_FONTS = [
1818
'Times-BoldItalic',
1919
];
2020

21+
// Create a shared lightweight document for accessing standard font instances.
22+
// Standard fonts are created once and cached, so this is negligible overhead.
23+
let _sharedDoc: any = null;
24+
25+
const openStandardFont = (src: string) => {
26+
if (!_sharedDoc) {
27+
_sharedDoc = new PDFDocument({ autoFirstPage: false });
28+
}
29+
_sharedDoc.font(src);
30+
return _sharedDoc._font;
31+
};
32+
2133
class StandardFont implements Font {
2234
name: string;
2335
src: any;
@@ -57,11 +69,21 @@ class StandardFont implements Font {
5769
this.numGlyphs = 0;
5870
this.characterSet = [];
5971

60-
this.src = PDFFont.open(null, src);
72+
this.src = openStandardFont(src);
6173
}
6274

6375
encode(str: string) {
64-
return this.src.encode(str);
76+
const [encoded, positions] = this.src.encode(str);
77+
78+
// Soft hyphens (U+00AD) should have zero width for line breaking purposes.
79+
// Upstream pdfkit maps them to 'hyphen' in AFM data, so we override here.
80+
for (let i = 0; i < str.length; i++) {
81+
if (str.charCodeAt(i) === 0x00ad) {
82+
positions[i].advanceWidth = 0;
83+
}
84+
}
85+
86+
return [encoded, positions];
6587
}
6688

6789
layout(str: string) {

packages/pdfkit/src/index.js

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
11
import PDFDocument from './document';
22

3-
export * from './font';
43
export default PDFDocument;

0 commit comments

Comments
 (0)