Add watermark when loading documents

This commit is contained in:
Sosthene 2025-07-01 22:33:20 +02:00
parent 31ca61963a
commit 84366e749e
3 changed files with 301 additions and 37 deletions

View File

@ -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",

View File

@ -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<void>(
(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);
const fileBlob: FileBlob = {
type: file.type,
data: uint8Array
};
return new Promise<void>(
(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 fileData: FileData = {
file_blob: fileBlob,
file_name: file.name
};
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
const fileBlob: FileBlob = {
type: watermarkedFile.type,
data: uint8Array
};
FileService.createFile(fileData, validatorId).then((processCreated: any) => {
const fileUid: string = processCreated.processData.uid;
const fileData: FileData = {
file_blob: fileBlob,
file_name: watermarkedFile.name
};
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
DocumentService.getDocumentByUid(document.uid!).then((process: any) => {
if (process) {
const document: any = process.processData;
FileService.createFile(fileData, validatorId).then((processCreated: any) => {
const fileUid: string = processCreated.processData.uid;
let files: any[] = document.files;
if (!files) {
files = [];
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());
}
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<void>(
(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],
);

View File

@ -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<File> - The file with watermark added
*/
public async addWatermark(file: File): Promise<File> {
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<File> - Image with watermark
*/
private async addWatermarkToImage(file: File): Promise<File> {
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<File> - PDF with watermark
*/
private async addWatermarkToPdf(file: File): Promise<File> {
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
});
}
}