Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Stamp fields where they were placed on rotated and cropped pages
njarrar07b904246736
diff --git a/src/lib/services/document-import.ts b/src/lib/services/document-import.tsindex e1104ce..821953b 100644--- a/src/lib/services/document-import.ts+++ b/src/lib/services/document-import.ts@@ -4,6 +4,7 @@ import { PDFDocument } from "pdf-lib";import type { EnvelopePageRecord } from "../schemas/envelope.ts";import { MAX_UPLOAD_SIZE_BYTES } from "../types/domain.ts";+import { getDisplayedPageGeometry } from "./pdf-page-geometry.ts";const PDF_MAGIC_HEADER = "%PDF-";@@ -150,11 +151,14 @@ async function parsePdfDocument(ignoreEncryption: false,});- const pages = document.getPages().map((page, index) => ({- heightPt: page.getHeight(),- pageNumber: index + 1,- widthPt: page.getWidth(),- }));+ // The size of each page as a reader shows it: the CropBox, with width and+ // height swapped on a page rotated a quarter turn. The field overlay is+ // laid out to this size, so it has to match what the browser draws.+ const pages = document.getPages().map((page, index) => {+ const { heightPt, widthPt } = getDisplayedPageGeometry(page);++ return { heightPt, pageNumber: index + 1, widthPt };+ });return {pages,diff --git a/src/lib/services/pdf-finalize.ts b/src/lib/services/pdf-finalize.tsindex 275b7d6..cf99aaf 100644--- a/src/lib/services/pdf-finalize.ts+++ b/src/lib/services/pdf-finalize.ts@@ -13,6 +13,11 @@ import { buildSignatureManifestation } from "../signature-meanings.ts";import { canonicalJson } from "../utils/canonical-json.ts";import { normalizedRectToPdfRect } from "../utils/pdf-coords.ts";import { embedTextFaces, type TextFace } from "./pdf-fonts.ts";+import {+ drawOnDisplayedPage,+ getDisplayedPageGeometry,+ type DisplayedPageGeometry,+} from "./pdf-page-geometry.ts";import { sha256Hex } from "./pdf-seal.ts";import { getBranding } from "../settings.ts";import {@@ -393,15 +398,42 @@ export async function stampFieldValue(imageCache: Map<string, PDFImage>,pdfDocument: PDFDocument,storageService: StorageService,+ // A field's place is given on the page as it is shown, so the value is+ // drawn in those coordinates. On a rotated page it comes out turned with+ // the page, and so reads upright. A caller that draws on another page+ // than the one the field is on passes that page's geometry.+ geometry: DisplayedPageGeometry = getDisplayedPageGeometry(page),): Promise<void> {if (!shouldStampField(field)) {return;}- const rect = normalizedRectToPdfRect(field, {- heightPt: page.getHeight(),- widthPt: page.getWidth(),- });+ await drawOnDisplayedPage(page, geometry, () =>+ drawFieldValue(+ field,+ page,+ geometry,+ fonts,+ imageCache,+ pdfDocument,+ storageService,+ ),+ );+}++async function drawFieldValue(+ field: FieldRecord,+ page: PDFPage,+ geometry: DisplayedPageGeometry,+ fonts: {+ auditRegular: TextFace;+ signature: TextFace;+ },+ imageCache: Map<string, PDFImage>,+ pdfDocument: PDFDocument,+ storageService: StorageService,+): Promise<void> {+ const rect = normalizedRectToPdfRect(field, geometry);const padding = getFieldPadding(rect.widthPt, rect.heightPt);switch (field.type) {@@ -549,17 +581,28 @@ export async function stampFieldValue(* Prints a Part 11 signature's manifestation just under the signature, or* just above it when the field sits at the foot of the page.*/-function stampSignatureManifestation(+async function stampSignatureManifestation(+ field: FieldRecord,+ page: PDFPage,+ font: TextFace,+ text: string,+): Promise<void> {+ const geometry = getDisplayedPageGeometry(page);++ await drawOnDisplayedPage(page, geometry, () =>+ drawSignatureManifestation(field, page, geometry, font, text),+ );+}++function drawSignatureManifestation(field: FieldRecord,page: PDFPage,+ geometry: DisplayedPageGeometry,font: TextFace,text: string,): void {- const pageWidth = page.getWidth();- const rect = normalizedRectToPdfRect(field, {- heightPt: page.getHeight(),- widthPt: pageWidth,- });+ const pageWidth = geometry.widthPt;+ const rect = normalizedRectToPdfRect(field, geometry);const margin = 2;const fullWidth = pageWidth - margin * 2;const minimumSize = 5;@@ -587,7 +630,7 @@ function stampSignatureManifestation(? rect.yPt - lineHeight: Math.min(rect.yPt + rect.heightPt + blockHeight - size,- page.getHeight() - size - margin,+ geometry.heightPt - size - margin,);lines.forEach((line, index) => {@@ -1322,7 +1365,12 @@ export async function renderFinalizedEnvelopePdf(field.type === "signature" ? manifestations.get(field.signerId) : null;if (manifestation) {- stampSignatureManifestation(field, page, faces.regular, manifestation);+ await stampSignatureManifestation(+ field,+ page,+ faces.regular,+ manifestation,+ );}}diff --git a/src/lib/services/pdf-page-geometry.test.ts b/src/lib/services/pdf-page-geometry.test.tsnew file mode 100644index 0000000..a2c1a71--- /dev/null+++ b/src/lib/services/pdf-page-geometry.test.ts@@ -0,0 +1,378 @@+import assert from "node:assert/strict";+import test from "node:test";++import {+ decodePDFRawStream,+ degrees,+ PDFArray,+ PDFDict,+ PDFDocument,+ PDFName,+ PDFRawStream,+} from "pdf-lib";++import type { EnvelopeRecord } from "../schemas/envelope.ts";+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 { prepareRevisionZero, prepareSignerRevision } from "./pdf-revision.ts";+import { sha256Hex } from "./pdf-seal.ts";+import type { StorageService } from "./storage.ts";++// A field is placed on the page as the browser shows it. These tests put one+// near the top left of the shown page, on pages that are rotated, cropped or+// whose box does not start at 0,0, and check where its value ends up in the+// page's own coordinates and on the page as pdf.js shows it.++type Box = [left: number, bottom: number, right: number, top: number];++type PageCase = {+ cropBox?: Box;+ /** The size of the page as shown. */+ displayed: { height: number; width: number };+ /** Where the field below is in the page's own coordinates. */+ fieldBox: Box;+ /** The `cm` operands that turn shown-page coordinates into the page's. */+ matrix: string | null;+ mediaBox: Box;+ name: string;+ rotate?: number;+};++// The field: a tenth in from the left, a twentieth down from the top, half+// the page wide and a tenth of it high.+const FIELD_RECT = { height: 0.1, width: 0.5, x: 0.1, y: 0.05 };+const VALUE = "Stamped";++const PAGE_CASES: PageCase[] = [+ {+ displayed: { height: 800, width: 600 },+ fieldBox: [60, 680, 360, 760],+ matrix: null,+ mediaBox: [0, 0, 600, 800],+ name: "an ordinary page",+ },+ {+ // The top left of the shown page is the bottom left of the page itself.+ displayed: { height: 600, width: 800 },+ fieldBox: [30, 80, 90, 480],+ matrix: "0 1 -1 0 600 0",+ mediaBox: [0, 0, 600, 800],+ name: "a page rotated 90",+ rotate: 90,+ },+ {+ displayed: { height: 800, width: 600 },+ fieldBox: [240, 40, 540, 120],+ matrix: "-1 0 0 -1 600 800",+ mediaBox: [0, 0, 600, 800],+ name: "a page rotated 180",+ rotate: 180,+ },+ {+ displayed: { height: 600, width: 800 },+ fieldBox: [510, 320, 570, 720],+ matrix: "0 -1 1 0 0 800",+ mediaBox: [0, 0, 600, 800],+ name: "a page rotated 270",+ rotate: 270,+ },+ {+ cropBox: [50, 100, 450, 700],+ displayed: { height: 600, width: 400 },+ fieldBox: [90, 610, 290, 670],+ matrix: "1 0 0 1 50 100",+ mediaBox: [0, 0, 600, 800],+ name: "a page with a CropBox",+ },+ {+ displayed: { height: 800, width: 600 },+ fieldBox: [160, 880, 460, 960],+ matrix: "1 0 0 1 100 200",+ mediaBox: [100, 200, 700, 1000],+ name: "a page whose MediaBox does not start at 0,0",+ },+ {+ cropBox: [150, 300, 550, 900],+ displayed: { height: 400, width: 600 },+ fieldBox: [170, 360, 210, 660],+ matrix: "0 1 -1 0 550 300",+ mediaBox: [100, 200, 700, 1000],+ name: "a rotated, cropped page with a shifted MediaBox",+ rotate: 90,+ },+];++const now = 1_800_000_000;++async function makeSource(pageCase: PageCase): Promise<Uint8Array> {+ const document = await PDFDocument.create();+ const [left, bottom, right, top] = pageCase.mediaBox;+ const page = document.addPage([right - left, top - bottom]);++ page.setMediaBox(left, bottom, right - left, top - bottom);++ if (pageCase.cropBox) {+ const [cropLeft, cropBottom, cropRight, cropTop] = pageCase.cropBox;++ page.setCropBox(+ cropLeft,+ cropBottom,+ cropRight - cropLeft,+ cropTop - cropBottom,+ );+ }++ if (pageCase.rotate) {+ page.setRotation(degrees(pageCase.rotate));+ }++ return document.save();+}++function field(overrides: Partial<FieldRecord>): FieldRecord {+ return {+ ...FIELD_RECT,+ createdAt: now - 500,+ envelopeId: "envelope-1",+ page: 1,+ required: true,+ signerId: "signer-1",+ submittedAt: now,+ type: "text",+ updatedAt: now,+ ...overrides,+ } as FieldRecord;+}++async function finalize(+ sourcePdf: Uint8Array,+ fields: FieldRecord[],+): Promise<Uint8Array> {+ const envelope: EnvelopeRecord = {+ completedAt: now,+ createdAt: now - 500,+ declinedAt: null,+ evidenceKey: null,+ id: "envelope-1",+ pageCount: 1,+ sentAt: now - 400,+ signedPdfKey: null,+ sourcePdfFilename: "scan.pdf",+ sourcePdfHash: sha256Hex(sourcePdf),+ sourcePdfKey: "source.pdf",+ sourcePdfSizeBytes: sourcePdf.byteLength,+ status: "completed",+ title: "Scan",+ updatedAt: now,+ userId: "user-1",+ voidedAt: null,+ };+ const signers: SignerRecord[] = [+ {+ createdAt: now - 500,+ email: "[email protected]",+ id: "signer-1",+ name: "Alice Example",+ signedAt: now,+ signOrder: 1,+ status: "signed",+ updatedAt: now,+ },+ ];+ const storageService = {+ getObject: async () => ({+ body: sourcePdf,+ contentLength: sourcePdf.byteLength,+ contentType: "application/pdf",+ }),+ } as unknown as StorageService;++ return renderFinalizedEnvelopePdf(+ {+ auditEvents: [],+ completedAt: now,+ envelope,+ fields,+ signers,+ sourcePdfKey: envelope.sourcePdfKey,+ },+ {+ seal: (pdfDocument: PDFDocument) => pdfDocument.save(),+ storageService,+ },+ );+}++type PlacedText = {+ /** Where the text starts in the page's own coordinates. */+ user: { x: number; y: number };+ /** The text's matrix on the shown page (y runs down). */+ viewport: number[];+ viewportSize: { height: number; width: number };+};++/** Where pdf.js finds a piece of text on the first page. */+async function findText(pdfBytes: Uint8Array, text: 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 page = await document.getPage(1);+ const viewport = page.getViewport({ scale: 1 });+ const content = await page.getTextContent();+ const item = (+ content.items as Array<{ str?: string; transform?: number[] }>+ ).find((entry) => entry.str === text);+ const placed: PlacedText | null = item?.transform+ ? {+ user: { x: item.transform[4]!, y: item.transform[5]! },+ viewport: pdfjs.Util.transform(viewport.transform, item.transform),+ viewportSize: { height: viewport.height, width: viewport.width },+ }+ : null;++ await document.destroy();++ return placed;+}++function assertInside(+ point: { x: number; y: number },+ [left, bottom, right, top]: Box,+ what: string,+) {+ assert.ok(+ point.x >= left && point.x <= right && point.y >= bottom && point.y <= top,+ `${what}: ${point.x.toFixed(2)},${point.y.toFixed(2)} is not in ${[left, bottom, right, top].join(" ")}`,+ );+}++function assertClose(actual: readonly number[], expected: readonly number[]) {+ assert.equal(actual.length, expected.length);+ actual.forEach((value, index) => {+ assert.ok(+ Math.abs(value - expected[index]!) < 0.001,+ `${actual.join(" ")} is not ${expected.join(" ")}`,+ );+ });+}++function decodeStream(stream: PDFRawStream): string {+ return Buffer.from(decodePDFRawStream(stream).decode()).toString("latin1");+}++for (const pageCase of PAGE_CASES) {+ test(`import records the size of ${pageCase.name} as it is shown`, async () => {+ const source = await makeSource(pageCase);+ const imported = await importPdfDocument({+ body: source,+ contentType: "application/pdf",+ filename: "scan.pdf",+ });++ assert.deepEqual(imported.pages, [+ {+ heightPt: pageCase.displayed.height,+ pageNumber: 1,+ widthPt: pageCase.displayed.width,+ },+ ]);+ });++ 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 placed = await findText(pdfBytes, VALUE);++ assert.ok(placed, "the value was not found on the page");+ assert.deepEqual(placed.viewportSize, pageCase.displayed);+ assertInside(placed.user, pageCase.fieldBox, "in the page's coordinates");++ // On the shown page y runs down from the top, as it does for the field.+ const { height, width } = pageCase.displayed;++ assertInside(+ { x: placed.viewport[4]!, y: placed.viewport[5]! },+ [+ FIELD_RECT.x * width,+ FIELD_RECT.y * height,+ (FIELD_RECT.x + FIELD_RECT.width) * width,+ (FIELD_RECT.y + FIELD_RECT.height) * height,+ ],+ "on the shown page",+ );++ // Upright as shown: it runs left to right and is not turned.+ assert.ok(placed.viewport[0]! > 0 && placed.viewport[3]! < 0);+ assert.ok(Math.abs(placed.viewport[1]!) < 0.001);+ assert.ok(Math.abs(placed.viewport[2]!) < 0.001);+ });++ test(`a signer's revision puts its annotations over the fields on ${pageCase.name}`, async () => {+ const source = await makeSource(pageCase);+ const revision = await prepareSignerRevision(+ await prepareRevisionZero(source),+ {+ fields: [+ field({ id: "field-1", value: VALUE }),+ field({+ id: "field-2",+ inputMethod: "typed",+ type: "signature",+ value: "Alice Example",+ }),+ ],+ images: new Map(),+ signature: {+ fieldName: "Alice Example (signer 1)",+ signingTime: new Date(now * 1000),+ },+ },+ );+ const document = await PDFDocument.load(revision.bytes);+ const annotations = document+ .getPage(0)+ .node.Annots()!+ .asArray()+ .map((ref) => document.context.lookup(ref, PDFDict));++ // The text field's stamp and the signature's widget.+ assert.equal(annotations.length, 2);++ for (const annotation of annotations) {+ const appearance = annotation+ .lookup(PDFName.of("AP"), PDFDict)+ .lookup(PDFName.of("N"));++ assert.ok(appearance instanceof PDFRawStream);++ const numbers = (array: PDFArray) =>+ array.asArray().map((entry) => Number(entry.toString()));++ assertClose(+ numbers(annotation.lookup(PDFName.of("Rect"), PDFArray)),+ pageCase.fieldBox,+ );+ // The appearance is cut to the same rectangle, so it is shown as+ // drawn, and it is drawn turned the way the page is shown.+ assertClose(+ numbers(appearance.dict.lookup(PDFName.of("BBox"), PDFArray)),+ pageCase.fieldBox,+ );+ assert.equal(+ decodeStream(appearance).includes(" cm"),+ pageCase.matrix !== null,+ );++ if (pageCase.matrix) {+ assert.ok(decodeStream(appearance).includes(`${pageCase.matrix} cm`));+ }+ }+ });+}diff --git a/src/lib/services/pdf-page-geometry.ts b/src/lib/services/pdf-page-geometry.tsnew file mode 100644index 0000000..596ade6--- /dev/null+++ b/src/lib/services/pdf-page-geometry.ts@@ -0,0 +1,184 @@+import {+ concatTransformationMatrix,+ popGraphicsState,+ pushGraphicsState,+ type PDFPage,+} from "pdf-lib";++// Where a page's content is, as a reader shows it.+//+// Fields are placed on the page the browser shows: the part inside the+// CropBox, turned by the page's /Rotate. A scanned landscape page is often a+// portrait page with /Rotate 90, and a page's box need not start at 0,0. So+// a field's place on the shown page is not its place in the page's own+// coordinates (user space), which is where content is drawn.+//+// Everything here is read from the PDF page itself, never from the sizes+// stored with an envelope, so it is right for documents imported before the+// stored sizes were those of the shown page.++type Box = {+ height: number;+ width: number;+ x: number;+ y: number;+};++/** a b c d e f, as the `cm` operator takes them. */+type Matrix = [number, number, number, number, number, number];++export type DisplayedPageGeometry = {+ /** The height of the page as shown, in points. */+ heightPt: number;+ /**+ * Maps a point on the shown page (origin at its bottom left, y up, in+ * points) to user space. Null when the two are the same, which is every+ * page with no rotation and a box that starts at 0,0.+ */+ toUserSpace: Matrix | null;+ /** The width of the page as shown, in points. */+ widthPt: number;+};++/** A box with a positive size, whichever corners the PDF listed. */+function normalizeBox(box: Box): Box {+ return {+ height: Math.abs(box.height),+ width: Math.abs(box.width),+ x: Math.min(box.x, box.x + box.width),+ y: Math.min(box.y, box.y + box.height),+ };+}++/**+ * The part of the page a reader shows: the CropBox where it lies inside the+ * MediaBox, or the MediaBox when there is no such part. pdf.js does the same.+ */+function getVisibleBox(page: PDFPage): Box {+ const mediaBox = normalizeBox(page.getMediaBox());+ const cropBox = normalizeBox(page.getCropBox());+ const left = Math.max(mediaBox.x, cropBox.x);+ const bottom = Math.max(mediaBox.y, cropBox.y);+ const right = Math.min(+ mediaBox.x + mediaBox.width,+ cropBox.x + cropBox.width,+ );+ const top = Math.min(+ mediaBox.y + mediaBox.height,+ cropBox.y + cropBox.height,+ );++ if (right - left <= 0 || top - bottom <= 0) {+ return mediaBox;+ }++ return { height: top - bottom, width: right - left, x: left, y: bottom };+}++/** The page's rotation as 0, 90, 180 or 270. Any other angle counts as 0. */+function getQuarterTurns(page: PDFPage): 0 | 90 | 180 | 270 {+ const angle = page.getRotation().angle;++ if (!Number.isFinite(angle) || angle % 90 !== 0) {+ return 0;+ }++ return (((angle % 360) + 360) % 360) as 0 | 90 | 180 | 270;+}++export function getDisplayedPageGeometry(page: PDFPage): DisplayedPageGeometry {+ const box = getVisibleBox(page);+ const rotation = getQuarterTurns(page);++ switch (rotation) {+ case 90:+ // Shown turned a quarter clockwise: the box's left edge is on top.+ return {+ heightPt: box.width,+ toUserSpace: [0, 1, -1, 0, box.x + box.width, box.y],+ widthPt: box.height,+ };+ case 180:+ return {+ heightPt: box.height,+ toUserSpace: [-1, 0, 0, -1, box.x + box.width, box.y + box.height],+ widthPt: box.width,+ };+ case 270:+ // Shown turned a quarter anticlockwise: the box's right edge is on top.+ return {+ heightPt: box.width,+ toUserSpace: [0, -1, 1, 0, box.x, box.y + box.height],+ widthPt: box.height,+ };+ default:+ return {+ heightPt: box.height,+ toUserSpace:+ box.x === 0 && box.y === 0 ? null : [1, 0, 0, 1, box.x, box.y],+ widthPt: box.width,+ };+ }+}++/**+ * Runs `draw` with the page's coordinates set to those of the shown page, so+ * that what it draws lands where it was placed and reads upright. A page+ * that needs no change gets no extra operators.+ */+export async function drawOnDisplayedPage(+ page: PDFPage,+ geometry: DisplayedPageGeometry,+ draw: () => Promise<void> | void,+): Promise<void> {+ if (!geometry.toUserSpace) {+ await draw();++ return;+ }++ page.pushOperators(+ pushGraphicsState(),+ concatTransformationMatrix(...geometry.toUserSpace),+ );++ try {+ await draw();+ } finally {+ page.pushOperators(popGraphicsState());+ }+}++/**+ * The rectangle in user space that covers a rectangle given on the shown+ * page (bottom-left origin, points). This is what an annotation's /Rect and+ * a form's /BBox take.+ */+export function displayedRectToUserSpaceBox(+ rect: { heightPt: number; widthPt: number; xPt: number; yPt: number },+ geometry: DisplayedPageGeometry,+): { bottom: number; left: number; right: number; top: number } {+ if (!geometry.toUserSpace) {+ return {+ bottom: rect.yPt,+ left: rect.xPt,+ right: rect.xPt + rect.widthPt,+ top: rect.yPt + rect.heightPt,+ };+ }++ const [a, b, c, d, e, f] = geometry.toUserSpace;+ const corners = [+ [rect.xPt, rect.yPt],+ [rect.xPt + rect.widthPt, rect.yPt + rect.heightPt],+ ].map(([x, y]) => [a * x! + c * y! + e, b * x! + d * y! + f]);+ const xs = corners.map((corner) => corner[0]!);+ const ys = corners.map((corner) => corner[1]!);++ return {+ bottom: Math.min(...ys),+ left: Math.min(...xs),+ right: Math.max(...xs),+ top: Math.max(...ys),+ };+}diff --git a/src/lib/services/pdf-revision.ts b/src/lib/services/pdf-revision.tsindex dbaab12..4f4eb6b 100644--- a/src/lib/services/pdf-revision.ts+++ b/src/lib/services/pdf-revision.ts@@ -18,6 +18,10 @@ import type { FieldRecord } from "../schemas/field.ts";import { normalizedRectToPdfRect } from "../utils/pdf-coords.ts";import { shouldStampField, stampFieldValue } from "./pdf-finalize.ts";import { embedTextFaces } from "./pdf-fonts.ts";+import {+ displayedRectToUserSpaceBox,+ getDisplayedPageGeometry,+} from "./pdf-page-geometry.ts";import {appendIncrementalUpdate,prepareSignedUpdate,@@ -359,17 +363,18 @@ export async function prepareSignerRevision(for (const field of fields.filter(shouldStampField)) {const page = document.getPage(field.page - 1);- const size = { heightPt: page.getHeight(), widthPt: page.getWidth() };- const rect = normalizedRectToPdfRect(field, size);+ const geometry = getDisplayedPageGeometry(page);+ // Where the field is in the page's own coordinates, which is what+ // the annotation's rectangle is given in.+ const box = displayedRectToUserSpaceBox(+ normalizedRectToPdfRect(field, geometry),+ geometry,+ );// Drawn on a page of its own, then taken as a form XObject cut to- // the field, so the original page's content is never touched.- const scratch = document.addPage([size.widthPt, size.heightPt]);- const box = {- bottom: rect.yPt,- left: rect.xPt,- right: rect.xPt + rect.widthPt,- top: rect.yPt + rect.heightPt,- };+ // the field, so the original page's content is never touched. It+ // is drawn with the original page's geometry, so the value is in+ // the same place and turned the same way as it would be there.+ const scratch = document.addPage([geometry.widthPt, geometry.heightPt]);await stampFieldValue(field,@@ -378,6 +383,7 @@ export async function prepareSignerRevision(imageCache,document,imageStore,+ geometry,);const embedded = await document.embedPage(scratch, box);