Skip to content

Open-source document signature platform. Not affiliated with DocuSign.

TypeScript

Draw signed PDFs and certificates with Unicode fonts

Claude9c71520dfde8
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 9241d7b..44c7de1 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -9,25 +9,42 @@ replace the licenses for redistributed third-party files.
### 1. Great Vibes font
- **Bundled path:** `src/assets/fonts/GreatVibes-Regular.ttf`
-- **Used by:** `src/lib/services/pdf-finalize.ts`
+- **Used by:** `src/lib/services/pdf-fonts.ts` (typed signatures)
- **License:** SIL Open Font License 1.1
-- **Full license text:** `src/assets/fonts/LICENSE-OFL.txt`
+- **Full license text:** `src/assets/fonts/LICENSE-GreatVibes-OFL.txt`
-### 2. Mozilla PDF.js legacy worker asset
+### 2. Noto Sans fonts
+
+- **Bundled paths:** `src/assets/fonts/NotoSans-Regular.ttf`, `src/assets/fonts/NotoSans-Bold.ttf`
+- **Source project:** https://github.com/notofonts/latin-greek-cyrillic (version 2.015, unhinted)
+- **Used by:** `src/lib/services/pdf-fonts.ts` (text on signed PDFs and audit certificates)
+- **License:** SIL Open Font License 1.1
+- **Full license text:** `src/assets/fonts/LICENSE-NotoSans-OFL.txt`
+
+### 3. Noto Sans CJK JP font (modified)
+
+- **Bundled path:** `src/assets/fonts/NotoSansCJKjp-Regular.ttf`
+- **Source project:** https://github.com/notofonts/noto-cjk (`Sans/Variable/TTF/NotoSansCJKjp-VF.ttf`)
+- **Used by:** `src/lib/services/pdf-fonts.ts` (Chinese, Japanese and Korean text)
+- **License:** SIL Open Font License 1.1
+- **Full license text:** `src/assets/fonts/LICENSE-NotoSansCJK-OFL.txt`
+- **Notes:** This is a modified version: fixed at weight 400, with only the default glyph of each character kept. The license file records how it was made.
+
+### 4. Mozilla PDF.js legacy worker asset
- **Bundled path:** `public/pdfjs/5.5.207/legacy/build/pdf.worker.min.mjs`
- **Source project:** Mozilla PDF.js
- **License:** Apache License 2.0
- **Full license text:** `LICENSES/Apache-2.0.txt`
-### 3. PDF.js standard fonts - PDFium-derived Foxit font files
+### 5. PDF.js standard fonts - PDFium-derived Foxit font files
- **Bundled path:** `public/pdfjs/5.5.207/standard_fonts/Foxit*.pfb`
- **Source project:** Mozilla PDF.js standard font assets
- **License text already bundled at:** `public/pdfjs/5.5.207/standard_fonts/LICENSE_FOXIT`
- **Notes:** The bundled notice identifies these files under the PDFium Authors copyright and license terms distributed with PDF.js.
-### 4. PDF.js standard fonts - Liberation Sans
+### 6. PDF.js standard fonts - Liberation Sans
- **Bundled path:** `public/pdfjs/5.5.207/standard_fonts/LiberationSans-*.ttf`
- **Source project:** Mozilla PDF.js standard font assets
diff --git a/next.config.ts b/next.config.ts
index 5b44178..3a709c7 100644
--- a/next.config.ts
+++ b/next.config.ts
@@ -12,6 +12,15 @@ const nextConfig: NextConfig = {
images: {
unoptimized: true,
},
+ // Finished PDFs are drawn with fonts read from disk at runtime, cut down
+ // by a WebAssembly subsetter (src/lib/services/pdf-fonts.ts). Listing the
+ // files here makes sure they are copied into the deployed functions.
+ outputFileTracingIncludes: {
+ "/api/**": [
+ "./src/assets/fonts/*.ttf",
+ "./node_modules/harfbuzzjs/dist/harfbuzz-subset.wasm",
+ ],
+ },
};
export default nextConfig;
diff --git a/package-lock.json b/package-lock.json
index 8bf53db..8ed6589 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -20,6 +20,7 @@
"botid": "^1.5.13",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
+ "harfbuzzjs": "1.6.4",
"lucide-react": "^0.577.0",
"next": "16.4.6",
"node-forge": "1.4.2",
@@ -6520,6 +6521,12 @@
"dev": true,
"license": "ISC"
},
+ "node_modules/harfbuzzjs": {
+ "version": "1.6.4",
+ "resolved": "https://registry.npmjs.org/harfbuzzjs/-/harfbuzzjs-1.6.4.tgz",
+ "integrity": "sha512-T/PyfhVt1gGR2Tkf5KJUj1DQFkVBXHw552lS1iLEEDhV1Lukb3eq1pk2ov85kgbT2YUiZtJBTak9w+M7YgzUEQ==",
+ "license": "MIT"
+ },
"node_modules/has-bigints": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.1.0.tgz",
diff --git a/package.json b/package.json
index f4f6f78..de8d99f 100644
--- a/package.json
+++ b/package.json
@@ -35,6 +35,7 @@
"botid": "^1.5.13",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
+ "harfbuzzjs": "1.6.4",
"lucide-react": "^0.577.0",
"next": "16.4.6",
"node-forge": "1.4.2",
diff --git a/src/assets/fonts/LICENSE-OFL.txt b/src/assets/fonts/LICENSE-GreatVibes-OFL.txt
similarity index 100%
rename from src/assets/fonts/LICENSE-OFL.txt
rename to src/assets/fonts/LICENSE-GreatVibes-OFL.txt
diff --git a/src/assets/fonts/LICENSE-NotoSans-OFL.txt b/src/assets/fonts/LICENSE-NotoSans-OFL.txt
new file mode 100644
index 0000000..6843f31
--- /dev/null
+++ b/src/assets/fonts/LICENSE-NotoSans-OFL.txt
@@ -0,0 +1,93 @@
+Copyright 2022 The Noto Project Authors (https://github.com/notofonts/latin-greek-cyrillic)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+https://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/src/assets/fonts/LICENSE-NotoSansCJK-OFL.txt b/src/assets/fonts/LICENSE-NotoSansCJK-OFL.txt
new file mode 100644
index 0000000..d3b6cdd
--- /dev/null
+++ b/src/assets/fonts/LICENSE-NotoSansCJK-OFL.txt
@@ -0,0 +1,106 @@
+Copyright 2014-2021 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source'.
+
+NotoSansCJKjp-Regular.ttf in this folder is a modified version of the variable
+font NotoSansCJKjp-VF.ttf from https://github.com/notofonts/noto-cjk: it is
+fixed at weight 400 and keeps only the default glyph of each character, with
+the layout and vertical-metrics tables removed. It was made with fontTools:
+
+ fonttools varLib.instancer NotoSansCJKjp-VF.ttf wght=400 \
+ --update-name-table -o cjk-static.ttf
+ pyftsubset cjk-static.ttf --unicodes='*' --layout-features='' \
+ --drop-tables+=vhea,vmtx,BASE,STAT,GSUB,GPOS,GDEF --no-hinting \
+ --notdef-outline --name-IDs='*' --name-languages='0x409' \
+ --output-file=NotoSansCJKjp-Regular.ttf
+
+This Font Software is licensed under the SIL Open Font License,
+Version 1.1.
+
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font
+creation efforts of academic and linguistic communities, and to
+provide a free and open framework in which fonts may be shared and
+improved in partnership with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply to
+any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software
+components as distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to,
+deleting, or substituting -- in part or in whole -- any of the
+components of the Original Version, by changing formats or by porting
+the Font Software to a new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed,
+modify, redistribute, and sell modified and unmodified copies of the
+Font Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components, in
+Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the
+corresponding Copyright Holder. This restriction only applies to the
+primary font name as presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created using
+the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/src/assets/fonts/NotoSans-Bold.ttf b/src/assets/fonts/NotoSans-Bold.ttf
new file mode 100644
index 0000000..b7f8290
Binary files /dev/null and b/src/assets/fonts/NotoSans-Bold.ttf differ
diff --git a/src/assets/fonts/NotoSans-Regular.ttf b/src/assets/fonts/NotoSans-Regular.ttf
new file mode 100644
index 0000000..cb427d5
Binary files /dev/null and b/src/assets/fonts/NotoSans-Regular.ttf differ
diff --git a/src/assets/fonts/NotoSansCJKjp-Regular.ttf b/src/assets/fonts/NotoSansCJKjp-Regular.ttf
new file mode 100644
index 0000000..acbe3e0
Binary files /dev/null and b/src/assets/fonts/NotoSansCJKjp-Regular.ttf differ
diff --git a/src/lib/services/pdf-finalize.test.ts b/src/lib/services/pdf-finalize.test.ts
new file mode 100644
index 0000000..30a14ac
--- /dev/null
+++ b/src/lib/services/pdf-finalize.test.ts
@@ -0,0 +1,224 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { PDFDocument } from "pdf-lib";
+
+import type { AuditEventRecord, EnvelopeRecord } from "../schemas/envelope.ts";
+import type { FieldRecord } from "../schemas/field.ts";
+import type { SignerRecord } from "../schemas/signer.ts";
+import {
+ renderEnvelopeCertificatePdf,
+ renderFinalizedEnvelopePdf,
+} from "./pdf-finalize.ts";
+import { sha256Hex } from "./pdf-seal.ts";
+import type { StorageService } from "./storage.ts";
+
+// Names and values outside Windows-1252 used to fail the whole signing with
+// "WinAnsi cannot encode". These tests run the two renderers on such text.
+
+const TITLE = "Umowa o dzieło – Łódź / 業務委託契約書";
+const SIGNER_NAME = "Łukasz Żółć";
+const SECOND_SIGNER_NAME = "山田 太郎";
+const TEXT_VALUE = "Санкт-Петербург, 東京都";
+
+async function extractText(pdfBytes: Uint8Array): Promise<string> {
+ const pdfjs = await import("pdfjs-dist/legacy/build/pdf.mjs");
+ const document = await pdfjs.getDocument({
+ data: new Uint8Array(pdfBytes),
+ useSystemFonts: false,
+ verbosity: 0,
+ }).promise;
+ const parts: string[] = [];
+
+ for (let pageNumber = 1; pageNumber <= document.numPages; pageNumber += 1) {
+ const page = await document.getPage(pageNumber);
+ const content = await page.getTextContent();
+
+ parts.push(
+ content.items.map((item: { str?: string }) => item.str ?? "").join(" "),
+ );
+ }
+
+ await document.destroy();
+
+ return parts.join("\n");
+}
+
+async function makeFixture() {
+ const sourceDocument = await PDFDocument.create();
+
+ sourceDocument.addPage([612, 792]);
+
+ const sourcePdf = await sourceDocument.save();
+ const now = 1_800_000_000;
+ const envelope: EnvelopeRecord = {
+ completedAt: now,
+ createdAt: now - 500,
+ declinedAt: null,
+ evidenceKey: null,
+ id: "envelope-1",
+ pageCount: 1,
+ sentAt: now - 400,
+ signedPdfKey: null,
+ sourcePdfFilename: "umowa.pdf",
+ sourcePdfHash: sha256Hex(sourcePdf),
+ sourcePdfKey: "source.pdf",
+ sourcePdfSizeBytes: sourcePdf.byteLength,
+ status: "completed",
+ title: TITLE,
+ updatedAt: now,
+ userId: "user-1",
+ voidedAt: null,
+ };
+ const signers: SignerRecord[] = [
+ {
+ createdAt: now - 500,
+ email: "[email protected]",
+ id: "signer-1",
+ name: SIGNER_NAME,
+ signedAt: now - 100,
+ signOrder: 1,
+ status: "signed",
+ updatedAt: now - 100,
+ },
+ {
+ createdAt: now - 500,
+ email: "[email protected]",
+ id: "signer-2",
+ name: SECOND_SIGNER_NAME,
+ signedAt: now,
+ signOrder: 2,
+ status: "signed",
+ updatedAt: now,
+ },
+ ];
+ const baseField = {
+ createdAt: now - 500,
+ envelopeId: envelope.id,
+ height: 0.05,
+ page: 1,
+ required: true,
+ submittedAt: now - 100,
+ updatedAt: now - 100,
+ width: 0.4,
+ x: 0.1,
+ };
+ const fields: FieldRecord[] = [
+ {
+ ...baseField,
+ id: "field-1",
+ inputMethod: "typed",
+ signerId: "signer-1",
+ type: "signature",
+ value: SIGNER_NAME,
+ y: 0.1,
+ },
+ {
+ ...baseField,
+ id: "field-2",
+ inputMethod: "typed",
+ signerId: "signer-2",
+ type: "signature",
+ value: SECOND_SIGNER_NAME,
+ y: 0.2,
+ },
+ {
+ ...baseField,
+ id: "field-3",
+ signerId: "signer-1",
+ type: "text",
+ value: TEXT_VALUE,
+ y: 0.3,
+ },
+ {
+ ...baseField,
+ id: "field-4",
+ signerId: "signer-1",
+ type: "text",
+ value: "first line\nsecond line",
+ y: 0.4,
+ },
+ ];
+ const auditEvents: AuditEventRecord[] = [
+ {
+ actorEmail: "[email protected]",
+ actorType: "signer",
+ createdAt: now - 100,
+ envelopeId: envelope.id,
+ event: "signed",
+ id: "event-1",
+ ipAddress: "203.0.113.7",
+ metadata: {
+ signerEmail: "[email protected]",
+ signerId: "signer-1",
+ signerName: SIGNER_NAME,
+ },
+ userAgent: "Mozilla/5.0 (テスト)",
+ },
+ ];
+ const storageService = {
+ getObject: async () => ({
+ body: sourcePdf,
+ contentLength: sourcePdf.byteLength,
+ contentType: "application/pdf",
+ }),
+ } as unknown as StorageService;
+
+ return { auditEvents, envelope, fields, signers, storageService };
+}
+
+const saveUnsealed = (pdfDocument: PDFDocument) => pdfDocument.save();
+
+test("the signed PDF stamps values in any of the supported scripts", async () => {
+ const fixture = await makeFixture();
+ const pdfBytes = await renderFinalizedEnvelopePdf(
+ {
+ auditEvents: fixture.auditEvents,
+ completedAt: fixture.envelope.completedAt!,
+ envelope: fixture.envelope,
+ fields: fixture.fields,
+ signers: fixture.signers,
+ sourcePdfKey: fixture.envelope.sourcePdfKey,
+ },
+ { seal: saveUnsealed, storageService: fixture.storageService },
+ );
+ const text = (await extractText(pdfBytes)).replace(/\s+/g, " ");
+
+ assert.ok(text.includes(SIGNER_NAME));
+ assert.ok(text.includes(SECOND_SIGNER_NAME));
+ assert.ok(text.includes(TEXT_VALUE));
+ // A line break in a value used to fail too. It is drawn as a space.
+ assert.ok(text.includes("first line second line"));
+ // Only the glyphs in use are embedded, next to the script font.
+ assert.ok(
+ pdfBytes.byteLength < 500_000,
+ `signed PDF is ${String(pdfBytes.byteLength)} bytes`,
+ );
+});
+
+test("the certificate prints names, titles and browser strings as they are", async () => {
+ const fixture = await makeFixture();
+ const pdfBytes = await renderEnvelopeCertificatePdf(
+ {
+ auditEvents: fixture.auditEvents,
+ envelope: fixture.envelope,
+ signers: fixture.signers,
+ },
+ { seal: saveUnsealed },
+ );
+ const text = (await extractText(pdfBytes)).replace(/\s+/g, " ");
+
+ assert.ok(text.includes("Łódź"));
+ assert.ok(text.includes("業務委託契約書"));
+ assert.ok(text.includes(SIGNER_NAME));
+ assert.ok(text.includes(SECOND_SIGNER_NAME));
+ assert.ok(text.includes("テスト"));
+ assert.ok(
+ pdfBytes.byteLength < 200_000,
+ `certificate is ${String(pdfBytes.byteLength)} bytes`,
+ );
+
+ const reloaded = await PDFDocument.load(pdfBytes);
+
+ assert.ok(reloaded.getTitle()?.includes("業務委託契約書"));
+});
diff --git a/src/lib/services/pdf-finalize.ts b/src/lib/services/pdf-finalize.ts
index 151c9b7..3e76477 100644
--- a/src/lib/services/pdf-finalize.ts
+++ b/src/lib/services/pdf-finalize.ts
@@ -1,16 +1,6 @@
-import fs from "node:fs/promises";
-import path from "node:path";
import { randomUUID } from "node:crypto";
-import fontkit from "@pdf-lib/fontkit";
-import {
- PDFDocument,
- type PDFFont,
- type PDFImage,
- type PDFPage,
- rgb,
- StandardFonts,
-} from "pdf-lib";
+import { PDFDocument, type PDFImage, type PDFPage, rgb } from "pdf-lib";
import {
auditEventRecordSchema,
@@ -21,6 +11,7 @@ import type { FieldRecord } from "../schemas/field.ts";
import type { SignerRecord } from "../schemas/signer.ts";
import { canonicalJson } from "../utils/canonical-json.ts";
import { normalizedRectToPdfRect } from "../utils/pdf-coords.ts";
+import { embedTextFaces, type TextFace } from "./pdf-fonts.ts";
import { sha256Hex } from "./pdf-seal.ts";
import { saveInstallSealedPdf, type SealPurpose } from "./seal-identity.ts";
import {
@@ -33,20 +24,11 @@ import {
type StorageService,
} from "./storage.ts";
-const TYPED_SIGNATURE_FONT_PATH = path.join(
- process.cwd(),
- "src",
- "assets",
- "fonts",
- "GreatVibes-Regular.ttf",
-);
const DEFAULT_AUDIT_PAGE_SIZE = {
height: 792,
width: 612,
} as const;
-let typedSignatureFontBytesPromise: Promise<Uint8Array> | null = null;
-
export type StoredSealedPdf = StorageObjectRef & {
body: Uint8Array;
sha256: string;
@@ -68,15 +50,6 @@ export type PdfSealer = (
const defaultSealer: PdfSealer = (pdfDocument, purpose) =>
saveInstallSealedPdf(pdfDocument, purpose);
-/**
- * Standard PDF fonts can only draw Windows-1252 text. Evidence lines carry
- * text from browsers and email providers, so anything outside Latin-1
- * becomes "?".
- */
-function toPrintable(value: string): string {
- return value.replace(/[^\x20-\x7e\xa0-\xff]/g, "?");
-}
-
const CERTIFICATE_FINGERPRINT_VERSION = 1;
/**
@@ -155,7 +128,7 @@ function redactAuditEventForRecipients(
}
type WrappedLine = {
- font: PDFFont;
+ font: TextFace;
size: number;
text: string;
};
@@ -171,7 +144,7 @@ function formatAuditTimestamp(timestamp: number | null | undefined): string {
}
function chunkLongWord(
- font: PDFFont,
+ font: TextFace,
size: number,
maxWidth: number,
word: string,
@@ -203,7 +176,7 @@ function chunkLongWord(
}
function wrapText(
- font: PDFFont,
+ font: TextFace,
size: number,
maxWidth: number,
text: string,
@@ -247,7 +220,7 @@ function wrapText(
}
function fitTextSize(
- font: PDFFont,
+ font: TextFace,
text: string,
maxWidth: number,
maxHeight: number,
@@ -274,14 +247,6 @@ function shouldStampField(field: FieldRecord): boolean {
return typeof field.submittedAt === "number";
}
-async function getTypedSignatureFontBytes(): Promise<Uint8Array> {
- typedSignatureFontBytesPromise ??= fs
- .readFile(TYPED_SIGNATURE_FONT_PATH)
- .then((buffer) => new Uint8Array(buffer));
-
- return typedSignatureFontBytesPromise;
-}
-
function buildCompletedAuditEvent(
envelopeId: string,
generatedAt: number,
@@ -401,9 +366,8 @@ async function stampFieldValue(
field: FieldRecord,
page: PDFPage,
fonts: {
- auditBold: PDFFont;
- auditRegular: PDFFont;
- signature: PDFFont;
+ auditRegular: TextFace;
+ signature: TextFace;
},
imageCache: Map<string, PDFImage>,
pdfDocument: PDFDocument,
@@ -461,9 +425,8 @@ async function stampFieldValue(
Math.min(maxHeight, rect.heightPt * 0.9),
);
- page.drawText(signatureValue, {
+ fonts.signature.drawText(page, signatureValue, {
color: rgb(0.12, 0.12, 0.12),
- font: fonts.signature,
size: fontSize,
x: rect.xPt + padding,
y: rect.yPt + (rect.heightPt - fontSize) / 2 + fontSize * 0.1,
@@ -489,9 +452,8 @@ async function stampFieldValue(
Math.min(maxHeight, rect.heightPt * 0.64),
);
- page.drawText(textValue, {
+ fonts.auditRegular.drawText(page, textValue, {
color: rgb(0.12, 0.12, 0.12),
- font: fonts.auditRegular,
size: fontSize,
x: rect.xPt + padding,
y: rect.yPt + (rect.heightPt - fontSize) / 2 + fontSize * 0.2,
@@ -541,8 +503,8 @@ function buildAuditLines(input: {
completedAt: number;
envelope: EnvelopeRecord;
fonts: {
- bold: PDFFont;
- regular: PDFFont;
+ bold: TextFace;
+ regular: TextFace;
};
maxWidth: number;
redactForRecipients?: boolean;
@@ -557,7 +519,7 @@ function buildAuditLines(input: {
const pushParagraph = (
text: string,
- font: PDFFont,
+ font: TextFace,
size: number,
options: { gapAfter?: number; gapBefore?: number } = {},
) => {
@@ -684,19 +646,13 @@ function buildAuditLines(input: {
signerName && actor !== signerName ? `${signerName} <${actor}>` : actor;
pushParagraph(
- toPrintable(
- `${formatAuditTimestamp(event.createdAt)} | ${event.event} | ${actorLabel}`,
- ),
+ `${formatAuditTimestamp(event.createdAt)} | ${event.event} | ${actorLabel}`,
input.fonts.regular,
bodyFontSize,
);
for (const detail of describeEventEvidence(event)) {
- pushParagraph(
- toPrintable(` ${detail}`),
- input.fonts.regular,
- bodyFontSize,
- );
+ pushParagraph(` ${detail}`, input.fonts.regular, bodyFontSize);
}
}
@@ -867,8 +823,8 @@ function appendAuditTrailPages(input: {
completedAt: number;
envelope: EnvelopeRecord;
fonts: {
- bold: PDFFont;
- regular: PDFFont;
+ bold: TextFace;
+ regular: TextFace;
};
pdfDocument: PDFDocument;
redactForRecipients?: boolean;
@@ -912,9 +868,8 @@ function appendAuditTrailPages(input: {
cursorY = pageSize.height - margin;
}
- page.drawText(line.text, {
+ line.font.drawText(page, line.text, {
color: rgb(0.14, 0.14, 0.14),
- font: line.font,
size: line.size,
x: margin,
y: cursorY - line.size,
@@ -1003,9 +958,10 @@ export async function renderEnvelopeCertificatePdf(
assertTerminalEnvelope(input.envelope, "Certificates");
const pdfDocument = await PDFDocument.create();
- const auditRegularFont = await pdfDocument.embedFont(StandardFonts.Helvetica);
- const auditBoldFont = await pdfDocument.embedFont(
- StandardFonts.HelveticaBold,
+ const faces = await embedTextFaces(
+ pdfDocument,
+ [input.envelope, input.signers, input.auditEvents],
+ { bold: true, certificate: true },
);
const terminalTimestamp = resolveTerminalTimestamp(
input.envelope,
@@ -1021,18 +977,13 @@ export async function renderEnvelopeCertificatePdf(
),
completedAt: terminalTimestamp,
envelope: input.envelope,
- fonts: {
- bold: auditBoldFont,
- regular: auditRegularFont,
- },
+ fonts: faces,
pdfDocument,
redactForRecipients: input.redactForRecipients,
signedPdfSha256: input.signedPdfSha256,
signers: input.signers,
});
- pdfDocument.setTitle(
- `Audit certificate: ${toPrintable(input.envelope.title)}`,
- );
+ pdfDocument.setTitle(`Audit certificate: ${input.envelope.title}`);
pdfDocument.setProducer("SignuDoc");
return seal(pdfDocument, "certificate");
@@ -1074,20 +1025,32 @@ export async function renderFinalizedEnvelopePdf(
const pdfDocument = await PDFDocument.load(sourcePdfObject.body);
- pdfDocument.registerFontkit(fontkit);
-
- const signatureFont = await pdfDocument.embedFont(
- await getTypedSignatureFontBytes(),
- );
- const auditRegularFont = await pdfDocument.embedFont(StandardFonts.Helvetica);
- const auditBoldFont = await pdfDocument.embedFont(
- StandardFonts.HelveticaBold,
+ const stampedFields = input.fields
+ .filter(shouldStampField)
+ .sort((left, right) => left.page - right.page || left.y - right.y);
+ // The signed document embeds glyphs for the stamped values only. The
+ // certificate's wording is added when the audit trail is appended to it.
+ const faces = await embedTextFaces(
+ pdfDocument,
+ [
+ stampedFields.map((field) => field.value),
+ input.includeAuditTrail
+ ? [input.envelope, input.signers, input.auditEvents]
+ : [],
+ ],
+ {
+ bold: Boolean(input.includeAuditTrail),
+ certificate: Boolean(input.includeAuditTrail),
+ signature: stampedFields.some(
+ (field) =>
+ (field.type === "signature" || field.type === "initials") &&
+ field.inputMethod !== "drawn",
+ ),
+ },
);
const imageCache = new Map<string, PDFImage>();
- for (const field of input.fields
- .filter(shouldStampField)
- .sort((left, right) => left.page - right.page || left.y - right.y)) {
+ for (const field of stampedFields) {
const page = pdfDocument.getPage(field.page - 1);
if (!page) {
@@ -1099,11 +1062,7 @@ export async function renderFinalizedEnvelopePdf(
await stampFieldValue(
field,
page,
- {
- auditBold: auditBoldFont,
- auditRegular: auditRegularFont,
- signature: signatureFont,
- },
+ { auditRegular: faces.regular, signature: faces.signature },
imageCache,
pdfDocument,
storageService,
@@ -1121,10 +1080,7 @@ export async function renderFinalizedEnvelopePdf(
auditEvents: stripCompletedAuditEvents(input.auditEvents),
completedAt: input.completedAt,
envelope: input.envelope,
- fonts: {
- bold: auditBoldFont,
- regular: auditRegularFont,
- },
+ fonts: faces,
pdfDocument,
signers: input.signers,
});
diff --git a/src/lib/services/pdf-fonts.test.ts b/src/lib/services/pdf-fonts.test.ts
new file mode 100644
index 0000000..68ce361
--- /dev/null
+++ b/src/lib/services/pdf-fonts.test.ts
@@ -0,0 +1,149 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { PDFDocument } from "pdf-lib";
+
+import {
+ collectCodePoints,
+ embedTextFaces,
+ toDrawableText,
+} from "./pdf-fonts.ts";
+
+async function extractText(pdfBytes: Uint8Array): Promise<string> {
+ const pdfjs = await import("pdfjs-dist/legacy/build/pdf.mjs");
+ const document = await pdfjs.getDocument({
+ data: new Uint8Array(pdfBytes),
+ useSystemFonts: false,
+ verbosity: 0,
+ }).promise;
+ const parts: string[] = [];
+
+ for (let pageNumber = 1; pageNumber <= document.numPages; pageNumber += 1) {
+ const page = await document.getPage(pageNumber);
+ const content = await page.getTextContent();
+
+ parts.push(
+ content.items.map((item: { str?: string }) => item.str ?? "").join(""),
+ );
+ }
+
+ await document.destroy();
+
+ return parts.join("\n");
+}
+
+test("toDrawableText keeps one line of visible characters", () => {
+ assert.equal(toDrawableText("a\tb\nc\r\nd"), "a b c d");
+ assert.equal(toDrawableText("9:41 AM"), "9:41 AM");
+ assert.equal(toDrawableText("zero​width"), "zerowidth");
+ // Decomposed "é" is drawn as the single composed character.
+ assert.equal(toDrawableText("Café"), "Café");
+ assert.equal(toDrawableText("\ud800"), "");
+});
+
+test("collectCodePoints walks every string in a value", () => {
+ const codePoints = collectCodePoints([
+ { name: "Ab", nested: { value: "c" } },
+ null,
+ 7,
+ ["山"],
+ ]);
+
+ assert.deepEqual(
+ [...codePoints].sort((left, right) => left - right),
+ [0x41, 0x62, 0x63, 0x5c71],
+ );
+});
+
+test("text outside Windows-1252 is drawn and can be read back", async () => {
+ const lines = [
+ "Zażółć gęślą jaźń Łukasz",
+ "Привет мир Ελληνικά Việt",
+ "契約書 山田太郎 한국어 签名",
+ ];
+ const pdfDocument = await PDFDocument.create();
+ const faces = await embedTextFaces(pdfDocument, lines, {
+ bold: true,
+ certificate: true,
+ signature: true,
+ });
+ const page = pdfDocument.addPage([612, 400]);
+
+ lines.forEach((line, index) => {
+ faces.regular.drawText(page, line, {
+ size: 12,
+ x: 40,
+ y: 340 - index * 30,
+ });
+ faces.bold.drawText(page, line, { size: 12, x: 40, y: 240 - index * 30 });
+ });
+ faces.signature.drawText(page, "Łukasz 山田", { size: 24, x: 40, y: 100 });
+
+ const pdfBytes = await pdfDocument.save();
+ const text = await extractText(pdfBytes);
+
+ for (const line of lines) {
+ assert.ok(text.includes(line), `missing: ${line}`);
+ }
+
+ assert.ok(text.includes("Łukasz 山田"));
+ // Three subset fonts plus the whole script font: the 14 MB CJK font must
+ // not have been embedded whole.
+ assert.ok(
+ pdfBytes.byteLength < 700_000,
+ `PDF is ${String(pdfBytes.byteLength)} bytes`,
+ );
+});
+
+test("a mixed line is split into runs, one per font", async () => {
+ const pdfDocument = await PDFDocument.create();
+ const faces = await embedTextFaces(pdfDocument, [
+ "Signed by 山田 太郎 today",
+ ]);
+ const runs = faces.regular.runs("Signed by 山田 太郎 today");
+
+ assert.deepEqual(
+ runs.map((run) => run.text),
+ ["Signed by ", "山田 太郎 ", "today"],
+ );
+ assert.equal(runs[0]!.font, runs[2]!.font);
+ assert.notEqual(runs[0]!.font, runs[1]!.font);
+ assert.ok(faces.regular.widthOfTextAtSize("山田", 10) > 0);
+});
+
+test("a character no font has becomes U+FFFD instead of failing", async () => {
+ const pdfDocument = await PDFDocument.create();
+ const faces = await embedTextFaces(pdfDocument, ["مرحبا שלום 😀 ok"]);
+ const page = pdfDocument.addPage([400, 100]);
+
+ assert.doesNotThrow(() => {
+ faces.regular.drawText(page, "مرحبا שלום 😀 ok", {
+ size: 12,
+ x: 10,
+ y: 50,
+ });
+ // Text that was never announced to embedTextFaces is replaced too.
+ faces.regular.drawText(page, "山", { size: 12, x: 10, y: 20 });
+ });
+
+ const text = await extractText(await pdfDocument.save());
+
+ assert.match(text, /�+ �+ � ok/);
+});
+
+test("without a subsetter whole Latin fonts are embedded and CJK is left out", async () => {
+ const pdfDocument = await PDFDocument.create();
+ const faces = await embedTextFaces(pdfDocument, ["Łukasz 山田"], {
+ subset: () => {
+ throw new Error("no subsetter");
+ },
+ });
+ const page = pdfDocument.addPage([400, 100]);
+
+ faces.regular.drawText(page, "Łukasz 山田", { size: 12, x: 10, y: 50 });
+
+ const text = await extractText(await pdfDocument.save());
+
+ assert.ok(text.includes("Łukasz"));
+ assert.ok(!text.includes("山田"));
+});
diff --git a/src/lib/services/pdf-fonts.ts b/src/lib/services/pdf-fonts.ts
new file mode 100644
index 0000000..426230f
--- /dev/null
+++ b/src/lib/services/pdf-fonts.ts
@@ -0,0 +1,518 @@
+import fs from "node:fs/promises";
+import path from "node:path";
+
+import fontkit from "@pdf-lib/fontkit";
+import type { Color, PDFDocument, PDFFont, PDFPage } from "pdf-lib";
+
+// Fonts for the text SignuDoc draws into finished PDFs: field values on the
+// signed document, and every line of the audit certificate.
+//
+// The standard PDF fonts can only draw Windows-1252, and pdf-lib throws on
+// anything else, so a name such as "Łukasz" or "山田" used to fail the whole
+// signing. Text is now drawn with Noto Sans (Latin, Greek, Cyrillic) and
+// falls back to Noto Sans CJK for Chinese, Japanese and Korean. A character
+// neither font has is drawn as "\uFFFD". Drawing never throws.
+//
+// Each PDF embeds only the glyphs it uses. pdf-lib's own subsetting writes
+// fonts that some readers cannot open, so the subset is cut with HarfBuzz
+// and embedded whole.
+//
+// Not handled: right-to-left scripts (Arabic, Hebrew) and scripts that need
+// glyph shaping (Thai, the Indic scripts). Those draw as "\uFFFD".
+
+// Each path is spelled out so that Next.js file tracing copies the file into
+// the deployed function.
+const FONT_PATHS = {
+ bold: path.join(process.cwd(), "src", "assets", "fonts", "NotoSans-Bold.ttf"),
+ cjk: path.join(
+ process.cwd(),
+ "src",
+ "assets",
+ "fonts",
+ "NotoSansCJKjp-Regular.ttf",
+ ),
+ regular: path.join(
+ process.cwd(),
+ "src",
+ "assets",
+ "fonts",
+ "NotoSans-Regular.ttf",
+ ),
+ signature: path.join(
+ process.cwd(),
+ "src",
+ "assets",
+ "fonts",
+ "GreatVibes-Regular.ttf",
+ ),
+} as const;
+
+const SUBSETTER_PATH = path.join(
+ process.cwd(),
+ "node_modules",
+ "harfbuzzjs",
+ "dist",
+ "harfbuzz-subset.wasm",
+);
+
+type FontName = keyof typeof FONT_PATHS;
+
+type LoadedFont = {
+ bytes: Uint8Array;
+ characters: ReadonlySet<number>;
+};
+
+const loadedFonts = new Map<FontName, Promise<LoadedFont>>();
+
+function loadFont(name: FontName): Promise<LoadedFont> {
+ let loaded = loadedFonts.get(name);
+
+ if (!loaded) {
+ loaded = fs.readFile(FONT_PATHS[name]).then((buffer) => {
+ const bytes = new Uint8Array(buffer);
+
+ return {
+ bytes,
+ characters: new Set(fontkit.create(bytes).characterSet),
+ };
+ });
+ // A failed read is not remembered, so the next PDF tries again.
+ loaded.catch(() => loadedFonts.delete(name));
+ loadedFonts.set(name, loaded);
+ }
+
+ return loaded;
+}
+
+type SubsetterExports = {
+ free: (pointer: number) => void;
+ hb_blob_create: (
+ data: number,
+ length: number,
+ mode: number,
+ userData: number,
+ destroy: number,
+ ) => number;
+ hb_blob_destroy: (blob: number) => void;
+ hb_blob_get_data: (blob: number, length: number) => number;
+ hb_blob_get_length: (blob: number) => number;
+ hb_face_create: (blob: number, index: number) => number;
+ hb_face_destroy: (face: number) => void;
+ hb_face_reference_blob: (face: number) => number;
+ hb_set_add: (set: number, value: number) => void;
+ hb_set_clear: (set: number) => void;
+ hb_subset_input_create_or_fail: () => number;
+ hb_subset_input_destroy: (input: number) => void;
+ hb_subset_input_set: (input: number, setType: number) => number;
+ hb_subset_input_unicode_set: (input: number) => number;
+ hb_subset_or_fail: (face: number, input: number) => number;
+ malloc: (size: number) => number;
+ memory: WebAssembly.Memory;
+};
+
+const HB_MEMORY_MODE_WRITABLE = 2;
+const HB_SUBSET_SETS_LAYOUT_FEATURE_TAG = 6;
+
+let subsetterPromise: Promise<SubsetterExports> | null = null;
+
+function loadSubsetter(): Promise<SubsetterExports> {
+ if (!subsetterPromise) {
+ subsetterPromise = fs
+ .readFile(SUBSETTER_PATH)
+ .then((wasm) => WebAssembly.instantiate(wasm))
+ .then((result) => result.instance.exports as unknown as SubsetterExports);
+ subsetterPromise.catch(() => {
+ subsetterPromise = null;
+ });
+ }
+
+ return subsetterPromise;
+}
+
+/**
+ * Cuts a TrueType font down to the given characters. Layout features are
+ * dropped, so the result maps each character to one glyph and nothing more.
+ */
+function subsetFont(
+ subsetter: SubsetterExports,
+ fontBytes: Uint8Array,
+ codePoints: Iterable<number>,
+): Uint8Array {
+ const fontPointer = subsetter.malloc(fontBytes.byteLength);
+
+ if (!fontPointer) {
+ throw new Error("The font subsetter is out of memory.");
+ }
+
+ let face = 0;
+ let input = 0;
+ let subsetFace = 0;
+ let result = 0;
+
+ try {
+ // The buffer is looked up after malloc: growing the memory replaces it.
+ new Uint8Array(subsetter.memory.buffer).set(fontBytes, fontPointer);
+
+ const blob = subsetter.hb_blob_create(
+ fontPointer,
+ fontBytes.byteLength,
+ HB_MEMORY_MODE_WRITABLE,
+ 0,
+ 0,
+ );
+
+ face = subsetter.hb_face_create(blob, 0);
+ subsetter.hb_blob_destroy(blob);
+ input = subsetter.hb_subset_input_create_or_fail();
+
+ if (!input) {
+ throw new Error("The font subsetter could not start.");
+ }
+
+ const unicodes = subsetter.hb_subset_input_unicode_set(input);
+
+ for (const codePoint of codePoints) {
+ subsetter.hb_set_add(unicodes, codePoint);
+ }
+
+ subsetter.hb_set_clear(
+ subsetter.hb_subset_input_set(input, HB_SUBSET_SETS_LAYOUT_FEATURE_TAG),
+ );
+ subsetFace = subsetter.hb_subset_or_fail(face, input);
+
+ if (!subsetFace) {
+ throw new Error("The font could not be subset.");
+ }
+
+ result = subsetter.hb_face_reference_blob(subsetFace);
+
+ const offset = subsetter.hb_blob_get_data(result, 0);
+ const length = subsetter.hb_blob_get_length(result);
+
+ if (!offset || length === 0) {
+ throw new Error("The font subset came back empty.");
+ }
+
+ return new Uint8Array(subsetter.memory.buffer).slice(
+ offset,
+ offset + length,
+ );
+ } finally {
+ if (result) subsetter.hb_blob_destroy(result);
+ if (subsetFace) subsetter.hb_face_destroy(subsetFace);
+ if (input) subsetter.hb_subset_input_destroy(input);
+ if (face) subsetter.hb_face_destroy(face);
+ subsetter.free(fontPointer);
+ }
+}
+
+function isSpaceSeparator(codePoint: number): boolean {
+ return (
+ codePoint === 0x20 ||
+ codePoint === 0xa0 ||
+ codePoint === 0x1680 ||
+ (codePoint >= 0x2000 && codePoint <= 0x200a) ||
+ codePoint === 0x2028 ||
+ codePoint === 0x2029 ||
+ codePoint === 0x202f ||
+ codePoint === 0x205f ||
+ codePoint === 0x3000
+ );
+}
+
+function isInvisible(codePoint: number): boolean {
+ return (
+ // C0 and C1 controls.
+ codePoint < 0x20 ||
+ (codePoint >= 0x7f && codePoint <= 0x9f) ||
+ // Soft hyphen, zero-width characters, direction marks and embeddings,
+ // word joiner, byte-order mark, variation selectors.
+ codePoint === 0xad ||
+ (codePoint >= 0x200b && codePoint <= 0x200f) ||
+ (codePoint >= 0x202a && codePoint <= 0x202e) ||
+ (codePoint >= 0x2060 && codePoint <= 0x2064) ||
+ codePoint === 0xfeff ||
+ (codePoint >= 0xfe00 && codePoint <= 0xfe0f) ||
+ (codePoint >= 0xe0100 && codePoint <= 0xe01ef) ||
+ // Unpaired surrogates.
+ (codePoint >= 0xd800 && codePoint <= 0xdfff)
+ );
+}
+
+/**
+ * What is actually drawn for a piece of text: composed characters, one line,
+ * ordinary spaces, and nothing invisible.
+ */
+export function toDrawableText(value: string): string {
+ let drawable = "";
+
+ for (const character of value.normalize("NFC")) {
+ const codePoint = character.codePointAt(0)!;
+
+ if (
+ isSpaceSeparator(codePoint) ||
+ codePoint === 0x09 ||
+ codePoint === 0x0a ||
+ codePoint === 0x0b ||
+ codePoint === 0x0c ||
+ codePoint === 0x0d ||
+ codePoint === 0x85
+ ) {
+ drawable += " ";
+ } else if (!isInvisible(codePoint)) {
+ drawable += character;
+ }
+ }
+
+ return drawable;
+}
+
+/** Drawn in place of a character that none of the fonts has. */
+const REPLACEMENT_CHARACTER = 0xfffd;
+
+type FaceFont = {
+ characters: ReadonlySet<number>;
+ font: PDFFont;
+};
+
+export type TextRun = {
+ font: PDFFont;
+ text: string;
+};
+
+/** A font with fallbacks: each character is drawn by the first font that has it. */
+export class TextFace {
+ private readonly fonts: readonly FaceFont[];
+
+ constructor(fonts: readonly FaceFont[]) {
+ if (fonts.length === 0) {
+ throw new Error("A text face needs at least one font.");
+ }
+
+ this.fonts = fonts;
+ }
+
+ runs(value: string): TextRun[] {
+ const runs: TextRun[] = [];
+ let current: FaceFont | null = null;
+ let buffer = "";
+
+ for (const character of toDrawableText(value)) {
+ const codePoint = character.codePointAt(0)!;
+ let drawn = character;
+ let next: FaceFont | undefined =
+ // A space stays with the text before it.
+ codePoint === 0x20 && current
+ ? current
+ : this.fonts.find((entry) => entry.characters.has(codePoint));
+
+ if (!next) {
+ const replacement = this.fonts.find((entry) =>
+ entry.characters.has(REPLACEMENT_CHARACTER),
+ );
+
+ next = replacement ?? this.fonts[0]!;
+ drawn = replacement ? String.fromCodePoint(REPLACEMENT_CHARACTER) : "?";
+ }
+
+ if (current && next !== current && buffer) {
+ runs.push({ font: current.font, text: buffer });
+ buffer = "";
+ }
+
+ current = next;
+ buffer += drawn;
+ }
+
+ if (current && buffer) {
+ runs.push({ font: current.font, text: buffer });
+ }
+
+ return runs;
+ }
+
+ widthOfTextAtSize(value: string, size: number): number {
+ return this.runs(value).reduce(
+ (width, run) => width + run.font.widthOfTextAtSize(run.text, size),
+ 0,
+ );
+ }
+
+ drawText(
+ page: PDFPage,
+ value: string,
+ options: { color?: Color; size: number; x: number; y: number },
+ ): void {
+ let x = options.x;
+
+ for (const run of this.runs(value)) {
+ page.drawText(run.text, {
+ color: options.color,
+ font: run.font,
+ size: options.size,
+ x,
+ y: options.y,
+ });
+ x += run.font.widthOfTextAtSize(run.text, options.size);
+ }
+ }
+}
+
+export type PdfTextFaces = {
+ bold: TextFace;
+ regular: TextFace;
+ /** Typed signatures: a script font, falling back to the regular face. */
+ signature: TextFace;
+};
+
+/** Every code point in every string of a value, however deeply nested. */
+export function collectCodePoints(
+ value: unknown,
+ into: Set<number> = new Set(),
+): Set<number> {
+ if (typeof value === "string") {
+ for (const character of toDrawableText(value)) {
+ into.add(character.codePointAt(0)!);
+ }
+ } else if (Array.isArray(value)) {
+ for (const entry of value) {
+ collectCodePoints(entry, into);
+ }
+ } else if (value && typeof value === "object") {
+ for (const entry of Object.values(value)) {
+ collectCodePoints(entry, into);
+ }
+ }
+
+ return into;
+}
+
+/** Printable ASCII and Latin-1, plus the punctuation the certificate uses. */
+function certificateBaseline(): number[] {
+ const codePoints: number[] = [];
+
+ for (let codePoint = 0x20; codePoint <= 0x7e; codePoint += 1) {
+ codePoints.push(codePoint);
+ }
+
+ for (let codePoint = 0xa1; codePoint <= 0xff; codePoint += 1) {
+ codePoints.push(codePoint);
+ }
+
+ // En dash, em dash, curly quotes, bullet, ellipsis.
+ codePoints.push(0x2013, 0x2014, 0x2018, 0x2019, 0x201c, 0x201d);
+ codePoints.push(0x2022, 0x2026);
+
+ return codePoints;
+}
+
+type EmbedTextFacesOptions = {
+ /** Embed the bold face. The signed document itself never uses it. */
+ bold?: boolean;
+ /** Add the characters the certificate's own wording needs. */
+ certificate?: boolean;
+ /** Embed the script font for typed signatures. */
+ signature?: boolean;
+ /** For tests: replaces the HarfBuzz subsetter. */
+ subset?: (fontBytes: Uint8Array, codePoints: Iterable<number>) => Uint8Array;
+};
+
+/**
+ * Embeds the fonts a PDF needs to draw `text` (any nested value; every string
+ * in it is counted) and returns the faces to draw with.
+ */
+export async function embedTextFaces(
+ pdfDocument: PDFDocument,
+ text: unknown,
+ options: EmbedTextFacesOptions = {},
+): Promise<PdfTextFaces> {
+ const codePoints = collectCodePoints(text);
+
+ if (options.certificate) {
+ for (const codePoint of certificateBaseline()) {
+ codePoints.add(codePoint);
+ }
+ }
+
+ // Always there: the space, and what stands in for a character no font has.
+ codePoints.add(0x20);
+ codePoints.add(0x3f);
+ codePoints.add(REPLACEMENT_CHARACTER);
+ pdfDocument.registerFontkit(fontkit);
+
+ const [regular, bold, signature] = await Promise.all([
+ loadFont("regular"),
+ options.bold ? loadFont("bold") : null,
+ options.signature ? loadFont("signature") : null,
+ ]);
+ const needsCjk = [...codePoints].some(
+ (codePoint) => !regular.characters.has(codePoint),
+ );
+ const cjk = needsCjk ? await loadFont("cjk") : null;
+ let subset = options.subset ?? null;
+
+ if (!subset) {
+ try {
+ const subsetter = await loadSubsetter();
+
+ subset = (fontBytes, wanted) => subsetFont(subsetter, fontBytes, wanted);
+ } catch (error) {
+ console.error(
+ "The font subsetter could not be loaded. PDFs will embed whole fonts and leave out the CJK fallback:",
+ error,
+ );
+ }
+ }
+
+ const embed = async (
+ loaded: LoadedFont,
+ { whole = false }: { whole?: boolean } = {},
+ ): Promise<FaceFont | null> => {
+ const wanted = [...codePoints].filter((codePoint) =>
+ loaded.characters.has(codePoint),
+ );
+
+ if (whole || !subset) {
+ return {
+ characters: loaded.characters,
+ font: await pdfDocument.embedFont(loaded.bytes),
+ };
+ }
+
+ try {
+ return {
+ characters: new Set(wanted),
+ font: await pdfDocument.embedFont(subset(loaded.bytes, wanted)),
+ };
+ } catch (error) {
+ console.error("A font could not be subset for a PDF:", error);
+
+ return null;
+ }
+ };
+
+ // Without a subsetter the Latin fonts are small enough to embed whole. The
+ // CJK font is not: at 14 MB it would dwarf the document.
+ const regularFont =
+ (await embed(regular)) ?? (await embed(regular, { whole: true }))!;
+ const boldFont = bold
+ ? ((await embed(bold)) ?? (await embed(bold, { whole: true }))!)
+ : regularFont;
+ const cjkFont = cjk && subset ? await embed(cjk) : null;
+ const fallbacks = cjkFont ? [cjkFont] : [];
+ // The script font is embedded whole, as it always was: a typed signature
+ // should look the same in every document.
+ const signatureFont = signature
+ ? await embed(signature, { whole: true })
+ : null;
+
+ return {
+ bold: new TextFace([boldFont, regularFont, ...fallbacks]),
+ regular: new TextFace([regularFont, ...fallbacks]),
+ signature: new TextFace([
+ ...(signatureFont ? [signatureFont] : []),
+ regularFont,
+ ...fallbacks,
+ ]),
+ };
+}