Manipulating PDF Content Streams, Affine Matrices, and SHA-256 ByteRanges in TypeScript
How to prepend underlay watermarks, scale pages with a 0.94 affine matrix for Bates stamping, and hash PDF buffers in browser RAM.
Manipulating PDFs in JavaScript looks deceptively simple when you test on a freshly generated "Hello World" document. You call page.drawText('CONFIDENTIAL', { x: 100, y: 400 }) or stamp a page number at { x: 480, y: 20 }, and it works.
Then you test your code on real-world PDFs—scanned multi-page agreements, documents exported from macOS Preview with non-zero CropBox offsets, or dense contracts where text runs all the way to the bottom margin—and three bugs immediately appear:
- Opaque Watermarks Obscure Black Text: Drawing watermark text at the end of a page's content stream paints the watermark on top of the body text glyphs instead of underneath them.
- Stamps Disappear Outside the
CropBox: If a page hasMediaBox = [0, 0, 612, 792]butCropBox = [36, 48, 576, 744], drawing a footer aty = 20places the text below the visibleCropBoxboundary (y = 48), making the stamp invisible in Adobe Acrobat and Chrome PDF Viewer. - Footer Collisions on Full-Bleed Pages: When existing page text extends down to
y = 12pt, stamping a sequential Bates number (EXH-000001) aty = 16ptoverwrites the original document text.
Here is how we solved all three problems at the ISO 32000-1 PDF content-stream level in pure browser TypeScript.
1. Normalizing CropBox Coordinates and Applying a 0.94 Shrink-to-Fit Matrix
In the PDF coordinate system (1 pt = 1/72 inch), the origin sits at the bottom-left corner of the box.
To guarantee that header and footer Bates stamps never overwrite existing document text—without changing the physical dimensions of the page—we wrap the page’s existing content stream inside a graphics-state save/restore block (q ... Q) and apply a uniform 0.94 affine scaling matrix ([a b c d tx ty cm]):
export interface PageTransformGeometry {
originX: number;
originY: number;
width: number;
height: number;
scaleFactor: number;
translateX: number;
translateY: number;
pdfMatrixOperator: string;
}
export function buildShrinkToFitMatrix(
visibleBox: [number, number, number, number],
scaleFactor = 0.94
): PageTransformGeometry {
const [llx, lly, urx, ury] = visibleBox;
const width = Math.abs(urx - llx);
const height = Math.abs(ury - lly);
// Compute translation (tx, ty) so the scaled page stays centered inside [llx, lly, urx, ury]
const translateX = Number((llx + (width * (1 - scaleFactor)) / 2).toFixed(2));
const translateY = Number((lly + (height * (1 - scaleFactor)) / 2).toFixed(2));
return {
originX: llx,
originY: lly,
width,
height,
scaleFactor,
translateX,
translateY,
pdfMatrixOperator: `q ${scaleFactor} 0 0 ${scaleFactor} ${translateX} ${translateY} cm`,
};
}
On a standard US Letter page (612 × 792 pt), scaleFactor = 0.94 shrinks the interior content by 3% on each side, creating a clean 23.76 pt (8.38 mm) margin collar at the top and bottom of the page where 6-anchor Bates numbers can be stamped with zero risk of overlapping existing text.
2. Underlay vs. Overlay Content Streams ([stream_0, ...stream_n])
Why do most browser watermark tools paint over the text? Because high-level PDF libraries append new drawing operators to the end of the page's /Contents array.
In ISO 32000-1, PDF viewers render the /Contents array using the Painter’s Algorithm: the first stream in the array is painted first (at the bottom), and each subsequent stream is painted on top of it.
To create a true Underlay Watermark:
- We construct a standalone PDF content stream containing the 45-degree rotation matrix (
cos θ sin θ -sin θ cos θ tx ty cm) and an/ExtGStatedictionary setting non-stroking alpha opacity (ca 0.14). - We wrap the page’s original content streams in
q ... Q(so their coordinate state doesn't leak) and prepend our watermark stream to index0of the/Contentsarray:
export function buildRotatedWatermarkOperators(
textEscaped: string,
centerX: number,
centerY: number,
angleDegrees: number,
fontSize: number
): string {
const rad = (angleDegrees * Math.PI) / 180;
const cos = Number(Math.cos(rad).toFixed(4));
const sin = Number(Math.sin(rad).toFixed(4));
const negSin = Number((-Math.sin(rad)).toFixed(4));
return [
'q',
'/GS_Watermark gs',
'BT',
`/F1 ${fontSize} Tf`,
`${cos} ${sin} ${negSin} ${cos} ${centerX.toFixed(2)} ${centerY.toFixed(2)} Tm`,
`(${textEscaped}) Tj`,
'ET',
'Q',
].join('\n');
}
When rendered at index 0, the watermark sits cleanly behind vector text runs while remaining visible across page margins and whitespace. (For full-page scanned JPEG PDFs where an opaque image covers the background, we switch to index n Overlay Mode).
3. Computing WebCrypto SHA-256 Digests & /ByteRange Audit Metadata
When placing a visual signature (such as quadratic Bezier ink strokes drawn on an HTML5 <canvas> or a vector corporate seal), we also want a verifiable cryptographic fingerprint of the document before and after signing.
Using the browser’s built-in crypto.subtle.digest('SHA-256', buffer), we can hash a 50 MB PDF ArrayBuffer in a few milliseconds without external crypto libraries:
export async function computePdfSha256Hex(buffer: ArrayBuffer): Promise<string> {
const hashBuffer = await crypto.subtle.digest('SHA-256', buffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
}
Recording both the preSignSha256 and postSignSha256 digests alongside an ISO 32000-1 /Sig /ByteRange dictionary and an appended Audit Certificate Page gives the recipient a tamper-evident record of the exact file bytes.
I wrapped this coordinate engine, underlay/overlay watermarker, and multi-PDF Bates stamper into a browser utility at KivaroTools PDF Digital Signer & Bates Stamper (part of my client-side toolkit on kivarotools.com) if you want to test it on your own PDFs.
About the author
- Founder & Lead Software Architect @ KivaroTools | BS Computer Science | Full-Stack & Systems Engineer (TypeScript, Next.js, Python, Java, C++, WebAssembly) | Privacy-First Web & Financial Engines
Comments
Join the discussionNo comments yet. Be the first to comment.
KivaroTools: Browser Engineering & Client-Side Architecture
A technical series exploring the engineering behind KivaroTools, including browser-based file processing, JavaScript and TypeScript architecture, memory management, application security, data parsing, performance optimization, and financial computation. Each article shares practical implementation insights, engineering decisions, testing approaches, and lessons learned while building reliable web utilities.

