Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Stamp fields where they were placed on older rotated and cropped pages
Claude8e58c7eb9633
diff --git a/src/lib/downloads.ts b/src/lib/downloads.tsindex 733b633..7606479 100644--- a/src/lib/downloads.ts+++ b/src/lib/downloads.ts@@ -22,6 +22,7 @@ import {renderEnvelopeCertificatePdf,renderFinalizedEnvelopePdf,} from "./services/pdf-finalize.ts";+import type { StoredPageSize } from "./services/pdf-page-geometry.ts";import {createStorageService,StorageObjectNotFoundError,@@ -486,6 +487,25 @@ async function listFieldsForEnvelope(return rows.map(mapFieldRow);}+async function listPageSizesForEnvelope(+ envelopeId: string,+ database: DbExecutor,+): Promise<StoredPageSize[]> {+ return queryMany<StoredPageSize>(+ database,+ `+ SELECT+ page_number AS "pageNumber",+ width_pt AS "widthPt",+ height_pt AS "heightPt"+ FROM envelope_pages+ WHERE envelope_id = $1+ ORDER BY page_number ASC+ `,+ [envelopeId],+ );+}+export function sanitizeFileNameSegment(value: string): string {return value.trim()@@ -561,9 +581,10 @@ async function buildSignedPdfDownload(throw new DownloadAccessError("This file is no longer available.", 404);}- const [auditEvents, fields, signers] = await Promise.all([+ const [auditEvents, fields, pages, signers] = await Promise.all([listAuditEventsForEnvelope(envelope.id, database),listFieldsForEnvelope(envelope.id, database),+ listPageSizesForEnvelope(envelope.id, database),listSignersForEnvelope(envelope.id, database),]);let body: Uint8Array;@@ -575,6 +596,7 @@ async function buildSignedPdfDownload(completedAt: envelope.completedAt,envelope,fields,+ pages,signers,sourcePdfKey: envelope.sourcePdfKey,},diff --git a/src/lib/provider-signing.ts b/src/lib/provider-signing.tsindex 8f0c876..4d59a4d 100644--- a/src/lib/provider-signing.ts+++ b/src/lib/provider-signing.ts@@ -201,6 +201,7 @@ export async function startProviderSigning(const revision = await prepareSignerRevision(base, {fields: prepared.signerFields,images: prepared.images,+ pages: context.pages,signature: {fieldName: signatureFieldName(signer.name, prepared.signerIndex),name: signer.name,diff --git a/src/lib/services/pdf-finalize.test.ts b/src/lib/services/pdf-finalize.test.tsindex 2997e6a..cf3adf2 100644--- a/src/lib/services/pdf-finalize.test.ts+++ b/src/lib/services/pdf-finalize.test.ts@@ -179,6 +179,7 @@ test("the signed PDF stamps values in any of the supported scripts", async () =>envelope: fixture.envelope,fields: fixture.fields,signers: fixture.signers,+ pages: [],sourcePdfKey: fixture.envelope.sourcePdfKey,},{ seal: saveUnsealed, storageService: fixture.storageService },@@ -499,6 +500,7 @@ test("numbers and dropdown choices are stamped as text, radio buttons as rings",envelope: fixture.envelope,fields,signers: fixture.signers,+ pages: [],sourcePdfKey: fixture.envelope.sourcePdfKey,},{ seal: saveUnsealed, storageService: fixture.storageService },@@ -556,6 +558,7 @@ test("a name field is stamped with the name it was filled in with", async () =>envelope: fixture.envelope,fields: [...fixture.fields, nameField],signers: fixture.signers,+ pages: [],sourcePdfKey: fixture.envelope.sourcePdfKey,},{ seal: saveUnsealed, storageService: fixture.storageService },diff --git a/src/lib/services/pdf-finalize.ts b/src/lib/services/pdf-finalize.tsindex 0d151a7..e199ceb 100644--- a/src/lib/services/pdf-finalize.ts+++ b/src/lib/services/pdf-finalize.ts@@ -16,8 +16,10 @@ import { normalizedRectToPdfRect } from "../utils/pdf-coords.ts";import { embedTextFaces, type TextFace } from "./pdf-fonts.ts";import {drawOnDisplayedPage,+ fieldOnDisplayedPage,getDisplayedPageGeometry,type DisplayedPageGeometry,+ type StoredPageSize,} from "./pdf-page-geometry.ts";import { sha256Hex } from "./pdf-seal.ts";import { getBranding } from "../settings.ts";@@ -1357,6 +1359,8 @@ export async function renderFinalizedEnvelopePdf(envelope: EnvelopeRecord;fields: FieldRecord[];includeAuditTrail?: boolean;+ /** The envelope's stored page sizes, which fields were placed against. */+ pages: readonly StoredPageSize[];signers: SignerRecord[];sourcePdfKey: string;},@@ -1420,16 +1424,26 @@ export async function renderFinalizedEnvelopePdf(},);const imageCache = new Map<string, PDFImage>();+ const storedPages = new Map(+ input.pages.map((page) => [page.pageNumber, page]),+ );- for (const field of stampedFields) {- const page = pdfDocument.getPage(field.page - 1);+ for (const placedField of stampedFields) {+ const page = pdfDocument.getPage(placedField.page - 1);if (!page) {throw new PdfFinalizeError(- `Field ${field.id} references missing page ${field.page}.`,+ `Field ${placedField.id} references missing page ${placedField.page}.`,);}+ const geometry = getDisplayedPageGeometry(page);+ const field = fieldOnDisplayedPage(+ placedField,+ storedPages.get(placedField.page),+ geometry,+ );+await stampFieldValue(field,page,@@ -1437,6 +1451,7 @@ export async function renderFinalizedEnvelopePdf(imageCache,pdfDocument,storageService,+ geometry,);const manifestation =@@ -1479,6 +1494,7 @@ export async function finalizeEnvelope(copyRecipients?: readonly CertificateCopyRecipient[];envelope: EnvelopeRecord;fields: FieldRecord[];+ pages: readonly StoredPageSize[];signers: SignerRecord[];sourcePdf: StorageObjectRef;},@@ -1509,6 +1525,7 @@ export async function finalizeEnvelope(copyRecipients: input.copyRecipients,envelope: input.envelope,fields: input.fields,+ pages: input.pages,signers: input.signers,sourcePdfKey: input.sourcePdf.key,},diff --git a/src/lib/services/pdf-page-geometry.test.ts b/src/lib/services/pdf-page-geometry.test.tsindex 2bb30c5..5036337 100644--- a/src/lib/services/pdf-page-geometry.test.ts+++ b/src/lib/services/pdf-page-geometry.test.ts@@ -16,6 +16,10 @@ import type { FieldRecord } from "../schemas/field.ts";import type { SignerRecord } from "../schemas/signer.ts";import { importPdfDocument } from "./document-import.ts";import { renderFinalizedEnvelopePdf } from "./pdf-finalize.ts";+import {+ fieldOnDisplayedPage,+ type StoredPageSize,+} from "./pdf-page-geometry.ts";import { prepareRevisionZero, prepareSignerRevision } from "./pdf-revision.ts";import { sha256Hex } from "./pdf-seal.ts";import type { StorageService } from "./storage.ts";@@ -147,9 +151,21 @@ function field(overrides: Partial<FieldRecord>): FieldRecord {} as FieldRecord;}+/** The stored size of an envelope imported since sizes are read as shown. */+function shownSize(pageCase: PageCase): StoredPageSize[] {+ return [+ {+ heightPt: pageCase.displayed.height,+ pageNumber: 1,+ widthPt: pageCase.displayed.width,+ },+ ];+}+async function finalize(sourcePdf: Uint8Array,fields: FieldRecord[],+ pages: StoredPageSize[],): Promise<Uint8Array> {const envelope: EnvelopeRecord = {completedAt: now,@@ -196,6 +212,7 @@ async function finalize(completedAt: now,envelope,fields,+ pages,signers,sourcePdfKey: envelope.sourcePdfKey,},@@ -383,9 +400,11 @@ for (const pageCase of PAGE_CASES) {test(`a value is stamped where its field was placed on ${pageCase.name}`, async () => {const source = await makeSource(pageCase);- const pdfBytes = await finalize(source, [- field({ id: "field-1", value: VALUE }),- ]);+ const pdfBytes = await finalize(+ source,+ [field({ id: "field-1", value: VALUE })],+ shownSize(pageCase),+ );const placed = await findText(pdfBytes, VALUE);assert.ok(placed, "the value was not found on the page");@@ -407,6 +426,7 @@ for (const pageCase of PAGE_CASES) {}),],images: new Map(),+ pages: shownSize(pageCase),signature: {fieldName: "Alice Example (signer 1)",signingTime: new Date(now * 1000),@@ -465,3 +485,134 @@ for (const pageCase of PAGE_CASES) {}});}++// Envelopes imported before page sizes were read as shown stored the raw+// MediaBox. The sender placed fields on a box of that shape, with the shown+// page drawn in it as large as fits, centred. These tests place the field+// where FIELD_RECT is on the page drawn in that box, and check that it is+// stamped there.++/** The raw MediaBox size, as envelopes imported before stored it. */+function mediaBoxSize(pageCase: PageCase): StoredPageSize[] {+ const [left, bottom, right, top] = pageCase.mediaBox;++ return [{ heightPt: top - bottom, pageNumber: 1, widthPt: right - left }];+}++/** Where FIELD_RECT on the shown page is on a box of the stored shape. */+function placedOnStoredBox(pageCase: PageCase) {+ const [stored] = mediaBoxSize(pageCase);+ const { height, width } = pageCase.displayed;+ const scale = Math.min(stored!.widthPt / width, stored!.heightPt / height);+ const drawnWidth = (scale * width) / stored!.widthPt;+ const drawnHeight = (scale * height) / stored!.heightPt;++ return {+ height: FIELD_RECT.height * drawnHeight,+ width: FIELD_RECT.width * drawnWidth,+ x: (1 - drawnWidth) / 2 + FIELD_RECT.x * drawnWidth,+ y: (1 - drawnHeight) / 2 + FIELD_RECT.y * drawnHeight,+ };+}++for (const pageCase of PAGE_CASES) {+ test(`on ${pageCase.name} imported before sizes were read as shown, a value is stamped where its field was placed`, async () => {+ const source = await makeSource(pageCase);+ const pdfBytes = await finalize(+ source,+ [field({ ...placedOnStoredBox(pageCase), id: "field-1", value: VALUE })],+ mediaBoxSize(pageCase),+ );+ const placed = await findText(pdfBytes, VALUE);++ assert.ok(placed, "the value was not found on the page");+ assertShownInField(placed, pageCase);+ });++ test(`on ${pageCase.name} imported before sizes were read as shown, a signer's revision puts its annotation over the field`, async () => {+ const source = await makeSource(pageCase);+ const revision = await prepareSignerRevision(+ await prepareRevisionZero(source),+ {+ fields: [+ field({+ ...placedOnStoredBox(pageCase),+ id: "field-1",+ value: VALUE,+ }),+ ],+ images: new Map(),+ pages: mediaBoxSize(pageCase),+ signature: {+ fieldName: "Alice Example (signer 1)",+ signingTime: new Date(now * 1000),+ },+ },+ );+ const document = await PDFDocument.load(revision.bytes);+ const [annotation] = document+ .getPage(0)+ .node.Annots()!+ .asArray()+ .map((ref) => document.context.lookup(ref, PDFDict));++ assertClose(+ annotation!+ .lookup(PDFName.of("Rect"), PDFArray)+ .asArray()+ .map((entry) => Number(entry.toString())),+ pageCase.fieldBox,+ );++ const placed = await findText(+ await showAppearanceAlone(revision.bytes, 0),+ VALUE,+ );++ assert.ok(placed, "the annotation does not show the value");+ assertShownInField(placed, pageCase);+ });+}++test("a field on a page stored at the shape it is shown keeps its place", () => {+ const rect = { height: 0.1, width: 0.5, x: 0.1, y: 0.05 };++ // Same shape, other scale, as when a CropBox keeps the page's proportions.+ assert.equal(+ fieldOnDisplayedPage(+ rect,+ { heightPt: 800, widthPt: 600 },+ { heightPt: 400, widthPt: 300 },+ ),+ rect,+ );+ // Sizes as Postgres stores them, a little off in the last digits.+ assert.equal(+ fieldOnDisplayedPage(+ rect,+ { heightPt: 841.8900146484375, widthPt: 595.2760009765625 },+ { heightPt: 841.89, widthPt: 595.276 },+ ),+ rect,+ );+ // No stored size: nothing to correct against.+ assert.equal(+ fieldOnDisplayedPage(rect, undefined, { heightPt: 600, widthPt: 800 }),+ rect,+ );+});++test("a field placed on a portrait box over a landscape page moves to the page", () => {+ // A 600 x 800 box shows an 800 x 600 page at 600 x 450, 175 down from the+ // top: the page's top is at 0.21875 of the box, and it fills 0.5625 of it.+ const moved = fieldOnDisplayedPage(+ { height: 0.05625, width: 0.5, x: 0.1, y: 0.21875 + 0.05 * 0.5625 },+ { heightPt: 800, widthPt: 600 },+ { heightPt: 600, widthPt: 800 },+ );++ assertClose(+ [moved.x, moved.y, moved.width, moved.height],+ [0.1, 0.05, 0.5, 0.1],+ );+});diff --git a/src/lib/services/pdf-page-geometry.ts b/src/lib/services/pdf-page-geometry.tsindex 596ade6..276ff86 100644--- a/src/lib/services/pdf-page-geometry.ts+++ b/src/lib/services/pdf-page-geometry.ts@@ -182,3 +182,66 @@ export function displayedRectToUserSpaceBox(top: Math.max(...ys),};}++/** A page's size as stored with its envelope, which the field overlay uses. */+export type StoredPageSize = {+ heightPt: number;+ pageNumber: number;+ widthPt: number;+};++/**+ * A field's place on the shown page, from its place on the stored page.+ *+ * Fields are placed on a box laid out to the page's stored size, with the+ * shown page drawn in it as large as fits, centred. Envelopes made before+ * page sizes were read as shown stored the raw MediaBox, so on a rotated or+ * cropped page the box has another shape than the page in it, and the page+ * sits inside it with a margin. This turns the field's place on that box+ * into its place on the page, so it is stamped where the sender saw it.+ *+ * When the box has the page's shape, which is every page imported since,+ * the field is returned as it is.+ */+export function fieldOnDisplayedPage<+ Rect extends { height: number; width: number; x: number; y: number },+>(+ rect: Rect,+ stored: Pick<StoredPageSize, "heightPt" | "widthPt"> | undefined,+ geometry: Pick<DisplayedPageGeometry, "heightPt" | "widthPt">,+): Rect {+ if (+ !stored ||+ !(stored.widthPt > 0) ||+ !(stored.heightPt > 0) ||+ !(geometry.widthPt > 0) ||+ !(geometry.heightPt > 0)+ ) {+ return rect;+ }++ const boxAspect = stored.widthPt / stored.heightPt;+ const pageAspect = geometry.widthPt / geometry.heightPt;++ if (Math.abs(boxAspect - pageAspect) <= 1e-6 * pageAspect) {+ return rect;+ }++ // Measured in units of the box: the page drawn in it, and its margins.+ const scale = Math.min(+ stored.widthPt / geometry.widthPt,+ stored.heightPt / geometry.heightPt,+ );+ const drawnWidth = (scale * geometry.widthPt) / stored.widthPt;+ const drawnHeight = (scale * geometry.heightPt) / stored.heightPt;+ const left = (1 - drawnWidth) / 2;+ const top = (1 - drawnHeight) / 2;++ return {+ ...rect,+ height: rect.height / drawnHeight,+ width: rect.width / drawnWidth,+ x: (rect.x - left) / drawnWidth,+ y: (rect.y - top) / drawnHeight,+ };+}diff --git a/src/lib/services/pdf-revision.test.ts b/src/lib/services/pdf-revision.test.tsindex 9001b72..a2a0e62 100644--- a/src/lib/services/pdf-revision.test.ts+++ b/src/lib/services/pdf-revision.test.ts@@ -208,6 +208,7 @@ test("each signer's revision keeps the signatures before it valid", async (t) =>await prepareSignerRevision(revisionZero, {fields: aliceFields,images: new Map(),+ pages: [],signature: {fieldName: "Alice Example (signer 1)",name: "Alice Example",@@ -233,6 +234,7 @@ test("each signer's revision keeps the signatures before it valid", async (t) =>await prepareSignerRevision(first.bytes, {fields: bobFields,images: new Map(),+ pages: [],signature: {fieldName: "Bob Example (signer 2)",name: "Bob Example",@@ -317,6 +319,7 @@ test("a signature for other content, or by another key, is refused", async () =>const prepared = await prepareSignerRevision(revisionZero, {fields: aliceFields,images: new Map(),+ pages: [],signature: { fieldName: "Alice", signingTime: new Date() },});const otherContent = Buffer.from(@@ -361,6 +364,7 @@ test("a qualified signature needs a qualified certificate", async () => {{fields: aliceFields,images: new Map(),+ pages: [],signature: { fieldName: "Carol", signingTime: new Date() },},);@@ -386,6 +390,7 @@ test("a signature timestamp counts only when it is for the signature and verifie{fields: aliceFields,images: new Map(),+ pages: [],signature: { fieldName: "Alice", signingTime: new Date() },},);diff --git a/src/lib/services/pdf-revision.ts b/src/lib/services/pdf-revision.tsindex 4f4eb6b..53f43af 100644--- a/src/lib/services/pdf-revision.ts+++ b/src/lib/services/pdf-revision.ts@@ -20,7 +20,9 @@ import { shouldStampField, stampFieldValue } from "./pdf-finalize.ts";import { embedTextFaces } from "./pdf-fonts.ts";import {displayedRectToUserSpaceBox,+ fieldOnDisplayedPage,getDisplayedPageGeometry,+ type StoredPageSize,} from "./pdf-page-geometry.ts";import {appendIncrementalUpdate,@@ -327,10 +329,13 @@ export async function prepareSignerRevision({fields,images,+ pages,signature,}: {fields: readonly FieldRecord[];images: ReadonlyMap<string, Uint8Array>;+ /** The envelope's stored page sizes, which fields were placed against. */+ pages: readonly StoredPageSize[];signature: RevisionSignature;},): Promise<{ bytes: Uint8Array; digest: Buffer }> {@@ -359,11 +364,17 @@ export async function prepareSignerRevision(},);const imageCache = new Map<string, PDFImage>();+ const storedPages = new Map(pages.map((page) => [page.pageNumber, page]));let signaturePlaced = false;- for (const field of fields.filter(shouldStampField)) {- const page = document.getPage(field.page - 1);+ for (const placedField of fields.filter(shouldStampField)) {+ const page = document.getPage(placedField.page - 1);const geometry = getDisplayedPageGeometry(page);+ const field = fieldOnDisplayedPage(+ placedField,+ storedPages.get(placedField.page),+ geometry,+ );// Where the field is in the page's own coordinates, which is what// the annotation's rectangle is given in.const box = displayedRectToUserSpaceBox(diff --git a/src/lib/signing.ts b/src/lib/signing.tsindex 7118ab8..a70a14d 100644--- a/src/lib/signing.ts+++ b/src/lib/signing.ts@@ -2750,6 +2750,7 @@ export async function submitSigningForToken(copyRecipients,envelope: context.envelope,fields: completedFields,+ pages: context.pages,signers: completedSigners,sourcePdf: {bucketName: sourcePdfHead.bucketName,