/** * Watermarked copy of a PDF for Download and Print (Pro). * * The watermark is drawn exactly as in the viewer (paintWatermark) onto a * transparent image per page size, then laid over every page with pdf-lib. * Drawing it as an image keeps any script in names/emails and the same look. * Loaded on demand, only when someone downloads or prints. */ import { PDFDocument, degrees } from 'pdf-lib'; import { paintWatermark } from '../flipper/reader/watermark'; /** Image pixels per PDF point; 2 keeps the text crisp when printed. */ const SCALE = 2; function watermarkPng(width: number, height: number): Promise { const canvas = document.createElement('canvas'); canvas.width = Math.max(1, Math.round(width * SCALE)); canvas.height = Math.max(1, Math.round(height * SCALE)); const ctx = canvas.getContext('2d'); if (!ctx) throw new Error('Canvas unavailable'); paintWatermark(ctx, canvas.width, canvas.height); return new Promise((resolve, reject) => { canvas.toBlob((blob) => { if (!blob) return reject(new Error('Could not draw the watermark')); blob.arrayBuffer().then((buf) => resolve(new Uint8Array(buf)), reject); }, 'image/png'); }); } export async function stampPdf(bytes: ArrayBuffer): Promise { const doc = await PDFDocument.load(bytes, { ignoreEncryption: true, updateMetadata: false }); if (doc.isEncrypted) throw new Error('Encrypted PDFs cannot be watermarked'); const images = new Map>>(); for (const page of doc.getPages()) { const box = page.getCropBox(); const rotation = ((page.getRotation().angle % 360) + 360) % 360; const sideways = rotation === 90 || rotation === 270; // Size of the page as it is displayed (after /Rotate). const vw = sideways ? box.height : box.width; const vh = sideways ? box.width : box.height; const key = `${Math.round(vw)}x${Math.round(vh)}`; let image = images.get(key); if (!image) { image = await doc.embedPng(await watermarkPng(vw, vh)); images.set(key, image); } // Draw counter-rotated in user space so it reads upright once the // viewer applies the page's /Rotate. const at = { 0: { x: box.x, y: box.y }, 90: { x: box.x + box.width, y: box.y }, 180: { x: box.x + box.width, y: box.y + box.height }, 270: { x: box.x, y: box.y + box.height }, }[rotation as 0 | 90 | 180 | 270] ?? { x: box.x, y: box.y }; page.drawImage(image, { x: at.x, y: at.y, width: vw, height: vh, rotate: degrees(rotation) }); } const out = await doc.save({ useObjectStreams: true }); return new Blob([out], { type: 'application/pdf' }); }