From 84366e749e8c276becf2988aff9ea67ca5e73653 Mon Sep 17 00:00:00 2001 From: Sosthene Date: Tue, 1 Jul 2025 22:33:20 +0200 Subject: [PATCH] Add watermark when loading documents --- package.json | 1 + .../DepositDocumentComponent/index.tsx | 126 ++++++++--- src/front/Services/WatermarkService/index.ts | 211 ++++++++++++++++++ 3 files changed, 301 insertions(+), 37 deletions(-) create mode 100644 src/front/Services/WatermarkService/index.ts diff --git a/package.json b/package.json index 59175b5f..a663ce2a 100644 --- a/package.json +++ b/package.json @@ -32,6 +32,7 @@ "jwt-decode": "^3.1.2", "le-coffre-resources": "file:../lecoffre-ressources", "next": "^14.2.3", + "pdf-lib": "^1.17.1", "prettier": "^2.8.7", "react": "18.2.0", "react-dom": "18.2.0", diff --git a/src/front/Components/Layouts/ClientDashboard/DepositDocumentComponent/index.tsx b/src/front/Components/Layouts/ClientDashboard/DepositDocumentComponent/index.tsx index 3f476e10..c828a65d 100644 --- a/src/front/Components/Layouts/ClientDashboard/DepositDocumentComponent/index.tsx +++ b/src/front/Components/Layouts/ClientDashboard/DepositDocumentComponent/index.tsx @@ -10,6 +10,7 @@ import Confirm from "@Front/Components/DesignSystem/OldModal/Confirm"; import FileService from "src/common/Api/LeCoffreApi/sdk/FileService"; import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService"; import { FileBlob, FileData } from "@Front/Api/Entities/types"; +import WatermarkService from "@Front/Services/WatermarkService"; type IProps = { document: any; @@ -31,50 +32,101 @@ export default function DepositDocumentComponent(props: IProps) { }, [document.files]); const addFile = useCallback( - (file: File) => { - return new Promise( - (resolve: () => void) => { - const reader = new FileReader(); - reader.onload = (event) => { - if (event.target?.result) { - const arrayBuffer = event.target.result as ArrayBuffer; - const uint8Array = new Uint8Array(arrayBuffer); + async (file: File) => { + try { + // Add watermark to the file before processing + const watermarkedFile = await WatermarkService.getInstance().addWatermark(file); + + return new Promise( + (resolve: () => void) => { + const reader = new FileReader(); + reader.onload = (event) => { + if (event.target?.result) { + const arrayBuffer = event.target.result as ArrayBuffer; + const uint8Array = new Uint8Array(arrayBuffer); - const fileBlob: FileBlob = { - type: file.type, - data: uint8Array - }; + const fileBlob: FileBlob = { + type: watermarkedFile.type, + data: uint8Array + }; - const fileData: FileData = { - file_blob: fileBlob, - file_name: file.name - }; - const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0'; + const fileData: FileData = { + file_blob: fileBlob, + file_name: watermarkedFile.name + }; + const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0'; - FileService.createFile(fileData, validatorId).then((processCreated: any) => { - const fileUid: string = processCreated.processData.uid; + FileService.createFile(fileData, validatorId).then((processCreated: any) => { + const fileUid: string = processCreated.processData.uid; - DocumentService.getDocumentByUid(document.uid!).then((process: any) => { - if (process) { - const document: any = process.processData; + DocumentService.getDocumentByUid(document.uid!).then((process: any) => { + if (process) { + const document: any = process.processData; - let files: any[] = document.files; - if (!files) { - files = []; + let files: any[] = document.files; + if (!files) { + files = []; + } + files.push({ uid: fileUid }); + + DocumentService.updateDocument(process, { files: files, document_status: EDocumentStatus.DEPOSITED }).then(() => resolve()); } - files.push({ uid: fileUid }); - - DocumentService.updateDocument(process, { files: files, document_status: EDocumentStatus.DEPOSITED }).then(() => resolve()); - } + }); }); - }); - } - }; - reader.readAsArrayBuffer(file); - }) - .then(onChange) - .then(() => ToasterService.getInstance().success({ title: "Succès !", description: "Fichier uploadé avec succès!" })) - .catch((error) => ToasterService.getInstance().error({ title: "Erreur !", description: error.message })); + } + }; + reader.readAsArrayBuffer(watermarkedFile); + }) + .then(onChange) + .then(() => ToasterService.getInstance().success({ title: "Succès !", description: "Fichier uploadé avec succès!" })) + .catch((error) => ToasterService.getInstance().error({ title: "Erreur !", description: error.message })); + } catch (error) { + console.error('Error processing file with watermark:', error); + // If watermarking fails, proceed with original file + return new Promise( + (resolve: () => void) => { + const reader = new FileReader(); + reader.onload = (event) => { + if (event.target?.result) { + const arrayBuffer = event.target.result as ArrayBuffer; + const uint8Array = new Uint8Array(arrayBuffer); + + const fileBlob: FileBlob = { + type: file.type, + data: uint8Array + }; + + const fileData: FileData = { + file_blob: fileBlob, + file_name: file.name + }; + const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0'; + + FileService.createFile(fileData, validatorId).then((processCreated: any) => { + const fileUid: string = processCreated.processData.uid; + + DocumentService.getDocumentByUid(document.uid!).then((process: any) => { + if (process) { + const document: any = process.processData; + + let files: any[] = document.files; + if (!files) { + files = []; + } + files.push({ uid: fileUid }); + + DocumentService.updateDocument(process, { files: files, document_status: EDocumentStatus.DEPOSITED }).then(() => resolve()); + } + }); + }); + } + }; + reader.readAsArrayBuffer(file); + }) + .then(onChange) + .then(() => ToasterService.getInstance().success({ title: "Succès !", description: "Fichier uploadé avec succès!" })) + .catch((error) => ToasterService.getInstance().error({ title: "Erreur !", description: error.message })); + } }, [document.uid, onChange], ); diff --git a/src/front/Services/WatermarkService/index.ts b/src/front/Services/WatermarkService/index.ts new file mode 100644 index 00000000..b7dcf66a --- /dev/null +++ b/src/front/Services/WatermarkService/index.ts @@ -0,0 +1,211 @@ +export default class WatermarkService { + private static instance: WatermarkService; + + public static getInstance(): WatermarkService { + if (!WatermarkService.instance) { + WatermarkService.instance = new WatermarkService(); + } + return WatermarkService.instance; + } + + /** + * Add a watermark to a file based on its type + * @param file - The original file + * @returns Promise - The file with watermark added + */ + public async addWatermark(file: File): Promise { + const fileType = file.type; + + try { + if (fileType.startsWith('image/')) { + return await this.addWatermarkToImage(file); + } else if (fileType === 'application/pdf') { + return await this.addWatermarkToPdf(file); + } else { + // For other file types, return the original file + console.log(`Watermark not supported for file type: ${fileType}`); + return file; + } + } catch (error) { + console.error('Error adding watermark:', error); + // Return original file if watermarking fails + return file; + } + } + + /** + * Add watermark to image files + * @param file - Image file + * @returns Promise - Image with watermark + */ + private async addWatermarkToImage(file: File): Promise { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = (event) => { + try { + const img = new Image(); + img.onload = () => { + try { + // Create canvas + const canvas = document.createElement('canvas'); + const ctx = canvas.getContext('2d'); + + if (!ctx) { + reject(new Error('Could not get canvas context')); + return; + } + + // Set canvas size to image size + canvas.width = img.width; + canvas.height = img.height; + + // Draw original image + ctx.drawImage(img, 0, 0); + + // Add watermark + this.addImageWatermark(ctx, img.width, img.height); + + // Convert to blob + canvas.toBlob((blob) => { + if (blob) { + const watermarkedFile = new File([blob], file.name, { type: file.type }); + resolve(watermarkedFile); + } else { + reject(new Error('Could not create blob from canvas')); + } + }, file.type); + } catch (error) { + reject(error); + } + }; + img.onerror = reject; + img.src = event.target?.result as string; + } catch (error) { + reject(error); + } + }; + reader.onerror = reject; + reader.readAsDataURL(file); + }); + } + + /** + * Add watermark to PDF files + * @param file - PDF file + * @returns Promise - PDF with watermark + */ + private async addWatermarkToPdf(file: File): Promise { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = async (event) => { + try { + const arrayBuffer = event.target?.result as ArrayBuffer; + + // Import pdf-lib dynamically to avoid SSR issues + const { PDFDocument, rgb } = await import('pdf-lib'); + + // Load the existing PDF + const pdfDoc = await PDFDocument.load(arrayBuffer); + + // Get all pages + const pages = pdfDoc.getPages(); + + // Add watermark to each page + for (const page of pages) { + this.addPdfWatermark(page, rgb(0.8, 0.2, 0.2)); // Pale red color + } + + // Save the modified PDF + const pdfBytes = await pdfDoc.save(); + const watermarkedFile = new File([pdfBytes], file.name, { type: file.type }); + resolve(watermarkedFile); + + } catch (error) { + console.error('Error adding watermark to PDF:', error); + // If PDF watermarking fails, return original file + resolve(file); + } + }; + reader.onerror = reject; + reader.readAsArrayBuffer(file); + }); + } + + /** + * Add watermark to image using Canvas + * @param ctx - Canvas 2D context + * @param width - Image width + * @param height - Image height + */ + private addImageWatermark(ctx: CanvasRenderingContext2D, width: number, height: number): void { + // Save current state + ctx.save(); + + // Set watermark properties + ctx.fillStyle = 'rgba(128, 128, 128, 0.7)'; // Semi-transparent gray + ctx.font = '12px Arial'; + ctx.textAlign = 'right'; + ctx.textBaseline = 'bottom'; + + // Position watermark in bottom-right corner + const text = 'Processed by LeCoffre'; + const x = width - 10; // 10 pixels from right edge + const y = height - 10; // 10 pixels from bottom + + // Add watermark text + ctx.fillText(text, x, y); + + // Restore state + ctx.restore(); + } + + /** + * Add watermark to PDF using pdf-lib + * @param page - PDF page from pdf-lib + * @param color - Color for the watermark + */ + private addPdfWatermark(page: any, color: any): void { + const { width, height } = page.getSize(); + + // Calculate watermark position (bottom-right corner) + const text = 'Processed by LeCoffre'; + const dateTime = new Date().toLocaleString('fr-FR', { + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit' + }); + + const fontSize = 10; + const lineHeight = 12; // Space between lines + + // Calculate text widths (approximate - pdf-lib doesn't have a direct method for this) + // Using a conservative estimate: ~6 points per character for 10pt font + const estimatedTextWidth1 = text.length * 6; + const estimatedTextWidth2 = dateTime.length * 6; + const maxTextWidth = Math.max(estimatedTextWidth1, estimatedTextWidth2); + + // Position watermark with proper margins (20 points from edges) + const x = width - maxTextWidth - 20; // 20 points from right edge + const y = 20; // 20 points from bottom + + // Add watermark text with transparency (first line) + page.drawText(text, { + x: x, + y: y + lineHeight, // Second line (top) + size: fontSize, + color: color, + opacity: 0.7 + }); + + // Add date/time with transparency (second line) + page.drawText(dateTime, { + x: x, + y: y, // First line (bottom) + size: fontSize, + color: color, + opacity: 0.7 + }); + } +} \ No newline at end of file