#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
fix(viewer): render non-embedded fonts with matching widths (#8629)
Reece Browne5c59188758c1
diff --git a/.github/dependabot.yml b/.github/dependabot.ymlindex f1a0789951..19814cd951 100644--- a/.github/dependabot.yml+++ b/.github/dependabot.yml@@ -68,6 +68,8 @@ updates:default-days: 7rebase-strategy: "auto"groups:+ # An @embedpdf/engines bump fails the build until the local font patch is+ # re-checked: see the upgrade steps in frontend/scripts/embedpdfFontFallbackPatch.mts.embedpdf:patterns:- "@embedpdf/*"diff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex b9c70d89aa..8aebd7f066 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -13,7 +13,7 @@"@cantoo/pdf-lib": "^2.8.2","@dnd-kit/core": "^6.3.1","@embedpdf/core": "^2.15.1",- "@embedpdf/engines": "^2.14.4",+ "@embedpdf/engines": "2.15.1","@embedpdf/models": "^2.15.1","@embedpdf/plugin-annotation": "^2.15.1","@embedpdf/plugin-attachment": "^2.15.1",diff --git a/frontend/package.json b/frontend/package.jsonindex 0d013eefdf..d41bfcf2b7 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -10,7 +10,7 @@"@cantoo/pdf-lib": "^2.8.2","@dnd-kit/core": "^6.3.1","@embedpdf/core": "^2.15.1",- "@embedpdf/engines": "^2.14.4",+ "@embedpdf/engines": "2.15.1","@embedpdf/models": "^2.15.1","@embedpdf/plugin-annotation": "^2.15.1","@embedpdf/plugin-attachment": "^2.15.1",diff --git a/frontend/scripts/embedpdfFontFallbackPatch.mts b/frontend/scripts/embedpdfFontFallbackPatch.mtsnew file mode 100644index 0000000000..736bcbd9a6--- /dev/null+++ b/frontend/scripts/embedpdfFontFallbackPatch.mts@@ -0,0 +1,171 @@+// In-memory patch for the pinned @embedpdf/engines: its PDFium font fallback+// picks a face by charset only, ignoring the requested font name and the+// serif/fixed-pitch flags PDFium passes, so a non-embedded Times or Courier+// renders in the sans fallback with mismatched glyph widths. The patch lets the+// fallback config name serif, monospace and wide-sans (Verdana-proportioned)+// faces, chosen from the face name and then from those flags.+//+// Applied while Vite reads the package (bundling, the dev prebundle, vitest),+// never written to node_modules, so read-only installs and builds that skip+// lifecycle scripts work unchanged.+//+// Upgrading @embedpdf/engines (any other version fails the build):+// 1. Remove embedpdfFontFallbackPlugin() from vite.config.ts and+// vitest.config.ts, then run src/editor/core/services/pdfiumFontFallback.test.ts.+// 2. If it passes, the engine selects fallback faces by family itself: delete+// this file and those two plugin entries. If it fails only because the+// engine names the option differently, move `fontFamilies` in+// pdfiumFontFallback.ts to that name and delete this file.+// 3. Otherwise restore the plugin entries, check each EDITS anchor still occurs+// once in the new engine's dist files, then update EXPECTED_VERSION, bump+// PATCH_REVISION and re-run the test.+import { readFileSync } from "node:fs";+import path from "node:path";+import type { Plugin as EsbuildPlugin } from "esbuild";+import type { Plugin } from "vite";++const EXPECTED_VERSION = "2.15.1";+// Part of the plugin names, which feed Vite's dependency-prebundle hash: a+// change here rebuilds caches that hold the previous engine code.+const PATCH_REVISION = "2";+const ENGINES_DIST =+ /[\\/]node_modules[\\/]@embedpdf[\\/]engines[\\/]dist[\\/]/;+const MATCH_ANCHOR =+ "findBestFontMatch(charset, requestedWeight, requestedItalic) {";++// Families apply to every charset configured with the ANSI face, so the config+// alone decides which scripts get them. Compared by value: the worker receives+// a structured clone of the config. Names win over PDFium's pitch-family bits+// (FXFONT_FF_FIXEDPITCH = 1, FXFONT_FF_ROMAN = 16). The inserted code uses no+// single quotes or backslashes, so the same text is valid inside the worker+// engine's single-quoted source string.+const FAMILY_METHOD = `stirlingFamilyEntry(charset, pitchFamily, face) {+ const { fonts, fontFamilies: families } = this.fontConfig;+ if (!families || fonts[charset] === void 0 || JSON.stringify(fonts[charset]) !== JSON.stringify(fonts[0])) return void 0;+ const raw = (face || "").toLowerCase();+ const name = (raw.includes("+") ? raw.slice(raw.indexOf("+") + 1) : raw).replace(/[^a-z]/g, "");+ const has = (prefixes) => prefixes.some((prefix) => name.startsWith(prefix));+ let family = null;+ if (/mono(?!type)/.test(name) || has(["courier", "consolas", "menlo", "monaco", "lucidaconsole", "andale"])) family = "monospace";+ else if (has(["verdana", "dejavusans", "bitstreamvera"])) family = "wide";+ else if (has(["helvetica", "arial", "liberationsans", "nimbussans", "notosans", "calibri", "tahoma", "segoe", "trebuchet", "centurygothic"])) family = null;+ else if (has(["times", "georgia", "cambria", "garamond", "bookantiqua", "palatino", "liberationserif", "nimbusroman", "dejavuserif", "notoserif", "centuryschoolbook"])) family = "serif";+ else if (pitchFamily & 1) family = "monospace";+ else if (pitchFamily & 16) family = "serif";+ return family ? families[family] : void 0;+ }+ `;++const EDITS: { from: string | RegExp; to: string }[] = [+ {+ from: "const result = this.findBestFontMatch(charset, weight, italic);",+ to: "const result = this.findBestFontMatch(charset, weight, italic, this.stirlingFamilyEntry(charset, pitchFamily, face));",+ },+ {+ from: MATCH_ANCHOR,+ to: `${FAMILY_METHOD}findBestFontMatch(charset, requestedWeight, requestedItalic, familyEntry) {`,+ },+ {+ // Bundlers rename `fonts` per chunk (fonts, fonts2), so match the identifier.+ from: /const entry = (fonts\d*)\[charset\] \?\? defaultFont;/,+ to: "const entry = familyEntry ?? $1[charset] ?? defaultFont;",+ },+];++const escapeNewlines = (text: string) => text.replace(/\n/g, "\\n");+const fail = (file: string, reason: string): never => {+ throw new Error(+ `[embedpdf-font-fallback] ${path.basename(file)}: ${reason}. ` ++ "Follow the upgrade steps at the top of " ++ "frontend/scripts/embedpdfFontFallbackPatch.mts.",+ );+};++let checkedVersion = false;+function assertPinnedVersion(file: string) {+ if (checkedVersion) return;+ const pkgDir =+ file.slice(0, file.search(ENGINES_DIST)) ++ "/node_modules/@embedpdf/engines";+ const version = JSON.parse(+ readFileSync(path.join(pkgDir, "package.json"), "utf8"),+ ).version;+ if (version !== EXPECTED_VERSION) {+ fail(+ file,+ `expected @embedpdf/engines@${EXPECTED_VERSION}, found ${version}`,+ );+ }+ checkedVersion = true;+}++/**+ * Returns the patched source of an @embedpdf/engines file that carries the font+ * fallback manager, or null for any other file. Throws when a carrier file does+ * not match every anchor exactly once.+ */+export function patchEmbedpdfFontFallback(+ code: string,+ file: string,+): string | null {+ if (!ENGINES_DIST.test(file)) return null;+ // Before the anchor search: an engine that renamed the method would+ // otherwise skip the patch silently.+ assertPinnedVersion(file);+ const anchorAt = code.indexOf(MATCH_ANCHOR);+ if (anchorAt === -1) return null;+ // The worker engine embeds its source as a string literal with `\n` escapes.+ const escaped = code.startsWith("\\n", anchorAt + MATCH_ANCHOR.length);+ let out = code;+ for (const edit of EDITS) {+ const to = escaped ? escapeNewlines(edit.to) : edit.to;+ if (edit.from instanceof RegExp) {+ const count = out.match(new RegExp(edit.from, "g"))?.length ?? 0;+ if (count !== 1)+ fail(file, `expected one match for ${edit.from}, found ${count}`);+ out = out.replace(edit.from, to);+ } else {+ const from = escaped ? escapeNewlines(edit.from) : edit.from;+ const count = out.split(from).length - 1;+ if (count !== 1)+ fail(+ file,+ `expected one match for "${edit.from.slice(0, 50)}", found ${count}`,+ );+ out = out.replace(from, () => to);+ }+ }+ return out;+}++/** Applies the patch to bundled code, to Vite's dev prebundle and to vitest. */+export function embedpdfFontFallbackPlugin(): Plugin {+ const prebundle: EsbuildPlugin = {+ name: `embedpdf-font-fallback-${PATCH_REVISION}`,+ setup(build) {+ build.onLoad(+ { filter: /[\\/]@embedpdf[\\/]engines[\\/]dist[\\/].*\.c?js$/ },+ (args) => {+ const patched = patchEmbedpdfFontFallback(+ readFileSync(args.path, "utf8"),+ args.path,+ );+ return patched === null+ ? undefined+ : { contents: patched, loader: "js" };+ },+ );+ },+ };+ return {+ name: `embedpdf-font-fallback-${PATCH_REVISION}`,+ enforce: "pre",+ config: () => ({+ optimizeDeps: { esbuildOptions: { plugins: [prebundle] } },+ }),+ transform(code, id) {+ const patched = patchEmbedpdfFontFallback(code, id.split("?")[0]);+ return patched === null ? null : { code: patched, map: null };+ },+ };+}diff --git a/frontend/src/editor/core/services/pdfiumFontFallback.test.ts b/frontend/src/editor/core/services/pdfiumFontFallback.test.tsindex 8d13266692..e63ab8331b 100644--- a/frontend/src/editor/core/services/pdfiumFontFallback.test.ts+++ b/frontend/src/editor/core/services/pdfiumFontFallback.test.ts@@ -1,8 +1,16 @@// @vitest-environment nodeimport { describe, expect, it } from "vitest";import { FontCharset } from "@embedpdf/models";+import { FontFallbackManager, type FontEntry } from "@embedpdf/engines";import { getLocalFontFallbackConfig } from "@editor/services/pdfiumFontFallback";+const fontUrls = (entry: FontEntry | undefined): string[] =>+ entry === undefined+ ? []+ : typeof entry === "string"+ ? [entry]+ : (Array.isArray(entry) ? entry : [entry]).map((v) => v.url);+describe("pdfiumFontFallback", () => {it("generates a self-hosted font fallback configuration without external CDN URLs", () => {const config = getLocalFontFallbackConfig();@@ -10,8 +18,7 @@ describe("pdfiumFontFallback", () => {expect(config.baseUrl).toContain("/fonts");expect(config.defaultFont).toBe("NotoSans-Regular.ttf");- expect(config.fonts[FontCharset.ANSI]).toBe("NotoSans-Regular.ttf");- expect(config.fonts[FontCharset.DEFAULT]).toBe("NotoSans-Regular.ttf");+ expect(config.fonts[FontCharset.VIETNAMESE]).toBe("NotoSans-Regular.ttf");expect(config.fonts[FontCharset.SHIFTJIS]).toBe("NotoSansJP-Regular.ttf");expect(config.fonts[FontCharset.HANGEUL]).toBe("NotoSansKR-Regular.ttf");expect(config.fonts[FontCharset.GB2312]).toBe("NotoSansSC-Regular.ttf");@@ -24,12 +31,87 @@ describe("pdfiumFontFallback", () => {expect(config.baseUrl).not.toContain("jsdelivr");for (const fontVal of Object.values(config.fonts)) {- expect(String(fontVal)).not.toContain("http://");- expect(String(fontVal)).not.toContain("https://");- expect(String(fontVal)).not.toContain("jsdelivr");+ for (const url of fontUrls(fontVal)) {+ expect(url).not.toContain("http://");+ expect(url).not.toContain("https://");+ expect(url).not.toContain("jsdelivr");+ }}});+ it("draws Latin, Greek and Cyrillic with a face metric-compatible with Helvetica and Arial", () => {+ const config = getLocalFontFallbackConfig();++ for (const charset of [+ FontCharset.ANSI,+ FontCharset.DEFAULT,+ FontCharset.EASTERNEUROPEAN,+ FontCharset.GREEK,+ FontCharset.CYRILLIC,+ ]) {+ expect(config.fonts[charset]).toEqual([+ { url: "LiberationSans-Regular.ttf", weight: 400 },+ { url: "LiberationSans-Bold.ttf", weight: 700 },+ { url: "LiberationSans-Italic.ttf", weight: 400, italic: true },+ { url: "LiberationSans-BoldItalic.ttf", weight: 700, italic: true },+ ]);+ }+ });++ // Exercises the local @embedpdf/engines patch; fails if an install skipped it.+ it("selects serif and monospace faces by name, then by PDFium's pitch flags", () => {+ const manager = new FontFallbackManager(getLocalFontFallbackConfig());+ const internals = manager as unknown as {+ mapFont(+ weight: number,+ italic: number,+ charset: number,+ pitchFamily: number,+ face: string,+ ): number;+ fontHandles: Map<number, { url: string }>;+ };+ const fileFor = (charset: number, pitchFamily: number, face: string) => {+ const handle = internals.mapFont(400, 0, charset, pitchFamily, face);+ return internals.fontHandles.get(handle)?.url.split("/").pop();+ };++ expect(fileFor(FontCharset.ANSI, 0, "Times-Roman")).toBe(+ "LiberationSerif-Regular.ttf",+ );+ expect(fileFor(FontCharset.ANSI, 0, "ABCDEF+CourierNewPSMT")).toBe(+ "LiberationMono-Regular.ttf",+ );+ expect(fileFor(FontCharset.ANSI, 0, "Helvetica")).toBe(+ "LiberationSans-Regular.ttf",+ );+ // Mono variants of sans families, and a sans face with a serif-like prefix.+ expect(fileFor(FontCharset.ANSI, 0, "NotoSansMono-Regular")).toBe(+ "LiberationMono-Regular.ttf",+ );+ expect(fileFor(FontCharset.ANSI, 0, "CenturyGothic")).toBe(+ "LiberationSans-Regular.ttf",+ );+ expect(fileFor(FontCharset.ANSI, 0, "Verdana")).toBe("DejaVuSans.ttf");+ expect(fileFor(FontCharset.ANSI, 0, "Tahoma")).toBe(+ "LiberationSans-Regular.ttf",+ );+ // Unknown names fall back to the serif (16) and fixed-pitch (1) flags.+ expect(fileFor(FontCharset.ANSI, 16, "HouseSerif")).toBe(+ "LiberationSerif-Regular.ttf",+ );+ expect(fileFor(FontCharset.EASTERNEUROPEAN, 1, "HouseMono")).toBe(+ "LiberationMono-Regular.ttf",+ );+ expect(fileFor(FontCharset.ANSI, 0, "HouseSans")).toBe(+ "LiberationSans-Regular.ttf",+ );+ // Non-Latin charsets keep their own faces whatever the flags say.+ expect(fileFor(FontCharset.ARABIC, 16, "Times-Roman")).toBe(+ "NotoSansArabic-Regular.ttf",+ );+ });+it("maps every charset with a face and leaves the rest to the default", () => {const config = getLocalFontFallbackConfig();@@ -47,9 +129,11 @@ describe("pdfiumFontFallback", () => {expect(config.fonts[FontCharset[name]]).toBeUndefined();continue;}- expect(String(config.fonts[FontCharset[name]])).toMatch(- /^NotoSans[A-Za-z-]*\.ttf$/,- );+ const urls = fontUrls(config.fonts[FontCharset[name]]);+ expect(urls.length).toBeGreaterThan(0);+ for (const url of urls) {+ expect(url).toMatch(/^(NotoSans|LiberationSans)[A-Za-z-]*\.ttf$/);+ }}});});diff --git a/frontend/src/editor/core/services/pdfiumFontFallback.ts b/frontend/src/editor/core/services/pdfiumFontFallback.tsindex 2170fba0e6..41931910fe 100644--- a/frontend/src/editor/core/services/pdfiumFontFallback.ts+++ b/frontend/src/editor/core/services/pdfiumFontFallback.ts@@ -1,7 +1,29 @@import { getFontBaseUrl } from "@editor/services/fontBaseUrl";-import type { FontFallbackConfig } from "@embedpdf/engines";+import type {+ FontEntry,+ FontFallbackConfig,+ FontVariant,+} from "@embedpdf/engines";import { FontCharset } from "@embedpdf/models";+const liberation = (family: "Sans" | "Serif" | "Mono"): FontVariant[] => [+ { url: `Liberation${family}-Regular.ttf`, weight: 400 },+ { url: `Liberation${family}-Bold.ttf`, weight: 700 },+ { url: `Liberation${family}-Italic.ttf`, weight: 400, italic: true },+ { url: `Liberation${family}-BoldItalic.ttf`, weight: 700, italic: true },+];++// The WASM PDFium build ships no standard-14 fonts, so a document's+// non-embedded Helvetica or Arial is drawn with this face. It must share their+// advance widths: a wider face overruns the PDF's glyph positions, swallowing+// word spaces or pushing justified lines past the margin.+const METRIC_COMPATIBLE_SANS = liberation("Sans");++/** `fontFamilies` is read by the engine patch in scripts/embedpdfFontFallbackPatch.mts. */+export type LocalFontFallbackConfig = FontFallbackConfig & {+ fontFamilies: Record<"serif" | "monospace" | "wide", FontEntry>;+};+/*** Fonts the engine substitutes for characters missing from a document.*@@ -11,17 +33,17 @@ import { FontCharset } from "@embedpdf/models";* is what keeps that CDN out of the render path. Charsets without a face* (SYMBOL) resolve to `defaultFont`.*/-export function getLocalFontFallbackConfig(): FontFallbackConfig {+export function getLocalFontFallbackConfig(): LocalFontFallbackConfig {return {baseUrl: getFontBaseUrl(),defaultFont: "NotoSans-Regular.ttf",fonts: {- [FontCharset.ANSI]: "NotoSans-Regular.ttf",- [FontCharset.DEFAULT]: "NotoSans-Regular.ttf",- [FontCharset.CYRILLIC]: "NotoSans-Regular.ttf",- [FontCharset.GREEK]: "NotoSans-Regular.ttf",+ [FontCharset.ANSI]: METRIC_COMPATIBLE_SANS,+ [FontCharset.DEFAULT]: METRIC_COMPATIBLE_SANS,+ [FontCharset.CYRILLIC]: METRIC_COMPATIBLE_SANS,+ [FontCharset.GREEK]: METRIC_COMPATIBLE_SANS,[FontCharset.VIETNAMESE]: "NotoSans-Regular.ttf",- [FontCharset.EASTERNEUROPEAN]: "NotoSans-Regular.ttf",+ [FontCharset.EASTERNEUROPEAN]: METRIC_COMPATIBLE_SANS,[FontCharset.ARABIC]: "NotoSansArabic-Regular.ttf",[FontCharset.HEBREW]: "NotoSansHebrew-Regular.ttf",[FontCharset.THAI]: "NotoSansThai-Regular.ttf",@@ -30,5 +52,17 @@ export function getLocalFontFallbackConfig(): FontFallbackConfig {[FontCharset.GB2312]: "NotoSansSC-Regular.ttf",[FontCharset.CHINESEBIG5]: "NotoSansTC-Regular.ttf",},+ // Times, Courier and Verdana counterparts with matching widths; selected+ // by the local @embedpdf/engines patch (scripts/embedpdfFontFallbackPatch.mts).+ fontFamilies: {+ serif: liberation("Serif"),+ monospace: liberation("Mono"),+ wide: [+ { url: "DejaVuSans.ttf", weight: 400 },+ { url: "DejaVuSans-Bold.ttf", weight: 700 },+ { url: "DejaVuSans-Oblique.ttf", weight: 400, italic: true },+ { url: "DejaVuSans-BoldOblique.ttf", weight: 700, italic: true },+ ],+ },};}diff --git a/frontend/vite.config.ts b/frontend/vite.config.tsindex 9593d4b0bc..db7bae2ffe 100644--- a/frontend/vite.config.ts+++ b/frontend/vite.config.ts@@ -12,6 +12,8 @@ import type { PreRenderedAsset } from "rollup";import tsconfigPaths from "vite-tsconfig-paths";// oxlint-disable-next-line no-restricted-imports -- config runs in node, before the aliases existimport { iconSvgr } from "./scripts/icons/svgrOptions.mts";+// oxlint-disable-next-line no-restricted-imports -- config runs in node, before the aliases exist+import { embedpdfFontFallbackPlugin } from "./scripts/embedpdfFontFallbackPatch.mts";import { viteStaticCopy } from "vite-plugin-static-copy";const gzipPromise = promisify(gzip);@@ -276,15 +278,17 @@ function compressStaticCopyPlugin(): PluginOption {// The TTFs are only ever requested through the backend, which serves the// .br/.gz siblings and falls back to its own classpath copy of the raw// file. Shipping the raw set in dist would duplicate ~100 MB for nothing.- // NotoSans-Regular.ttf stays: the text editor's Unicode fallback fetches- // it directly, and static hosts have no classpath to fall back to.+ // Kept: NotoSans-Regular.ttf, which the text editor's Unicode fallback+ // fetches directly, and the viewer's Latin fallback faces+ // (services/pdfiumFontFallback.ts). Static hosts have no classpath to+ // fall back to.+ const keptFonts =+ /^(NotoSans-Regular|Liberation(Sans|Serif|Mono)-(Regular|Bold|Italic|BoldItalic)|DejaVuSans(-Bold|-Oblique|-BoldOblique)?)\.ttf$/;const fontsDir = path.join(distDir, "fonts");const fontEntries = await fs.readdir(fontsDir).catch(() => []);await Promise.all(fontEntries- .filter(- (name) => name.endsWith(".ttf") && name !== "NotoSans-Regular.ttf",- )+ .filter((name) => name.endsWith(".ttf") && !keptFonts.test(name)).map((name) => fs.rm(path.join(fontsDir, name), { force: true })),);},@@ -574,6 +578,7 @@ export default defineConfig(async ({ mode, command }) => {__DEV_WORKTREE_LABEL__: JSON.stringify(devWorktreeLabel),},plugins: [+ embedpdfFontFallbackPlugin(),iconSvgr(),react(),...(runSubpath ? [subpathBareRedirectPlugin(runSubpath)] : []),diff --git a/frontend/vitest.config.ts b/frontend/vitest.config.tsindex e561b46837..00a8279def 100644--- a/frontend/vitest.config.ts+++ b/frontend/vitest.config.ts@@ -4,6 +4,8 @@ import react from "@vitejs/plugin-react-swc";import tsconfigPaths from "vite-tsconfig-paths";// oxlint-disable-next-line no-restricted-imports -- config runs in node, before the aliases existimport { iconSvgr } from "./scripts/icons/svgrOptions.mts";+// oxlint-disable-next-line no-restricted-imports -- config runs in node, before the aliases exist+import { embedpdfFontFallbackPlugin } from "./scripts/embedpdfFontFallbackPatch.mts";const frontendPackage: { dependencies: Record<string, string> } = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8"),@@ -68,8 +70,11 @@ export default defineConfig({environment: "jsdom",globals: true,setupFiles: ["./src/editor/core/setupTests.ts"],+ // Transformed rather than externalized, so the font fallback patch applies.+ server: { deps: { inline: [/@embedpdf\/engines/] } },},plugins: [+ embedpdfFontFallbackPlugin(),iconSvgr(),react(),tsconfigPaths({