Skip to content

A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!

fix(pdf): respect requested font metrics when positioning text (#3430)

Amruth Pillai8354c39c4532
diff --git a/packages/pdf/src/font-metrics.integration.test.tsx b/packages/pdf/src/font-metrics.integration.test.tsx
new file mode 100644
index 000000000..ffd5cf35c
--- /dev/null
+++ b/packages/pdf/src/font-metrics.integration.test.tsx
@@ -0,0 +1,100 @@
+import { describe, expect, it } from "vitest";
+import { Document, Font, Page, renderToBuffer, Text } from "@react-pdf/renderer";
+import { getDocument } from "pdfjs-dist/legacy/build/pdf.mjs";
+import { act } from "react";
+import { getWebFontSource } from "@reactive-resume/fonts";
+
+async function baselines(families: string[], content = "Heading", lineHeight = 1.5) {
+ for (const family of families) {
+ const src = getWebFontSource(family, "400", false);
+ if (!src) throw new Error(`Missing test font: ${family}`);
+ Font.register({ family, src });
+ }
+ const bytes = await act(() =>
+ renderToBuffer(
+ <Document>
+ <Page size="A4">
+ {families.map((family, index) => (
+ <Text
+ key={family}
+ style={{
+ position: "absolute",
+ top: 20 + index * 100,
+ left: 20,
+ fontFamily: family,
+ fontSize: 20,
+ lineHeight,
+ }}
+ >
+ {content}
+ </Text>
+ ))}
+ </Page>
+ </Document>,
+ ),
+ );
+ const task = getDocument({ data: new Uint8Array(bytes), useSystemFonts: true });
+ try {
+ const doc = await task.promise;
+ expect(doc.numPages).toBe(1);
+ const page = await doc.getPage(1);
+ const text = await page.getTextContent();
+ return text.items.flatMap((item) =>
+ "str" in item && item.str
+ ? [{ text: item.str, y: page.getViewport({ scale: 1 }).height - Number(item.transform[5]) }]
+ : [],
+ );
+ } finally {
+ await task.destroy();
+ }
+}
+
+function baselineAt(rows: { y: number }[], index: number) {
+ const row = rows[index];
+ if (!row) throw new Error(`Missing PDF text row ${index}`);
+ return row.y;
+}
+
+describe("font baselines in generated PDFs (#3249)", () => {
+ it.each(["Roboto", "Roboto Condensed"])(
+ "aligns %s with Roboto Flex's matching vertical metrics",
+ { timeout: 30_000 },
+ async (family) => {
+ const rows = await baselines([family, "Roboto Flex"]);
+ expect(rows).toHaveLength(2);
+ expect(baselineAt(rows, 0) - 20).toBeCloseTo(baselineAt(rows, 1) - 120, 3);
+ },
+ );
+ it("aligns IBM Plex Sans Condensed with IBM Plex Sans", { timeout: 30_000 }, async () => {
+ const rows = await baselines(["IBM Plex Sans Condensed", "IBM Plex Sans"]);
+ expect(rows).toHaveLength(2);
+ expect(baselineAt(rows, 0) - 20).toBeCloseTo(baselineAt(rows, 1) - 120, 3);
+ });
+ it.each([
+ ["IBM Plex Sans", 20.5],
+ ["Roboto Flex", 18.554688],
+ ["Geist", 20.1],
+ ["Ropa Sans", 16.82],
+ ] as const)("preserves %s's existing baseline", { timeout: 30_000 }, async (family, expected) => {
+ const rows = await baselines([family]);
+ expect(baselineAt(rows, 0) - 20).toBeCloseTo(expected, 3);
+ });
+ it.each([
+ "Noto Sans HK",
+ "Noto Sans SC",
+ "Noto Serif SC",
+ "Noto Sans TC",
+ "Noto Serif TC",
+ "Noto Sans JP",
+ "Noto Serif JP",
+ "Noto Sans KR",
+ "Noto Serif KR",
+ ])("preserves %s's compact CJK lines at tight line height", { timeout: 60_000 }, async (family) => {
+ const rows = await baselines([family], "高行\n高行", 0.8);
+ expect(rows.map((row) => row.text)).toEqual(["高行", "高行"]);
+ expect(baselineAt(rows, 0) - 20).toBeCloseTo(18, 3);
+ // The newline uses the standard-font fallback. Keep the existing 21.6pt
+ // line box; shrinking to the requested 16pt would clip the next line.
+ expect(baselineAt(rows, 1) - baselineAt(rows, 0)).toBeCloseTo(21.6, 3);
+ });
+});
diff --git a/patches/@react-pdf__textkit.patch b/patches/@react-pdf__textkit.patch
index 56c91f831..c11c73526 100644
--- a/patches/@react-pdf__textkit.patch
+++ b/patches/@react-pdf__textkit.patch
@@ -2,26 +2,23 @@ diff --git a/lib/textkit.js b/lib/textkit.js
index 2c0ec95..3683493 100644
--- a/lib/textkit.js
+++ b/lib/textkit.js
-@@ -709,6 +709,31 @@ const omit = (value, run) => {
+@@ -709,6 +709,28 @@ const omit = (value, run) => {
return Object.assign({}, run, { attributes });
};
+/**
-+ * Resolve a fontkit Font's vertical metrics, preferring the OS/2
-+ * `sTypoAscender / sTypoDescender / sTypoLineGap` triple when available
-+ * and falling back to hhea. This matches Chromium's font-metrics
-+ * resolution and is what browsers (and the v5.0.x Puppeteer renderer)
-+ * use, giving compact, predictable line boxes for fonts whose hhea
-+ * values are inflated for Windows GDI compatibility (notably Source
-+ * Han Sans/Serif a.k.a. Noto Sans/Serif CJK).
-+ *
-+ * `f['OS/2']` is exposed by fontkit when the font carries an OS/2 table.
-+ * Standard PDF fonts (Helvetica/Courier/Times) and our internal
-+ * EmbeddedFont don't, so they keep their existing hhea-based metrics.
++ * Honor the font's USE_TYPO_METRICS flag instead of substituting OS/2
++ * metrics for every font. Roboto and IBM Plex Sans Condensed deliberately
++ * use hhea metrics; their unused typo ascenders move text above icons.
++ * Keep the compact metrics used by our Noto CJK / Source Han fallbacks
++ * to avoid restoring inflated line boxes and CJK clipping (#2986).
++ * Standard PDF fonts have no OS/2 table and retain their own metrics.
+ */
+const resolveTypoMetrics = (font) => {
+ const os2 = font?.['OS/2'];
-+ if (!os2 || typeof os2.typoAscender !== 'number' || typeof os2.typoDescender !== 'number') {
++ const isCjkFont = /^(?:Noto (?:Sans|Serif) (?:SC|TC|HK|JP|KR)|Source Han (?:Sans|Serif)(?: (?:SC|TC|HK|JP|KR))?)$/.test(font?.familyName || '');
++ const useTypoMetrics = os2?.fsSelection?.useTypoMetrics || isCjkFont;
++ if (!useTypoMetrics || typeof os2?.typoAscender !== 'number' || typeof os2?.typoDescender !== 'number') {
+ return { ascent: font?.ascent || 0, descent: font?.descent || 0, lineGap: font?.lineGap || 0 };
+ }
+ return {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a2e01cf57..134cd997f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -12,7 +12,7 @@ overrides:
uuid@<11.1.1: ^11.1.1
patchedDependencies:
- '@react-pdf/textkit': 83ab8b75b1df9fb96f5b36ad308d9d27c91ff7d16d6345cb15dd0567c70e7e59
+ '@react-pdf/textkit': 092a6fe8baf3c472a81cdf2ab52a00ec98ef3364e1b8e744005dbcf219a8a213
importers:
@@ -11180,7 +11180,7 @@ snapshots:
'@react-pdf/paginate': 1.0.1
'@react-pdf/primitives': 4.4.0
'@react-pdf/stylesheet': 6.3.2
- '@react-pdf/textkit': 7.0.1(patch_hash=83ab8b75b1df9fb96f5b36ad308d9d27c91ff7d16d6345cb15dd0567c70e7e59)
+ '@react-pdf/textkit': 7.0.1(patch_hash=092a6fe8baf3c472a81cdf2ab52a00ec98ef3364e1b8e744005dbcf219a8a213)
'@react-pdf/types': 2.14.0
emoji-regex-xs: 1.0.0
queue: 6.0.2
@@ -11201,7 +11201,7 @@ snapshots:
'@babel/runtime': 7.29.7
'@react-pdf/fns': 3.1.3
'@react-pdf/primitives': 4.4.0
- '@react-pdf/textkit': 7.0.1(patch_hash=83ab8b75b1df9fb96f5b36ad308d9d27c91ff7d16d6345cb15dd0567c70e7e59)
+ '@react-pdf/textkit': 7.0.1(patch_hash=092a6fe8baf3c472a81cdf2ab52a00ec98ef3364e1b8e744005dbcf219a8a213)
'@react-pdf/types': 2.14.0
abs-svg-path: 0.1.1
color-string: 2.1.4
@@ -11239,7 +11239,7 @@ snapshots:
dependencies:
'@react-pdf/primitives': 4.4.0
- '@react-pdf/[email protected](patch_hash=83ab8b75b1df9fb96f5b36ad308d9d27c91ff7d16d6345cb15dd0567c70e7e59)':
+ '@react-pdf/[email protected](patch_hash=092a6fe8baf3c472a81cdf2ab52a00ec98ef3364e1b8e744005dbcf219a8a213)':
dependencies:
'@react-pdf/fns': 3.1.3
'@react-pdf/hyphenate': 0.1.0