2025-07-03 18:09:02 +02:00

211 lines
5.8 KiB
TypeScript

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
});
}
}