Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
fix: improve watermarking for non-supported characters
Marc Seitz96b8f99b31ff
diff --git a/components/view/nav.tsx b/components/view/nav.tsxindex cc075fc8..9c422ca3 100644--- a/components/view/nav.tsx+++ b/components/view/nav.tsx@@ -128,7 +128,10 @@ export default function Nav({return;}- if (hasWatermark) {+ // Check if the response is a PDF file (for watermarked PDFs)+ const contentType = response.headers.get("content-type");+ if (contentType === "application/pdf") {+ // Handle direct PDF download (watermarked PDFs)const pdfBlob = await response.blob();const blobUrl = window.URL.createObjectURL(pdfBlob);@@ -144,6 +147,7 @@ export default function Nav({document.body.removeChild(link);}, 100);} else {+ // Handle JSON response with downloadUrl (non-watermarked files)const { downloadUrl } = await response.json();const link = document.createElement("a");@@ -158,6 +162,7 @@ export default function Nav({}} catch (error) {console.error("Error downloading file:", error);+ toast.error("Error downloading file");}};diff --git a/components/view/viewer/download-only-viewer.tsx b/components/view/viewer/download-only-viewer.tsxindex b2bc90c6..7ed2be47 100644--- a/components/view/viewer/download-only-viewer.tsx+++ b/components/view/viewer/download-only-viewer.tsx@@ -1,11 +1,7 @@import { useRouter } from "next/router";--import { useEffect, useRef } from "react";--import { Download } from "lucide-react";import { toast } from "sonner";@@ -213,11 +209,34 @@ export default function DownloadOnlyViewer({toast.error("Error downloading file");return;}- const { downloadUrl } = await response.json();- window.open(downloadUrl, "_blank");+ // Check if the response is a PDF file (for watermarked PDFs)+ const contentType = response.headers.get("content-type");+ if (contentType === "application/pdf") {+ // Handle direct PDF download (watermarked PDFs)+ const pdfBlob = await response.blob();+ const url = URL.createObjectURL(pdfBlob);++ const a = document.createElement("a");+ a.href = url;+ a.download = `${documentName || "document"}.pdf`;+ a.rel = "noopener noreferrer";+ document.body.appendChild(a);+ a.click();++ // Clean up+ setTimeout(() => {+ URL.revokeObjectURL(url);+ document.body.removeChild(a);+ }, 100);+ } else {+ // Handle JSON response with downloadUrl (non-watermarked files)+ const { downloadUrl } = await response.json();+ window.open(downloadUrl, "_blank");+ }} catch (error) {console.error("Error downloading file:", error);+ toast.error("Error downloading file");}};@@ -253,4 +272,4 @@ export default function DownloadOnlyViewer({/></>);-}\ No newline at end of file+}diff --git a/pages/api/links/download/index.ts b/pages/api/links/download/index.tsindex 787a5ea7..92d781c0 100644--- a/pages/api/links/download/index.ts+++ b/pages/api/links/download/index.ts@@ -139,7 +139,21 @@ export default async function handle();if (!response.ok) {- return res.status(500).json({ error: "Error downloading" });+ // Try to get the specific error details from the watermarking API+ let errorMessage = "Error downloading";+ try {+ const errorData = await response.json();+ if (errorData.error && errorData.details) {+ errorMessage = `${errorData.error}: ${errorData.details}`;+ } else if (errorData.error) {+ errorMessage = errorData.error;+ }+ } catch {+ // If we can't parse the error response, use generic message+ errorMessage = "Error downloading";+ }++ return res.status(500).json({ error: errorMessage });}const pdfBuffer = await response.arrayBuffer();diff --git a/pages/api/mupdf/annotate-document.ts b/pages/api/mupdf/annotate-document.tsindex c8da649f..a1b28cd2 100644--- a/pages/api/mupdf/annotate-document.ts+++ b/pages/api/mupdf/annotate-document.ts@@ -73,7 +73,86 @@ async function insertWatermark(// Compile the Handlebars templateconst template = Handlebars.compile(config.text);- const watermarkText = template(viewerData);+ const rawWatermarkText = template(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 sizeconst calculateFontSize = () => {@@ -82,8 +161,19 @@ async function insertWatermark(};const fontSize = calculateFontSize();- const textWidth = font.widthOfTextAtSize(watermarkText, fontSize);- const textHeight = font.heightAtSize(fontSize);+ // 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;@@ -101,15 +191,22 @@ async function insertWatermark(const x = i * patternWidth + offsetX;const y = j * patternHeight + offsetY;- page.drawText(watermarkText, {- x,- y,- size: fontSize,- font,- color: hexToRgb(config.color) ?? rgb(0, 0, 0),- opacity: config.opacity,- rotate: degrees(config.rotation),- });+ 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 {@@ -121,15 +218,22 @@ async function insertWatermark(textHeight,);- page.drawText(watermarkText, {- x,- y,- size: fontSize,- font,- color: hexToRgb(config.color) ?? rgb(0, 0, 0),- opacity: config.opacity,- rotate: degrees(config.rotation),- });+ 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}`,+ );+ }}}@@ -204,6 +308,12 @@ export default async (req: NextApiRequest, res: NextApiResponse) => {type: "error",mention: true,});- throw error;++ // Return proper error response instead of throwing+ res.status(500).json({+ error: "Failed to apply watermark",+ details: (error as Error).message,+ });+ return;}};