Skip to content

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

TypeScript

Keep the spaces a signer typed inside a wrapped answer

Clauded0433c1b49fd
diff --git a/src/lib/services/pdf-finalize.test.ts b/src/lib/services/pdf-finalize.test.ts
index ea50378..09e734b 100644
--- a/src/lib/services/pdf-finalize.test.ts
+++ b/src/lib/services/pdf-finalize.test.ts
@@ -11,7 +11,9 @@ import {
findTypedValueTooLongForField,
renderEnvelopeCertificatePdf,
renderFinalizedEnvelopePdf,
+ wrapFieldText,
} from "./pdf-finalize.ts";
+import { embedTextFaces } from "./pdf-fonts.ts";
import { sha256Hex } from "./pdf-seal.ts";
import type { StorageService } from "./storage.ts";
@@ -852,3 +854,17 @@ test("a box shorter than two readable lines takes only one", async () => {
),
);
});
+
+test("spaces inside an answer are kept as they were typed", async () => {
+ const faces = await embedTextFaces(await PDFDocument.create(), [
+ "AB 12 and more words",
+ ]);
+
+ // pdf.js merges runs of spaces when it extracts text, so the lines are
+ // checked as they are laid out.
+ assert.deepEqual(wrapFieldText(faces.regular, 10, 500, "AB 12"), ["AB 12"]);
+ assert.deepEqual(
+ wrapFieldText(faces.regular, 10, 60, "AB 12 and more words"),
+ ["AB 12 and", "more words"],
+ );
+});
diff --git a/src/lib/services/pdf-finalize.ts b/src/lib/services/pdf-finalize.ts
index 3345791..ad12273 100644
--- a/src/lib/services/pdf-finalize.ts
+++ b/src/lib/services/pdf-finalize.ts
@@ -317,6 +317,53 @@ type FieldTextLayout = {
size: number;
};
+/**
+ * Wraps a field value. Unlike wrapText, the spaces inside a line are kept as
+ * the signer typed them; only those where a line breaks are dropped.
+ */
+export function wrapFieldText(
+ font: TextFace,
+ size: number,
+ maxWidth: number,
+ text: string,
+): string[] {
+ const parts = text.trim().split(/(\s+)/);
+ const lines: string[] = [];
+ let currentLine = "";
+ let pendingSpace = "";
+
+ for (let index = 0; index < parts.length; index += 2) {
+ const word = parts[index] ?? "";
+
+ if (!word) {
+ continue;
+ }
+
+ for (const chunk of chunkLongWord(font, size, maxWidth, word)) {
+ const candidate = currentLine
+ ? `${currentLine}${pendingSpace}${chunk}`
+ : chunk;
+
+ if (!currentLine || font.widthOfTextAtSize(candidate, size) <= maxWidth) {
+ currentLine = candidate;
+ } else {
+ lines.push(currentLine);
+ currentLine = chunk;
+ }
+
+ pendingSpace = "";
+ }
+
+ pendingSpace = parts[index + 1] ?? "";
+ }
+
+ if (currentLine) {
+ lines.push(currentLine);
+ }
+
+ return lines;
+}
+
function layoutAtSize(
font: TextFace,
text: string,
@@ -324,7 +371,7 @@ function layoutAtSize(
maxHeight: number,
size: number,
): FieldTextLayout {
- const lines = wrapText(font, size, maxWidth, text).map((line) => line.text);
+ const lines = wrapFieldText(font, size, maxWidth, text);
const blockHeight =
lines.length === 0
? 0