Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

fix: watermark download parity images flatten 21be

Marc Seitzbb93baabac5b
diff --git a/lib/utils/watermark-pdf.ts b/lib/utils/watermark-pdf.ts
new file mode 100644
index 00000000..8edb233e
--- /dev/null
+++ b/lib/utils/watermark-pdf.ts
@@ -0,0 +1,478 @@
+import {
+ PDF,
+ type PDFPage,
+ type RGB,
+ Standard14Font,
+ StandardFonts,
+ degrees,
+ rgb,
+} from "@libpdf/core";
+
+import { safeTemplateReplace } from "@/lib/utils";
+
+export interface WatermarkConfig {
+ text: string;
+ isTiled: boolean;
+ position:
+ | "top-left"
+ | "top-center"
+ | "top-right"
+ | "middle-left"
+ | "middle-center"
+ | "middle-right"
+ | "bottom-left"
+ | "bottom-center"
+ | "bottom-right";
+ rotation: 0 | 30 | 45 | 90 | 180;
+ color: string;
+ fontSize: number;
+ opacity: number; // 0 to 0.8
+}
+
+export interface ViewerData {
+ email?: string | null;
+ date?: string;
+ ipAddress?: string;
+ link?: string | null;
+ time?: string;
+}
+
+// Standard Helvetica is one of the built-in PDF fonts, so it needs no
+// embedding. A measurement instance lets us size/position text accurately.
+const WATERMARK_FONT = StandardFonts.Helvetica;
+const measureFont = Standard14Font.of(StandardFonts.Helvetica);
+
+// Helvetica ascent/descent ratios relative to the full text height returned by
+// `heightAtSize` (ascent ≈ 718/1000, descent ≈ 207/1000 → 0.776 / 0.224).
+const ASCENT_RATIO = 0.776;
+const DESCENT_RATIO = 0.224;
+
+const toRadians = (deg: number): number => (deg * Math.PI) / 180;
+
+/** Convert a `#RGB`/`#RRGGBB` hex string to a LibPDF RGB color. */
+function hexToLibColor(hex: string): RGB {
+ let value = hex.replace(/^#/, "");
+ if (value.length === 3) {
+ value = value
+ .split("")
+ .map((c) => c + c)
+ .join("");
+ }
+ const int = parseInt(value, 16);
+ if (Number.isNaN(int)) return rgb(0, 0, 0);
+ return rgb(
+ ((int >> 16) & 255) / 255,
+ ((int >> 8) & 255) / 255,
+ (int & 255) / 255,
+ );
+}
+
+/**
+ * Rotate a point around a pivot by `angleRad` (counter-clockwise, matching the
+ * PDF coordinate system where the y-axis points up).
+ */
+function rotatePoint(
+ px: number,
+ py: number,
+ pivotX: number,
+ pivotY: number,
+ angleRad: number,
+): { x: number; y: number } {
+ const dx = px - pivotX;
+ const dy = py - pivotY;
+ const cos = Math.cos(angleRad);
+ const sin = Math.sin(angleRad);
+ return {
+ x: pivotX + dx * cos - dy * sin,
+ y: pivotY + dx * sin + dy * cos,
+ };
+}
+
+/**
+ * Replace Unicode characters that can't be encoded in the WinAnsi character
+ * set used by the standard Helvetica font.
+ */
+export function sanitizeWatermarkText(text: string): string {
+ const replacements: { [key: string]: string } = {
+ // Turkish characters
+ İ: "I",
+ ı: "i",
+ ğ: "g",
+ Ğ: "G",
+ ü: "u",
+ Ü: "U",
+ ş: "s",
+ Ş: "S",
+ ç: "c",
+ Ç: "C",
+ ö: "o",
+ Ö: "O",
+ // German characters
+ ß: "ss",
+ ä: "a",
+ Ä: "A",
+ ë: "e",
+ Ë: "E",
+ // French characters
+ à: "a",
+ À: "A",
+ é: "e",
+ É: "E",
+ è: "e",
+ È: "E",
+ ê: "e",
+ Ê: "E",
+ ù: "u",
+ Ù: "U",
+ ô: "o",
+ Ô: "O",
+ // Spanish characters
+ ñ: "n",
+ Ñ: "N",
+ á: "a",
+ Á: "A",
+ í: "i",
+ Í: "I",
+ ó: "o",
+ Ó: "O",
+ ú: "u",
+ Ú: "U",
+ // Common symbols
+ "€": "EUR",
+ "£": "GBP",
+ "¥": "JPY",
+ "©": "(c)",
+ "®": "(R)",
+ "™": "TM",
+ "…": "...",
+ "–": "-",
+ "—": "-",
+ "\u201C": '"',
+ "\u201D": '"',
+ "\u2018": "'",
+ "\u2019": "'",
+ "•": "*",
+ };
+
+ let sanitized = text;
+ for (const [original, replacement] of Object.entries(replacements)) {
+ sanitized = sanitized.replace(new RegExp(original, "g"), replacement);
+ }
+ // Replace any remaining non-WinAnsi characters (outside Latin-1 range)
+ sanitized = sanitized.replace(/[^\u0000-\u00FF]/g, "?");
+ return sanitized;
+}
+
+/**
+ * Mirror the responsive font sizing used by the on-screen SVG watermark
+ * (`components/view/watermark-svg.tsx`) so the downloaded document matches the
+ * preview the viewer saw.
+ */
+function calculateFontSize(
+ config: WatermarkConfig,
+ width: number,
+ height: number,
+): number {
+ const baseFontSize = Math.min(width, height) * (config.fontSize / 1000);
+ return Math.max(8, Math.min(baseFontSize, config.fontSize));
+}
+
+/**
+ * Given a target centre point and the text metrics, return the baseline-left
+ * coordinate LibPDF expects so that the (rotated) text is centred on the
+ * point. LibPDF rotates the glyphs counter-clockwise around the supplied
+ * baseline-left point, so we shift back along the text direction by half the
+ * width and "down" (in the glyph frame) to the baseline.
+ */
+function baselineForCenteredText(
+ centerX: number,
+ centerY: number,
+ textWidth: number,
+ ascent: number,
+ descent: number,
+ angleRad: number,
+): { x: number; y: number } {
+ const cos = Math.cos(angleRad);
+ const sin = Math.sin(angleRad);
+ const dirX = cos;
+ const dirY = sin;
+ const perpX = -sin;
+ const perpY = cos;
+ const vShift = (ascent - descent) / 2;
+ return {
+ x: centerX - (textWidth / 2) * dirX - vShift * perpX,
+ y: centerY - (textWidth / 2) * dirY - vShift * perpY,
+ };
+}
+
+/**
+ * Draw the watermark onto a single page by writing it directly into the page
+ * content stream (LibPDF `drawText`). Because the watermark is part of the
+ * page content — not a separate annotation or optional-content layer — there
+ * is no removable layer to toggle or delete.
+ *
+ * The placement logic is a direct port of the on-screen SVG watermark
+ * (`components/view/watermark-svg.tsx`) so the download matches the preview:
+ * - Single watermarks are anchored exactly like the SVG (`textAnchor` +
+ * `dominantBaseline`) and rotated around that anchor.
+ * - Tiled watermarks reuse the SVG pattern dimensions (`length * fontSize *
+ * 0.6` wide, `fontSize * 10` tall) and the same rotation pivot (page
+ * top-left) so tiling density and angle line up with the preview.
+ */
+export function insertWatermark(
+ page: PDFPage,
+ config: WatermarkConfig,
+ viewerData: ViewerData,
+): void {
+ const width = page.width;
+ const height = page.height;
+
+ const rawWatermarkText = safeTemplateReplace(
+ config.text,
+ viewerData as Record<string, any>,
+ );
+ const watermarkText = sanitizeWatermarkText(rawWatermarkText);
+ if (!watermarkText) return;
+
+ const fontSize = calculateFontSize(config, width, height);
+ const color = hexToLibColor(config.color);
+ const angleRad = toRadians(config.rotation);
+
+ let textWidth: number;
+ let fullHeight: number;
+ try {
+ textWidth = measureFont.widthOfTextAtSize(watermarkText, fontSize);
+ fullHeight = measureFont.heightAtSize(fontSize);
+ } catch {
+ textWidth = watermarkText.length * fontSize * 0.6;
+ fullHeight = fontSize;
+ }
+ const ascent = fullHeight * ASCENT_RATIO;
+ const descent = fullHeight * DESCENT_RATIO;
+
+ const draw = (x: number, y: number) => {
+ page.drawText(watermarkText, {
+ x,
+ y,
+ size: fontSize,
+ font: WATERMARK_FONT,
+ color,
+ opacity: config.opacity,
+ rotate: degrees(config.rotation),
+ });
+ };
+
+ if (config.isTiled) {
+ // Match the SVG <pattern> dimensions so tiling density is identical to the
+ // on-screen preview. The SVG estimates the text width as
+ // `length * fontSize * 0.6`; reuse that estimate for spacing.
+ const estimatedTextWidth = Math.max(
+ watermarkText.length * fontSize * 0.6,
+ fontSize,
+ );
+ const spacingX = estimatedTextWidth;
+ const spacingY = fontSize * 10;
+
+ // The SVG pattern is rotated around the user-space origin, i.e. the
+ // top-left of the page. In PDF coordinates that is (0, height).
+ const pivotX = 0;
+ const pivotY = height;
+
+ const diagonal = Math.sqrt(width * width + height * height);
+ const cols = Math.ceil(diagonal / spacingX) + 2;
+ const rows = Math.ceil(diagonal / spacingY) + 2;
+
+ // Guard against pathological tile counts (very small font + long text).
+ const MAX_TILES = 20000;
+ let drawn = 0;
+ const margin = Math.max(spacingX, spacingY);
+
+ for (let i = -cols; i <= cols && drawn < MAX_TILES; i++) {
+ for (let j = -rows; j <= rows && drawn < MAX_TILES; j++) {
+ // Tile centre in the unrotated (SVG-like) space. The SVG draws the
+ // text at (patternWidth/2, patternHeight/4) within each tile.
+ const centerSvgX = i * spacingX + spacingX / 2;
+ const centerSvgY = j * spacingY + spacingY / 4;
+ // Convert from SVG (y-down, origin top-left) to PDF (y-up).
+ const centerX = centerSvgX;
+ const centerY = height - centerSvgY;
+
+ const rotated = rotatePoint(centerX, centerY, pivotX, pivotY, angleRad);
+
+ if (
+ rotated.x < -margin ||
+ rotated.x > width + margin ||
+ rotated.y < -margin ||
+ rotated.y > height + margin
+ ) {
+ continue;
+ }
+
+ const baseline = baselineForCenteredText(
+ rotated.x,
+ rotated.y,
+ textWidth,
+ ascent,
+ descent,
+ angleRad,
+ );
+ draw(baseline.x, baseline.y);
+ drawn++;
+ }
+ }
+ return;
+ }
+
+ // --- Single (non-tiled) watermark -----------------------------------------
+ // Reproduce the SVG anchor point + alignment, then rotate around it.
+ const { position } = config;
+
+ // Anchor point in SVG coordinates (y-down, origin top-left).
+ let anchorSvgX: number;
+ if (position.includes("left")) {
+ anchorSvgX = fontSize / 2;
+ } else if (position.includes("right")) {
+ anchorSvgX = width - fontSize / 2;
+ } else {
+ anchorSvgX = width / 2;
+ }
+
+ let anchorSvgY: number;
+ if (position.includes("top")) {
+ anchorSvgY = fontSize;
+ } else if (position.includes("bottom")) {
+ anchorSvgY = height - fontSize;
+ } else {
+ anchorSvgY = height / 2;
+ }
+
+ const pivotX = anchorSvgX;
+ const pivotY = height - anchorSvgY; // to PDF (y-up)
+
+ // Baseline-left of the text in the unrotated frame, honouring the SVG
+ // `textAnchor` (start/middle/end) and `dominantBaseline`
+ // (hanging/middle/auto).
+ let baselineX: number;
+ if (position.includes("left")) {
+ baselineX = pivotX; // textAnchor="start"
+ } else if (position.includes("right")) {
+ baselineX = pivotX - textWidth; // textAnchor="end"
+ } else {
+ baselineX = pivotX - textWidth / 2; // textAnchor="middle"
+ }
+
+ let baselineY: number;
+ if (position.includes("top")) {
+ // dominantBaseline="hanging": glyph top sits at the anchor.
+ baselineY = pivotY - ascent;
+ } else if (position.includes("bottom")) {
+ // dominantBaseline="auto": baseline sits at the anchor.
+ baselineY = pivotY;
+ } else {
+ // dominantBaseline="middle": vertical centre sits at the anchor.
+ baselineY = pivotY - (ascent - descent) / 2;
+ }
+
+ const rotated = rotatePoint(baselineX, baselineY, pivotX, pivotY, angleRad);
+ draw(rotated.x, rotated.y);
+}
+
+export interface BuildWatermarkedPdfOptions {
+ /** Raw bytes of the source file (PDF or image). */
+ fileBytes: Uint8Array;
+ /** Whether the source is a PDF or an image. */
+ fileType: "pdf" | "image";
+ watermarkConfig: WatermarkConfig;
+ viewerData: ViewerData;
+ /** Number of pages (PDF only). Images are always a single page. */
+ numPages: number;
+ /**
+ * When true, any form / annotation / optional-content layers in the source
+ * document are flattened so they can't be toggled or removed (the watermark
+ * itself is already merged into the page content stream).
+ */
+ flatten?: boolean;
+ /** Content type of the image (image inputs only, unused — kept for API compatibility). */
+ imageContentType?: string;
+ /** Optional progress/diagnostics hook. */
+ onProgress?: (message: string) => void;
+}
+
+/**
+ * Turn a PDF or image into a watermarked PDF using LibPDF.
+ *
+ * The watermark is drawn directly into each page's content stream (so it
+ * cannot be removed as an annotation/layer) and, when `flatten` is set, any
+ * existing form/annotation/optional-content layers are flattened too. This is
+ * fully serverless-friendly — there is no page rasterisation.
+ */
+export async function buildWatermarkedPdf({
+ fileBytes,
+ fileType,
+ watermarkConfig,
+ viewerData,
+ flatten = false,
+ onProgress,
+}: BuildWatermarkedPdfOptions): Promise<Uint8Array> {
+ let pdf: PDF;
+ let pages: PDFPage[];
+
+ if (fileType === "image") {
+ pdf = PDF.create();
+ let image;
+ try {
+ image = pdf.embedImage(fileBytes);
+ } catch (error) {
+ throw new Error(
+ `Unsupported image format for watermarking: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+ }
+ // Scale large images down so the watermark font-size cap (1000pt) doesn't
+ // shrink the watermark; the full-resolution image still embeds losslessly.
+ const MAX_IMAGE_PAGE_DIMENSION = 1000;
+ const longestSide = Math.max(image.widthInPoints, image.heightInPoints);
+ const scale =
+ longestSide > MAX_IMAGE_PAGE_DIMENSION
+ ? MAX_IMAGE_PAGE_DIMENSION / longestSide
+ : 1;
+ const widthPt = image.widthInPoints * scale;
+ const heightPt = image.heightInPoints * scale;
+ const page = pdf.addPage({ width: widthPt, height: heightPt });
+ page.drawImage(image, { x: 0, y: 0, width: widthPt, height: heightPt });
+ pages = [page];
+ } else {
+ pdf = await PDF.load(fileBytes);
+ pages = pdf.getPages();
+ }
+
+ for (let i = 0; i < pages.length; i++) {
+ insertWatermark(pages[i], watermarkConfig, viewerData);
+ if ((i + 1) % 25 === 0) {
+ onProgress?.(`Watermarked ${i + 1}/${pages.length} pages`);
+ }
+ }
+
+ if (flatten) {
+ // Flatten forms, annotations, and optional-content layers so nothing can
+ // be toggled/removed. Best-effort: never fail the download over this.
+ try {
+ pdf.flattenAll();
+ onProgress?.("Flattened form/annotation/layer content");
+ } catch (error) {
+ onProgress?.(
+ `flattenAll failed, falling back to form flatten: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+ try {
+ pdf.getForm()?.flatten();
+ } catch {
+ // No form / unsupported – ignore.
+ }
+ }
+ }
+
+ return await pdf.save();
+}
diff --git a/next.config.mjs b/next.config.mjs
index a94f0bd6..d1afefe5 100644
--- a/next.config.mjs
+++ b/next.config.mjs
@@ -2,7 +2,7 @@
const nextConfig = {
reactStrictMode: true,
pageExtensions: ["js", "jsx", "ts", "tsx", "mdx"],
- transpilePackages: ["@boxyhq/saml-jackson"],
+ transpilePackages: ["@boxyhq/saml-jackson", "@libpdf/core"],
images: {
minimumCacheTTL: 2592000, // 30 days
remotePatterns: prepareRemotePatterns(),
diff --git a/package-lock.json b/package-lock.json
index 4abccb92..8e59bbf1 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -28,7 +28,7 @@
"@github/webauthn-json": "^2.1.1",
"@hookform/resolvers": "^5.2.2",
"@jitsu/js": "^1.10.4",
- "@libpdf/core": "^0.3.6",
+ "@libpdf/core": "^0.4.0",
"@modelcontextprotocol/sdk": "^1.29.0",
"@next-auth/prisma-adapter": "^1.0.7",
"@next/third-parties": "^16.2.6",
@@ -4770,16 +4770,16 @@
}
},
"node_modules/@libpdf/core": {
- "version": "0.3.6",
- "resolved": "https://registry.npmjs.org/@libpdf/core/-/core-0.3.6.tgz",
- "integrity": "sha512-VzRUXaDq+M9qrroKiipCgePK2mwKM3M6DY7B0yfXnxD4aYnUxD/nUtkcsHCBUUnJpkX9rWikdEhYa5vU8ZlReg==",
+ "version": "0.4.0",
+ "resolved": "https://registry.npmjs.org/@libpdf/core/-/core-0.4.0.tgz",
+ "integrity": "sha512-G9nZRjf9DGDJaS/C23YWogk8akPM7O/6HfMslxVsKTKRbbbb+0szpQIetcGGUGRu7KtmBDmGDWCgz//DXSmq8A==",
"license": "MIT",
"dependencies": {
"@noble/ciphers": "^2.2.0",
"@noble/hashes": "^2.2.0",
"@scure/base": "^2.2.0",
"asn1js": "^3.0.10",
- "lru-cache": "^11.4.0",
+ "lru-cache": "^11.5.1",
"pako": "^2.1.0",
"pkijs": "^3.4.0"
},
@@ -17516,9 +17516,9 @@
}
},
"node_modules/lru-cache": {
- "version": "11.5.0",
- "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.0.tgz",
- "integrity": "sha512-5YgH9UJd7wVb9hIouI2adWpgqrrICkt070Dnj8EUY1+B4B2P9eRLPAkAAo6NICA7CEhOIeBHl46u9zSNpNu7zA==",
+ "version": "11.5.1",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.1.tgz",
+ "integrity": "sha512-RPimw/7aMdv2oqRrxKwvZXcPfwBrn/JZ2xYcY9Hus/6LaS3VOAKVWKWgNLCFSiOm1ESXinjsDlidVU7JlnCN2A==",
"license": "BlueOak-1.0.0",
"engines": {
"node": "20 || >=22"
diff --git a/package.json b/package.json
index f8b64024..26b142c2 100644
--- a/package.json
+++ b/package.json
@@ -40,7 +40,7 @@
"@github/webauthn-json": "^2.1.1",
"@hookform/resolvers": "^5.2.2",
"@jitsu/js": "^1.10.4",
- "@libpdf/core": "^0.3.6",
+ "@libpdf/core": "^0.4.0",
"@modelcontextprotocol/sdk": "^1.29.0",
"@next-auth/prisma-adapter": "^1.0.7",
"@next/third-parties": "^16.2.6",
diff --git a/pages/api/links/download/dataroom-document.ts b/pages/api/links/download/dataroom-document.ts
index 93b9a795..ec9f7d08 100644
--- a/pages/api/links/download/dataroom-document.ts
+++ b/pages/api/links/download/dataroom-document.ts
@@ -269,9 +269,12 @@ export default async function handle(
: undefined,
});
- // For PDF files with watermark, always buffer and process
+ const versionType = downloadDocuments[0].document!.versions[0].type;
+
+ // For PDFs and images with watermark, buffer and process. Images are
+ // converted to a watermarked PDF.
if (
- downloadDocuments[0].document!.versions[0].type === "pdf" &&
+ (versionType === "pdf" || versionType === "image") &&
view.link.enableWatermark &&
view.link.watermarkConfig
) {
@@ -285,7 +288,14 @@ export default async function handle(
},
body: JSON.stringify({
url: downloadUrl,
- numPages: downloadDocuments[0].document!.versions[0].numPages,
+ fileType: versionType === "image" ? "image" : "pdf",
+ numPages:
+ versionType === "image"
+ ? 1
+ : downloadDocuments[0].document!.versions[0].numPages,
+ // Flatten form/annotation/layers; the watermark is drawn into
+ // the page content stream so it can't be removed as a layer.
+ flatten: true,
watermarkConfig: view.link.watermarkConfig,
originalFileName: downloadDocuments[0].document!.name,
viewerData: {
diff --git a/pages/api/links/download/index.ts b/pages/api/links/download/index.ts
index 205f85fa..98d78e8b 100644
--- a/pages/api/links/download/index.ts
+++ b/pages/api/links/download/index.ts
@@ -205,8 +205,10 @@ export default async function handle(
: undefined,
});
+ const versionType = view.document!.versions[0].type;
+
if (
- view.document!.versions[0].type === "pdf" &&
+ (versionType === "pdf" || versionType === "image") &&
view.link.enableWatermark &&
view.link.watermarkConfig
) {
@@ -220,7 +222,15 @@ export default async function handle(
},
body: JSON.stringify({
url: downloadUrl,
- numPages: view.document!.versions[0].numPages,
+ // Images are a single page; convert them to a watermarked PDF.
+ fileType: versionType === "image" ? "image" : "pdf",
+ numPages:
+ versionType === "image"
+ ? 1
+ : view.document!.versions[0].numPages,
+ // Flatten form/annotation/layers; the watermark is drawn into
+ // the page content stream so it can't be removed as a layer.
+ flatten: true,
watermarkConfig: view.link.watermarkConfig,
originalFileName: view.document!.name,
viewerData: {
diff --git a/pages/api/mupdf/annotate-document.ts b/pages/api/mupdf/annotate-document.ts
index 88f423bf..da807a50 100644
--- a/pages/api/mupdf/annotate-document.ts
+++ b/pages/api/mupdf/annotate-document.ts
@@ -1,14 +1,11 @@
import { NextApiRequest, NextApiResponse } from "next";
-import fontkit from "@pdf-lib/fontkit";
-import { PDFDocument, PDFFont, StandardFonts, degrees, rgb } from "pdf-lib";
-
+import { getFileNameWithPdfExtension, log } from "@/lib/utils";
import {
- getFileNameWithPdfExtension,
- hexToRgb,
- log,
- safeTemplateReplace,
-} from "@/lib/utils";
+ type ViewerData,
+ type WatermarkConfig,
+ buildWatermarkedPdf,
+} from "@/lib/utils/watermark-pdf";
// This function can run for a maximum of 300 seconds
export const config = {
@@ -59,230 +56,6 @@ function validateUrl(urlString: string): URL {
return parsedUrl;
}
-interface WatermarkConfig {
- text: string;
- isTiled: boolean;
- position:
- | "top-left"
- | "top-center"
- | "top-right"
- | "middle-left"
- | "middle-center"
- | "middle-right"
- | "bottom-left"
- | "bottom-center"
- | "bottom-right";
- rotation: 0 | 30 | 45 | 90 | 180;
- color: string;
- fontSize: number;
- opacity: number; // 0 to 0.8
-}
-
-interface ViewerData {
- email: string;
- date: string;
- ipAddress: string;
- link: string;
- time: string;
-}
-
-function getPositionCoordinates(
- position: WatermarkConfig["position"],
- width: number,
- height: number,
- textWidth: number,
- textHeight: number,
-): number[] {
- const positions = {
- "top-left": [10, height - textHeight],
- "top-center": [(width - textWidth) / 2, height - textHeight],
- "top-right": [width - textWidth - 10, height - textHeight],
- "middle-left": [10, (height - textHeight) / 2],
- "middle-center": [(width - textWidth) / 2, (height - textHeight) / 2],
- "middle-right": [width - textWidth - 10, (height - textHeight) / 2],
- "bottom-left": [10, 20],
- "bottom-center": [(width - textWidth) / 2, 20],
- "bottom-right": [width - textWidth - 10, 20],
- };
- return positions[position];
-}
-
-async function insertWatermark(
- pdfDoc: PDFDocument,
- config: WatermarkConfig,
- viewerData: ViewerData,
- pageIndex: number,
- font: PDFFont, // Pre-embedded font passed in
-): Promise<void> {
- const pages = pdfDoc.getPages();
- const page = pages[pageIndex];
- const { width, height } = page.getSize();
-
- // Safely replace template variables with whitelisted values only
- const rawWatermarkText = safeTemplateReplace(config.text, viewerData);
-
- // Handle Unicode characters that can't be encoded in WinAnsi
- const sanitizeText = (text: string): string => {
- // Common character replacements for WinAnsi compatibility
- const replacements: { [key: string]: string } = {
- // Turkish characters
- İ: "I",
- ı: "i",
- ğ: "g",
- Ğ: "G",
- ü: "u",
- Ü: "U",
- ş: "s",
- Ş: "S",
- ç: "c",
- Ç: "C",
- ö: "o",
- Ö: "O",
- // German characters
- ß: "ss",
- ä: "a",
- Ä: "A",
- ë: "e",
- Ë: "E",
- // French characters
- à: "a",
- À: "A",
- é: "e",
- É: "E",
- è: "e",
- È: "E",
- ê: "e",
- Ê: "E",
- ù: "u",
- Ù: "U",
- ô: "o",
- Ô: "O",
- // Spanish characters
- ñ: "n",
- Ñ: "N",
- á: "a",
- Á: "A",
- í: "i",
- Í: "I",
- ó: "o",
- Ó: "O",
- ú: "u",
- Ú: "U",
- // Common symbols
- "€": "EUR",
- "£": "GBP",
- "¥": "JPY",
- "©": "(c)",
- "®": "(R)",
- "™": "TM",
- "…": "...",
- "–": "-",
- "—": "-",
- "\u201C": '"',
- "\u201D": '"',
- "\u2018": "'",
- "\u2019": "'",
- "•": "*",
- };
-
- let sanitized = text;
-
- // Apply character replacements
- for (const [original, replacement] of Object.entries(replacements)) {
- sanitized = sanitized.replace(new RegExp(original, "g"), replacement);
- }
-
- // Replace any remaining non-WinAnsi characters (outside Latin-1 range)
- sanitized = sanitized.replace(/[^\u0000-\u00FF]/g, "?");
-
- return sanitized;
- };
-
- const watermarkText = sanitizeText(rawWatermarkText);
-
- // Calculate a responsive font size
- const calculateFontSize = () => {
- const baseFontSize = Math.min(width, height) * (config.fontSize / 1000);
- return Math.max(8, Math.min(baseFontSize, config.fontSize));
- };
- const fontSize = calculateFontSize();
-
- // Calculate text dimensions with error handling
- let textWidth: number;
- let textHeight: number;
-
- try {
- textWidth = font.widthOfTextAtSize(watermarkText, fontSize);
- textHeight = font.heightAtSize(fontSize);
- } catch (error) {
- // If there are still encoding issues, provide fallback values
- console.warn("Font encoding error:", error);
- textWidth = watermarkText.length * fontSize * 0.6; // Approximate width
- textHeight = fontSize * 1.2; // Approximate height
- }
-
- if (config.isTiled) {
- const patternWidth = textWidth / 1.1;
- const patternHeight = textHeight * 15;
-
- // Calculate the offset to center the pattern
- const offsetX = -patternWidth / 4;
- const offsetY = -patternHeight / 4;
-
- const maxTilesPerRow = Math.ceil(width / patternWidth) + 1;
- const maxTilesPerColumn = Math.ceil(height / patternHeight) + 1;
-
- for (let i = 0; i < maxTilesPerRow; i++) {
- for (let j = 0; j < maxTilesPerColumn; j++) {
- const x = i * patternWidth + offsetX;
- const y = j * patternHeight + offsetY;
-
- try {
- page.drawText(watermarkText, {
- x,
- y,
- size: fontSize,
- font,
- color: hexToRgb(config.color) ?? rgb(0, 0, 0),
- opacity: config.opacity,
- rotate: degrees(config.rotation),
- });
- } catch (error) {
- console.error("Error drawing tiled watermark text:", error);
- throw new Error(
- `Failed to apply watermark to page ${pageIndex + 1}: ${error}`,
- );
- }
- }
- }
- } else {
- const [x, y] = getPositionCoordinates(
- config.position,
- width,
- height,
- textWidth,
- textHeight,
- );
-
- try {
- page.drawText(watermarkText, {
- x,
- y,
- size: fontSize,
- font,
- color: hexToRgb(config.color) ?? rgb(0, 0, 0),
- opacity: config.opacity,
- rotate: degrees(config.rotation),
- });
- } catch (error) {
- console.error("Error drawing positioned watermark text:", error);
- throw new Error(
- `Failed to apply watermark to page ${pageIndex + 1}: ${error}`,
- );
- }
- }
-}
-
export default async (req: NextApiRequest, res: NextApiResponse) => {
// check if post method
if (req.method !== "POST") {
@@ -300,14 +73,23 @@ export default async (req: NextApiRequest, res: NextApiResponse) => {
return;
}
- const { url, watermarkConfig, viewerData, numPages, originalFileName } =
- req.body as {
- url: string;
- watermarkConfig: WatermarkConfig;
- viewerData: ViewerData;
- numPages: number;
- originalFileName?: string;
- };
+ const {
+ url,
+ watermarkConfig,
+ viewerData,
+ numPages,
+ originalFileName,
+ fileType = "pdf",
+ flatten = false,
+ } = req.body as {
+ url: string;
+ watermarkConfig: WatermarkConfig;
+ viewerData: ViewerData;
+ numPages: number;
+ originalFileName?: string;
+ fileType?: "pdf" | "image";
+ flatten?: boolean;
+ };
// Validate required fields
if (!url || typeof url !== "string") {
@@ -320,15 +102,28 @@ export default async (req: NextApiRequest, res: NextApiResponse) => {
.json({ error: "Invalid or missing watermark config" });
}
- if (!numPages || typeof numPages !== "number" || numPages <= 0) {
- return res.status(400).json({ error: "Invalid page count" });
+ if (fileType !== "image" && fileType !== "pdf") {
+ return res.status(400).json({ error: "Invalid file type" });
}
- if (numPages > 1000) {
- return res.status(400).json({
- error: "Document too large",
- details: "Maximum 1000 pages supported",
- });
+ // Images are always a single page; PDFs need a valid page count.
+ const effectiveNumPages = fileType === "image" ? 1 : numPages;
+
+ if (fileType === "pdf") {
+ if (
+ !effectiveNumPages ||
+ typeof effectiveNumPages !== "number" ||
+ effectiveNumPages <= 0
+ ) {
+ return res.status(400).json({ error: "Invalid page count" });
+ }
+
+ if (effectiveNumPages > 1000) {
+ return res.status(400).json({
+ error: "Document too large",
+ details: "Maximum 1000 pages supported",
+ });
+ }
}
const startTime = Date.now();
@@ -351,7 +146,7 @@ export default async (req: NextApiRequest, res: NextApiResponse) => {
}
try {
- // Fetch the PDF data with timeout
+ // Fetch the source file (PDF or image) with timeout
let response: Response;
try {
const fetchStart = Date.now();
@@ -362,7 +157,7 @@ export default async (req: NextApiRequest, res: NextApiResponse) => {
response = await fetch(validatedUrl.toString(), {
signal: controller.signal,
headers: {
- Accept: "application/pdf",
+ Accept: fileType === "image" ? "image/*" : "application/pdf",
},
});
@@ -372,96 +167,45 @@ export default async (req: NextApiRequest, res: NextApiResponse) => {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
- console.log(`PDF fetch took ${Date.now() - fetchStart}ms`);
+ console.log(`Source fetch took ${Date.now() - fetchStart}ms`);
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
log({
- message: `Failed to fetch PDF in conversion process with error: \n\n Error: ${errorMsg}\nURL: ${url}`,
+ message: `Failed to fetch source file in watermarking process with error: \n\n Error: ${errorMsg}\nURL: ${url}`,
type: "error",
mention: true,
});
if (errorMsg.includes("aborted")) {
- throw new Error(`Timeout fetching PDF (exceeded 60s)`);
+ throw new Error(`Timeout fetching file (exceeded 60s)`);
}
- throw new Error(`Failed to fetch PDF: ${errorMsg}`);
+ throw new Error(`Failed to fetch file: ${errorMsg}`);
}
+ const contentType =
+ response.headers.get("content-type") ?? undefined;
+
// Convert the response to a buffer
const bufferStart = Date.now();
- const pdfBuffer = await response.arrayBuffer();
- const sizeInMB = pdfBuffer.byteLength / 1024 / 1024;
+ const fileBuffer = await response.arrayBuffer();
+ const sizeInMB = fileBuffer.byteLength / 1024 / 1024;
console.log(
`Buffer conversion took ${Date.now() - bufferStart}ms, size: ${sizeInMB.toFixed(2)}MB`,
);
- // Load the PDF document with optimizations
- const loadStart = Date.now();
- const pdfDoc = await PDFDocument.load(pdfBuffer, {
- updateMetadata: false, // Skip metadata updates for performance
- ignoreEncryption: false, // Respect encryption
- });
- console.log(`PDF load took ${Date.now() - loadStart}ms`);
-
- // Register fontkit and embed font ONCE
- pdfDoc.registerFontkit(fontkit);
- const fontStart = Date.now();
- const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
- console.log(`Font embedding took ${Date.now() - fontStart}ms`);
-
- // Calculate optimal batch size based on document size and page count
- // Larger documents = smaller batches to prevent memory spikes
- const calculateBatchSize = (pages: number, sizeMB: number): number => {
- if (sizeMB > 50 || pages > 200) return 5; // Large docs: 5 pages at a time
- if (sizeMB > 20 || pages > 100) return 10; // Medium docs: 10 pages
- return 20; // Smaller docs: 20 pages at a time
- };
-
- const BATCH_SIZE = calculateBatchSize(numPages, sizeInMB);
- const watermarkStart = Date.now();
-
- console.log(`Processing ${numPages} pages in batches of ${BATCH_SIZE}`);
-
- for (let batchStart = 0; batchStart < numPages; batchStart += BATCH_SIZE) {
- const batchEnd = Math.min(batchStart + BATCH_SIZE, numPages);
- const batchPromises = [];
-
- for (let i = batchStart; i < batchEnd; i++) {
- batchPromises.push(
- insertWatermark(pdfDoc, watermarkConfig, viewerData, i, font).catch(
- (error) => {
- const errMsg =
- error instanceof Error ? error.message : String(error);
- console.error(`Error watermarking page ${i + 1}:`, errMsg);
- throw new Error(`Failed to watermark page ${i + 1}: ${errMsg}`);
- },
- ),
- );
- }
-
- await Promise.all(batchPromises);
- const progress = ((batchEnd / numPages) * 100).toFixed(1);
- console.log(
- `Processed pages ${batchStart + 1}-${batchEnd} of ${numPages} (${progress}%)`,
- );
- }
-
- console.log(`All watermarking took ${Date.now() - watermarkStart}ms`);
-
- // Save the modified PDF with optimizations
- const saveStart = Date.now();
- const pdfBytes = await pdfDoc.save({
- useObjectStreams: false, // Better compatibility, slight size increase
- addDefaultPage: false, // Don't add default page
- objectsPerTick: 50, // Process objects in smaller chunks for better memory management
+ const pdfBytes = await buildWatermarkedPdf({
+ fileBytes: new Uint8Array(fileBuffer),
+ fileType,
+ watermarkConfig,
+ viewerData,
+ numPages: effectiveNumPages,
+ flatten,
+ imageContentType: contentType,
+ onProgress: (message) => console.log(message),
});
- const finalSizeMB = pdfBytes.length / 1024 / 1024;
- console.log(
- `PDF save took ${Date.now() - saveStart}ms, final size: ${finalSizeMB.toFixed(2)}MB`,
- );
console.log(
- `Total processing time: ${Date.now() - startTime}ms for ${numPages} pages`,
+ `Total processing time: ${Date.now() - startTime}ms for ${effectiveNumPages} page(s)${flatten ? " (flattened)" : ""}`,
);
// Set appropriate headers
@@ -497,13 +241,16 @@ export default async (req: NextApiRequest, res: NextApiResponse) => {
) {
statusCode = 502;
errorType = "Failed to fetch document";
- } else if (errorMessage.includes("Failed to watermark page")) {
+ } else if (errorMessage.includes("Unsupported image format")) {
+ statusCode = 415;
+ errorType = "Unsupported image format";
+ } else if (errorMessage.includes("Failed to apply watermark")) {
statusCode = 500;
errorType = "Watermarking error";
}
log({
- message: `${errorType} after ${elapsedTime}ms: ${errorMessage}\n\nDocument: ${originalFileName || "unknown"}\nPages: ${numPages}\nURL: ${url?.substring(0, 100)}...`,
+ message: `${errorType} after ${elapsedTime}ms: ${errorMessage}\n\nDocument: ${originalFileName || "unknown"}\nPages: ${effectiveNumPages}\nURL: ${url?.substring(0, 100)}...`,
type: "error",
mention: elapsedTime > 120000, // Only mention if it took more than 2 minutes
});