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): keep unsupported character replacements from overlapping text (RX-211) (#3885)

Amruth Pillai8f8f5d8713c8
diff --git a/docs/guides/customizing-typography.mdx b/docs/guides/customizing-typography.mdx
index 54a1ee61c..81cc9f9a2 100644
--- a/docs/guides/customizing-typography.mdx
+++ b/docs/guides/customizing-typography.mdx
@@ -86,6 +86,15 @@ If you set an exact body line height or **Vertical spacing** in Advanced that do
The list contains Google Fonts plus the PDF standard fonts Helvetica, Courier and Times-Roman. Fonts for Chinese, Japanese, Korean, Arabic, Hebrew, Thai, Indic scripts (such as Devanagari, Bengali, Tamil and Telugu), Amharic and Khmer text are included, and missing characters fall back to a matching Noto font so they still print.
+If none of the available fonts can draw a character, the PDF shows a question mark and leaves room for it so the following text stays readable. The export warning names the missing character. Your saved text stays unchanged, so you can choose another font or edit the character and export again.
+
+<Frame caption="An unavailable symbol prints as a question mark without overlapping the following text">
+ <img
+ src="/images/guides/customizing-typography/font-replacement.png"
+ alt="Fictional Avery Morgan resume with three question marks in place of unavailable symbols and readable text after them"
+ />
+</Frame>
+
### Exact typography settings
**Advanced → Typography** has the same fields for **Body** and **Heading**, plus one **Hyphenation** switch for both:
diff --git a/docs/images/guides/customizing-typography/font-replacement.png b/docs/images/guides/customizing-typography/font-replacement.png
new file mode 100644
index 000000000..33bb65be6
Binary files /dev/null and b/docs/images/guides/customizing-typography/font-replacement.png differ
diff --git a/packages/pdf/src/forme/export-text.integration.test.ts b/packages/pdf/src/forme/export-text.integration.test.ts
index 85cf12e10..1badf0ab8 100644
--- a/packages/pdf/src/forme/export-text.integration.test.ts
+++ b/packages/pdf/src/forme/export-text.integration.test.ts
@@ -1,10 +1,12 @@
+import type { ResumeData } from "@reactive-resume/schema/resume/data";
import { execFileSync } from "node:child_process";
import { expect, it } from "vite-plus/test";
import * as forme from "@formepdf/core";
-import { act } from "react";
+import { act, createElement } from "react";
import { defaultResumeData } from "@reactive-resume/schema/resume/default";
import { createResumePdfFile } from "../server";
-import { lostCharacters, renderResume } from "./render";
+import { Document, Page, Text } from "./primitives";
+import { lostCharacters, renderResume, renderResumeElement } from "./render";
function summaryResume(html: string, font = "Noto Sans", locale = "en-US") {
const data = structuredClone(defaultResumeData);
@@ -57,11 +59,51 @@ it.each(["span", "em", "a"])(
},
);
-it('exports characters no font can draw as "?" and names them', { timeout: 60_000 }, async () => {
- expect(await exportText("<p>Unsupported \u{10FFFF}</p>")).toContain("Unsupported ?");
- const result = await act(() => renderResume(forme, { data: summaryResume("<p>Unsupported \u{10FFFF}</p>") }));
- expect(lostCharacters(result.warnings)).toEqual([expect.stringContaining("U+10FFFF")]);
-});
+it(
+ 'measures the "?" it draws for unsupported characters, retaining their warning and authored text',
+ { timeout: 60_000 },
+ async () => {
+ const html = "<p>Before \u{10FFFF}\u{10FFFF}\u{10FFFF} AFTER</p>";
+ const data = summaryResume(html, "IBM Plex Serif");
+ const result = await act(() => renderResume(forme, { data }));
+ const bbox = execFileSync("pdftotext", ["-bbox", "-", "-"], { input: result.pdf, encoding: "utf8" });
+ const replacementEnd = Number(bbox.match(/<word[^>]*xMax="([\d.]+)"[^>]*>\?\?\?<\/word>/)?.[1]);
+ const followingStart = Number(bbox.match(/<word xMin="([\d.]+)"[^>]*>AFTER<\/word>/)?.[1]);
+ expect(replacementEnd).toBeGreaterThan(0);
+ expect(followingStart).toBeGreaterThan(replacementEnd);
+ expect(lostCharacters(result.warnings)).toEqual([expect.stringContaining("U+10FFFF")]);
+ expect(data.summary.content).toBe(html);
+ },
+);
+
+type MixedFontsProps = { data: ResumeData };
+
+function MixedFonts({ data }: MixedFontsProps) {
+ return createElement(
+ Document,
+ null,
+ createElement(
+ Page,
+ null,
+ createElement(Text, { style: { fontFamily: "Helvetica" } }, `Before ${data.basics.name} AFTER`),
+ createElement(Text, { style: { fontFamily: "STIX Two Text" } }, data.basics.name),
+ ),
+ );
+}
+
+it(
+ "preserves a character supported by another text's font when repairing its unsupported occurrence",
+ { timeout: 60_000 },
+ async () => {
+ const data = summaryResume("", "STIX Two Text");
+ data.basics.name = "∕";
+ const result = await act(() => renderResumeElement(forme, createElement(MixedFonts, { data })));
+ const text = execFileSync("pdftotext", ["-", "-"], { input: result.pdf, encoding: "utf8" });
+ expect(text).toContain("Before ? AFTER");
+ expect(text).toContain("∕");
+ expect(lostCharacters(result.warnings)).toEqual([expect.stringContaining("U+2215")]);
+ },
+);
it.each([
["अमित शर्मा", "hi-IN"],
diff --git a/packages/pdf/src/forme/render.ts b/packages/pdf/src/forme/render.ts
index 6b508d057..0a5eb91aa 100644
--- a/packages/pdf/src/forme/render.ts
+++ b/packages/pdf/src/forme/render.ts
@@ -2,7 +2,7 @@ import type { ResumeRenderOptions } from "../context";
import type { PageMap } from "../page-map";
import type { ConvertedDocument } from "./to-forme";
import type { ElementInfo, RenderWithLayoutResult } from "@formepdf/core";
-import type { FormeDocument } from "@formepdf/react";
+import type { FormeDocument, FormeNode, FormeStyle } from "@formepdf/react";
import type { ResumeData } from "@reactive-resume/schema/resume/data";
import type { Template } from "@reactive-resume/schema/templates";
import type { Locale } from "@reactive-resume/utils/locale";
@@ -67,6 +67,69 @@ export function lostCharacters(warnings: readonly string[]): string[] | null {
return [...new Set(lost.flatMap((warning) => warning.match(/"[^"]*" \(U\+[0-9A-F]+\)/g) ?? []))];
}
+const uncoveredCharacters = (warnings: readonly string[]) =>
+ new Set((lostCharacters(warnings) ?? []).map((character) => character.slice(1, character.lastIndexOf('"'))));
+
+/** Substitute in render-owned text only, asking the same engine which fonts actually need the replacement. */
+async function substituteMissingGlyphs(
+ document: FormeDocument,
+ characters: ReadonlySet<string>,
+ draw: (document: FormeDocument) => Promise<RenderWithLayoutResult>,
+ cache: Map<string, Set<string>>,
+) {
+ const groups = new Map<string, { style: FormeStyle; characters: Set<string>; text: { content: string }[] }>();
+ const collect = (text: { content: string }, inherited: FormeStyle) => {
+ const candidates = [...text.content].filter((character) => characters.has(character));
+ if (candidates.length === 0) return;
+ const style = {
+ fontFamily: inherited.fontFamily ?? "Helvetica",
+ fontWeight: inherited.fontWeight ?? 400,
+ fontStyle: inherited.fontStyle ?? "Normal",
+ };
+ const key = JSON.stringify(style);
+ let group = groups.get(key);
+ if (!group) groups.set(key, (group = { style, characters: new Set(), text: [] }));
+ for (const character of candidates) group.characters.add(character);
+ group.text.push(text);
+ };
+ const visit = (node: FormeNode, inherited: FormeStyle) => {
+ const style = { ...inherited, ...node.style };
+ const { kind } = node;
+ if (kind.type === "Text" || kind.type === "Heading") {
+ if (kind.runs?.length) for (const run of kind.runs) collect(run, { ...style, ...run.style });
+ else collect(kind, style);
+ }
+ for (const child of node.children) visit(child, style);
+ };
+ for (const child of document.children) visit(child, document.defaultStyle ?? {});
+ let changed = false;
+ for (const [key, group] of groups) {
+ const content = [...group.characters].sort().join("");
+ const cacheKey = `${key}:${content}`;
+ let missing = cache.get(cacheKey);
+ if (!missing) {
+ const probe = await draw({
+ ...document,
+ children: [
+ {
+ kind: { type: "Page", config: document.defaultPage },
+ style: {},
+ children: [{ kind: { type: "Text", content }, style: group.style, children: [] }],
+ },
+ ],
+ });
+ missing = uncoveredCharacters(probe.warnings);
+ cache.set(cacheKey, missing);
+ }
+ for (const text of group.text) {
+ const replacement = [...text.content].map((character) => (missing.has(character) ? "?" : character)).join("");
+ changed ||= replacement !== text.content;
+ text.content = replacement;
+ }
+ }
+ return changed;
+}
+
/** Every character in the document's strings, sorted: its text, plus style values and links, which cost little. */
function documentText(document: FormeDocument): string {
const characters = new Set<string>();
@@ -330,6 +393,9 @@ export async function renderResumeElement(
const presenceAheadNodes = new Map<string, number>();
// Every pass draws the same text, so the fonts are prepared once, from the first pass's document.
let formeFonts: typeof fonts | undefined;
+ const missingGlyphs = new Set<string>();
+ const missingGlyphWarnings = new Set<string>();
+ const glyphSubstitutions = new Map<string, Set<string>>();
const layOutOnce = async (keepNestedRowsWhole: boolean) => {
const convert = (freeFormHeights?: (number | undefined)[]) =>
toFormeDocument(tree, {
@@ -352,7 +418,21 @@ export async function renderResumeElement(
)
: fonts;
}
- return engine.renderSerializedDocWithLayout({ ...document, fonts: formeFonts.map((font) => ({ ...font })) });
+ const preparedFonts = formeFonts;
+ const draw = (input: FormeDocument) =>
+ engine.renderSerializedDocWithLayout({ ...input, fonts: preparedFonts.map((font) => ({ ...font })) });
+ if (missingGlyphs.size) await substituteMissingGlyphs(document, missingGlyphs, draw, glyphSubstitutions);
+ let result = await draw(document);
+ const uncovered = uncoveredCharacters(result.warnings);
+ if (uncovered.size) {
+ for (const character of uncovered) missingGlyphs.add(character);
+ for (const warning of result.warnings)
+ if (uncoveredCharacters([warning]).size) missingGlyphWarnings.add(warning);
+ // shortcut: Forme 0.29 measures missing glyphs before substituting "?"; remove this retry when fixed upstream.
+ if (await substituteMissingGlyphs(document, missingGlyphs, draw, glyphSubstitutions))
+ result = await draw(document);
+ }
+ return result;
};
let converted = convert();
let result = await render(converted);
@@ -438,6 +518,8 @@ export async function renderResumeElement(
pageMap: extractPageMap(result.layout),
missingFonts: [...new Set(missing)],
layout: result.layout,
- warnings: [...fontWarnings, ...imageWarnings, ...warnings, ...result.warnings],
+ warnings: [
+ ...new Set([...fontWarnings, ...imageWarnings, ...warnings, ...result.warnings, ...missingGlyphWarnings]),
+ ],
};
}
diff --git a/tests/e2e/specs/ai-provider-gating.spec.ts b/tests/e2e/specs/ai-provider-gating.spec.ts
index 22f16a39d..a401cd52d 100644
--- a/tests/e2e/specs/ai-provider-gating.spec.ts
+++ b/tests/e2e/specs/ai-provider-gating.spec.ts
@@ -28,7 +28,7 @@ async function saveProvider(page: Page, label: string) {
async function connectProvider(page: Page) {
await page.getByRole("button", { name: /^Add AI provider/ }).click();
- const dialog = page.getByRole("dialog");
+ const dialog = page.getByRole("dialog", { name: "Add provider", exact: true });
await dialog.getByRole("combobox", { name: "Provider", exact: true }).click();
await page.getByRole("option", { name: "OpenAI-compatible", exact: true }).click();
await dialog.getByLabel("Base URL").fill(stub.baseURL);
@@ -36,7 +36,7 @@ async function connectProvider(page: Page) {
await dialog.getByLabel("API key", { exact: true }).fill("stub-key");
await dialog.getByRole("button", { name: "Save and test", exact: true }).click();
await consent(page);
- await expect(dialog).toBeHidden();
+ await expect(page.getByRole("dialog")).toHaveCount(0);
}
test("provider retries update one row, Test preserves Off, and no public catalog is requested", async ({
@@ -56,7 +56,7 @@ test("provider retries update one row, Test preserves Off, and no public catalog
await page.getByRole("dialog").getByRole("button", { name: "Close", exact: true }).click();
await expect(page.getByRole("heading", { name: "AI is ready", exact: true })).toBeHidden();
await page.getByRole("button", { name: /^Add AI provider/ }).click();
- const dialog = page.getByRole("dialog");
+ const dialog = page.getByRole("dialog", { name: "Add provider", exact: true });
await dialog.getByRole("combobox", { name: "Provider", exact: true }).click();
await page.getByRole("option", { name: "OpenAI-compatible", exact: true }).click();
await dialog.getByLabel("Base URL").fill(stub.baseURL);
@@ -73,7 +73,7 @@ test("provider retries update one row, Test preserves Off, and no public catalog
await dialog.getByLabel("API key", { exact: true }).fill("stub-key");
await dialog.getByRole("button", { name: "Save and test", exact: true }).click();
await consent(page);
- await expect(dialog).toBeHidden();
+ await expect(page.getByRole("dialog")).toHaveCount(0);
await expect(page.getByRole("heading", { name: "AI is ready", exact: true })).toBeVisible();
const ready = page.getByRole("region", { name: "AI is ready", exact: true });
for (const name of ["Improve selected line", "Review writing", "Check fit", "New cover letter", "Ask the coach"])