Compare commits

...

2 Commits

Author SHA1 Message Date
Sosthene
747328324a Refactor certificate generation 2025-07-01 23:26:37 +02:00
Sosthene
84366e749e Add watermark when loading documents 2025-07-01 22:33:20 +02:00
5 changed files with 900 additions and 213 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,7 +32,57 @@ export default function DepositDocumentComponent(props: IProps) {
}, [document.files]);
const addFile = useCallback(
(file: File) => {
async (file: File) => {
try {
// Add watermark to the file before processing
const watermarkedFile = await WatermarkService.getInstance().addWatermark(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: watermarkedFile.type,
data: uint8Array
};
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;
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(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();
@ -75,6 +126,7 @@ export default function DepositDocumentComponent(props: IProps) {
.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

@ -210,40 +210,34 @@ export default function DocumentTables(props: IProps) {
}
};
// Fetch folder data to get office/notary information
// const folderProcess = await FolderService.getFolderByUid(folderUid, false, true);
// const folderData = folderProcess?.processData;
// Get the specific document that was clicked
const documentProcess = await DocumentService.getDocumentByUid(doc.uid);
if (!documentProcess) {
throw new Error('Document not found');
}
// console.log('[DocumentTables] onDownloadCertificate: folderData', folderData);
// Process only the files for this specific document
for (const file of documentProcess.processData.files) {
const fileProcess = await FileService.getFileByUid(file.uid);
console.log('[DocumentTables] onDownloadCertificate: fileProcess', fileProcess);
const documentProcesses = await DocumentService.getDocuments();
documentProcesses.filter((process: any) => process.processData.folder.uid === folderUid);
// console.log('[DocumentTables] onDownloadCertificate: documentProcesses', documentProcesses);
for (const document of documentProcesses) {
for (const file of document.processData.files) {
await FileService.getFileByUid(file.uid).then((res: any) => {
console.log('[DocumentTables] onDownloadCertificate: fileProcess', res);
const hash = res.lastUpdatedFileState.pcd_commitment.file_blob;
const hash = fileProcess.lastUpdatedFileState.pcd_commitment.file_blob;
certificateData.documentHash = hash;
MessageBus.getInstance().generateMerkleProof(res.lastUpdatedFileState, 'file_blob').then((proof) => {
const proof = await MessageBus.getInstance().generateMerkleProof(fileProcess.lastUpdatedFileState, 'file_blob');
console.log('[DocumentTables] onDownloadCertificate: proof', proof);
const metadata: Metadata = {
fileName: res.processData.file_name,
fileName: fileProcess.processData.file_name,
isDeleted: false,
updatedAt: new Date(res.processData.updated_at),
commitmentId: res.lastUpdatedFileState.commited_in,
createdAt: new Date(res.processData.created_at),
documentUid: doc.document_type.uid,
updatedAt: new Date(fileProcess.processData.updated_at),
commitmentId: fileProcess.lastUpdatedFileState.commited_in,
createdAt: new Date(fileProcess.processData.created_at),
documentUid: doc.uid,
documentType: doc.document_type.name,
merkleProof: proof
};
certificateData.metadata = metadata;
});
}
)}
}
console.log('[DocumentTables] onDownloadCertificate: certificateData', certificateData);

View File

@ -1,5 +1,5 @@
import { saveAs } from 'file-saver';
import jsPDF from 'jspdf';
import { PDFDocument, rgb, StandardFonts } from 'pdf-lib';
export interface CustomerInfo {
firstName: string;
@ -49,92 +49,218 @@ export default class PdfService {
*/
public async generateCertificate(certificateData: CertificateData): Promise<Blob> {
try {
const doc = new jsPDF();
const pdfDoc = await PDFDocument.create();
const page = pdfDoc.addPage([595, 842]); // A4 size
const { width, height } = page.getSize();
const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica);
const helveticaBoldFont = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
const helveticaObliqueFont = await pdfDoc.embedFont(StandardFonts.HelveticaOblique);
let y = height - 40; // Start 40pt from the top
const leftMargin = 20;
const rightSectionX = 320;
const lineSpacing = 16;
// Notary Information Section (Top Left)
doc.setFontSize(12);
doc.setFont('helvetica', 'bold');
doc.text('Notaire Validateur:', 20, 30);
doc.setFont('helvetica', 'normal');
doc.text(certificateData.notary.name, 20, 37);
page.drawText('Notaire Validateur:', {
x: leftMargin,
y: y,
size: 12,
font: helveticaBoldFont,
color: rgb(0, 0, 0)
});
y -= lineSpacing;
page.drawText(certificateData.notary.name, {
x: leftMargin,
y: y,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
// Customer Information Section (Top Right)
doc.setFont('helvetica', 'bold');
doc.text('Fournisseur de Document:', 120, 30);
doc.setFont('helvetica', 'normal');
doc.text(`${certificateData.customer.firstName} ${certificateData.customer.lastName}`, 120, 37);
doc.text(certificateData.customer.email, 120, 44);
doc.text(certificateData.customer.postalAddress, 120, 51);
let yRight = height - 40;
page.drawText('Fournisseur de Document:', {
x: rightSectionX,
y: yRight,
size: 12,
font: helveticaBoldFont,
color: rgb(0, 0, 0)
});
yRight -= lineSpacing;
page.drawText(`${certificateData.customer.firstName} ${certificateData.customer.lastName}`, {
x: rightSectionX,
y: yRight,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
yRight -= lineSpacing;
page.drawText(certificateData.customer.email, {
x: rightSectionX,
y: yRight,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
yRight -= lineSpacing;
page.drawText(certificateData.customer.postalAddress, {
x: rightSectionX,
y: yRight,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
// Centered Title
doc.setFontSize(20);
doc.setFont('helvetica', 'bold');
doc.text('Certificat de Validation de Document', 105, 80, { align: 'center' });
y -= 4 * lineSpacing; // Add more space between header and title
const titleText = 'Certificat de Validation de Document';
const titleWidth = helveticaBoldFont.widthOfTextAtSize(titleText, 20);
page.drawText(titleText, {
x: (width - titleWidth) / 2,
y: y,
size: 20,
font: helveticaBoldFont,
color: rgb(0, 0, 0)
});
y -= lineSpacing;
// Add a line separator
doc.setLineWidth(0.5);
doc.line(20, 90, 190, 90);
// Reset font for content
doc.setFontSize(12);
doc.setFont('helvetica', 'normal');
let yPosition = 110;
page.drawLine({
start: { x: leftMargin, y: y },
end: { x: width - leftMargin, y: y },
thickness: 0.5,
color: rgb(0, 0, 0)
});
y -= lineSpacing;
// Document Information Section
doc.setFont('helvetica', 'bold');
doc.text('Informations du Document', 20, yPosition);
yPosition += 10;
doc.setFont('helvetica', 'normal');
doc.text(`UID du Document: ${certificateData.metadata.documentUid}`, 20, yPosition);
yPosition += 7;
doc.text(`Type de Document: ${certificateData.metadata.documentType}`, 20, yPosition);
yPosition += 7;
doc.text(`UID du Dossier: ${certificateData.folderUid}`, 20, yPosition);
yPosition += 7;
doc.text(`Créé le: ${certificateData.metadata.createdAt.toLocaleDateString('fr-FR')}`, 20, yPosition);
yPosition += 7;
doc.text(`Nom du fichier: ${certificateData.metadata.fileName}`, 20, yPosition);
yPosition += 7;
doc.text(`ID de transaction: ${certificateData.metadata.commitmentId}`, 20, yPosition);
yPosition += 7;
doc.text(`Dernière modification: ${certificateData.metadata.updatedAt.toLocaleDateString('fr-FR')}`, 20, yPosition);
yPosition += 7;
doc.text(`Statut: ${certificateData.metadata.isDeleted ? 'Supprimé' : 'Actif'}`, 20, yPosition);
yPosition += 15;
page.drawText('Informations du Document', {
x: leftMargin,
y: y,
size: 12,
font: helveticaBoldFont,
color: rgb(0, 0, 0)
});
y -= lineSpacing;
page.drawText(`UID du Dossier: ${certificateData.folderUid}`, {
x: leftMargin,
y: y,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
y -= lineSpacing;
page.drawText(`Type de Document: ${certificateData.metadata.documentType}`, {
x: leftMargin,
y: y,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
y -= lineSpacing;
page.drawText(`Nom du fichier: ${certificateData.metadata.fileName}`, {
x: leftMargin,
y: y,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
y -= lineSpacing;
page.drawText(`Créé le: ${certificateData.metadata.createdAt.toLocaleDateString('fr-FR')}`, {
x: leftMargin,
y: y,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
y -= lineSpacing;
page.drawText(`Dernière modification: ${certificateData.metadata.updatedAt.toLocaleDateString('fr-FR')}`, {
x: leftMargin,
y: y,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
y -= lineSpacing;
// Document Hash Section
doc.setFont('helvetica', 'bold');
doc.text('Intégrité du Document', 20, yPosition);
yPosition += 10;
page.drawText('Intégrité du Document', {
x: leftMargin,
y: y,
size: 12,
font: helveticaBoldFont,
color: rgb(0, 0, 0)
});
y -= lineSpacing;
doc.setFont('helvetica', 'normal');
doc.text(`Hash SHA256 du Document:`, 20, yPosition);
yPosition += 7;
// Add verification data as base64
const verificationData = {
documentHash: certificateData.documentHash,
commitmentId: certificateData.metadata.commitmentId,
merkleProof: certificateData.metadata.merkleProof || "N/A"
};
const verificationDataBase64 = btoa(JSON.stringify(verificationData));
// Split hash into multiple lines if needed
const hash = certificateData.documentHash;
const maxWidth = 170; // Available width for text
const hashLines = this.splitTextToFit(doc, hash, maxWidth);
// Calculate proper chunk size based on available width and font size
const availableWidth = width - (2 * leftMargin) - 20; // Full width minus margins and safety buffer
const fontSize = 12;
// Use a typical base64 character for width calculation
const avgCharWidth = helveticaFont.widthOfTextAtSize('A', fontSize);
const charsPerLine = Math.floor(availableWidth / avgCharWidth);
const chunkSize = Math.max(60, Math.min(100, charsPerLine)); // More conservative limits
for (const line of hashLines) {
doc.text(line, 25, yPosition);
yPosition += 7;
const chunks = [];
for (let j = 0; j < verificationDataBase64.length; j += chunkSize) {
chunks.push(verificationDataBase64.slice(j, j + chunkSize));
}
yPosition += 8; // Extra space after hash
chunks.forEach((chunk, index) => {
page.drawText(chunk, {
x: leftMargin,
y: y - (index * 12), // Increased line spacing
size: fontSize,
font: helveticaFont,
color: rgb(0, 0, 0)
});
});
// Add explanatory text about certificate usage
y -= (chunks.length * 12) + 40; // Space after verification data
const explanatoryText = "Ce certificat doit être utilisé avec le document qu'il certifie pour être vérifié sur la page dédiée. Le document correspondant à ce certificat doit être téléchargé depuis LeCoffre et peut être conservé avec le certificat tant qu'il n'est pas modifié.";
const explanatoryLines = this.splitTextToFit(helveticaObliqueFont, explanatoryText, width - (2 * leftMargin), 11);
explanatoryLines.forEach((line, index) => {
page.drawText(line, {
x: leftMargin,
y: y - (index * 14), // Slightly more spacing for readability
size: 11,
font: helveticaObliqueFont,
color: rgb(0.3, 0.3, 0.3) // Slightly grayed out to distinguish from main content
});
});
// Footer
const pageCount = doc.getNumberOfPages();
for (let i = 1; i <= pageCount; i++) {
doc.setPage(i);
doc.setFontSize(10);
doc.setFont('helvetica', 'italic');
doc.text(`Page ${i} sur ${pageCount}`, 105, 280, { align: 'center' });
doc.text(`Généré le ${new Date().toLocaleString('fr-FR')}`, 105, 285, { align: 'center' });
}
const footerText1 = `Page 1 sur 1`;
const footerText2 = `Généré le ${new Date().toLocaleString('fr-FR')}`;
const footerWidth1 = helveticaObliqueFont.widthOfTextAtSize(footerText1, 10);
const footerWidth2 = helveticaObliqueFont.widthOfTextAtSize(footerText2, 10);
page.drawText(footerText1, {
x: (width - footerWidth1) / 2,
y: 35,
size: 10,
font: helveticaObliqueFont,
color: rgb(0, 0, 0)
});
page.drawText(footerText2, {
x: (width - footerWidth2) / 2,
y: 25,
size: 10,
font: helveticaObliqueFont,
color: rgb(0, 0, 0)
});
return doc.output('blob');
const pdfBytes = await pdfDoc.save();
return new Blob([pdfBytes], { type: 'application/pdf' });
} catch (error) {
console.error('Error generating certificate:', error);
throw new Error('Failed to generate certificate');
@ -143,21 +269,22 @@ export default class PdfService {
/**
* Split text to fit within a specified width
* @param doc - jsPDF document instance
* @param font - PDF font instance
* @param text - Text to split
* @param maxWidth - Maximum width in points
* @param fontSize - Font size
* @returns Array of text lines
*/
private splitTextToFit(doc: jsPDF, text: string, maxWidth: number): string[] {
private splitTextToFit(font: any, text: string, maxWidth: number, fontSize: number): string[] {
const lines: string[] = [];
let currentLine = '';
// Split by words first
const words = text.split('');
// Split by characters (pdf-lib doesn't have word-level text measurement)
const chars = text.split('');
for (const char of words) {
for (const char of chars) {
const testLine = currentLine + char;
const testWidth = doc.getTextWidth(testLine);
const testWidth = font.widthOfTextAtSize(testLine, fontSize);
if (testWidth <= maxWidth) {
currentLine = testLine;
@ -202,92 +329,257 @@ export default class PdfService {
*/
public async generateNotaryCertificate(certificateData: CertificateData): Promise<Blob> {
try {
const doc = new jsPDF();
// Create a new PDF document
const pdfDoc = await PDFDocument.create();
const page = pdfDoc.addPage([595, 842]); // A4 size
const { width, height } = page.getSize();
// Embed the standard font
const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica);
const helveticaBoldFont = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
const helveticaObliqueFont = await pdfDoc.embedFont(StandardFonts.HelveticaOblique);
// Notary Information Section (Top Left)
doc.setFontSize(12);
doc.setFont('helvetica', 'bold');
doc.text('Notaire Validateur:', 20, 30);
doc.setFont('helvetica', 'normal');
doc.text(certificateData.notary.name, 20, 37);
page.drawText('Notaire Validateur:', {
x: 20,
y: height - 30,
size: 12,
font: helveticaBoldFont,
color: rgb(0, 0, 0)
});
page.drawText(certificateData.notary.name, {
x: 20,
y: height - 37,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
// Customer Information Section (Top Right)
doc.setFont('helvetica', 'bold');
doc.text('Fournisseur de Document:', 120, 30);
doc.setFont('helvetica', 'normal');
doc.text(`${certificateData.customer.firstName} ${certificateData.customer.lastName}`, 120, 37);
doc.text(certificateData.customer.email, 120, 44);
doc.text(certificateData.customer.postalAddress, 120, 51);
page.drawText('Fournisseur de Document:', {
x: 120,
y: height - 30,
size: 12,
font: helveticaBoldFont,
color: rgb(0, 0, 0)
});
page.drawText(`${certificateData.customer.firstName} ${certificateData.customer.lastName}`, {
x: 120,
y: height - 37,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
page.drawText(certificateData.customer.email, {
x: 120,
y: height - 44,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
page.drawText(certificateData.customer.postalAddress, {
x: 120,
y: height - 51,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
// Centered Title
doc.setFontSize(20);
doc.setFont('helvetica', 'bold');
doc.text('Certificat Notarial de Validation de Document', 105, 80, { align: 'center' });
const titleText = 'Certificat Notarial de Validation de Document';
const titleWidth = helveticaBoldFont.widthOfTextAtSize(titleText, 20);
page.drawText(titleText, {
x: (width - titleWidth) / 2,
y: height - 80,
size: 20,
font: helveticaBoldFont,
color: rgb(0, 0, 0)
});
// Add a line separator
doc.setLineWidth(0.5);
doc.line(20, 90, 190, 90);
page.drawLine({
start: { x: 20, y: height - 90 },
end: { x: width - 20, y: height - 90 },
thickness: 0.5,
color: rgb(0, 0, 0)
});
// Reset font for content
doc.setFontSize(12);
doc.setFont('helvetica', 'normal');
let yPosition = 110;
let yPosition = height - 110;
// Document Information Section
doc.setFont('helvetica', 'bold');
doc.text('Informations du Document', 20, yPosition);
yPosition += 10;
page.drawText('Informations du Document', {
x: 20,
y: yPosition,
size: 12,
font: helveticaBoldFont,
color: rgb(0, 0, 0)
});
yPosition -= 10;
doc.setFont('helvetica', 'normal');
doc.text(`Identifiant du Document: ${certificateData.metadata.documentUid}`, 20, yPosition);
yPosition += 7;
doc.text(`Type de Document: ${certificateData.metadata.documentType}`, 20, yPosition);
yPosition += 7;
doc.text(`Numéro de dossier: ${certificateData.folderUid}`, 20, yPosition);
yPosition += 7;
doc.text(`Créé le: ${certificateData.metadata.createdAt.toLocaleDateString('fr-FR')}`, 20, yPosition);
yPosition += 7;
doc.text(`Nom du fichier: ${certificateData.metadata.fileName}`, 20, yPosition);
yPosition += 7;
doc.text(`ID de transaction: ${certificateData.metadata.commitmentId}`, 20, yPosition);
yPosition += 7;
doc.text(`Dernière modification: ${certificateData.metadata.updatedAt.toLocaleDateString('fr-FR')}`, 20, yPosition);
yPosition += 7;
doc.text(`Statut: ${certificateData.metadata.isDeleted ? 'Supprimé' : 'Actif'}`, 20, yPosition);
yPosition += 15;
page.drawText(`Identifiant du Document: ${certificateData.metadata.documentUid}`, {
x: 20,
y: yPosition,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
yPosition -= 7;
page.drawText(`Type de Document: ${certificateData.metadata.documentType}`, {
x: 20,
y: yPosition,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
yPosition -= 7;
page.drawText(`Numéro de dossier: ${certificateData.folderUid}`, {
x: 20,
y: yPosition,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
yPosition -= 7;
page.drawText(`Créé le: ${certificateData.metadata.createdAt.toLocaleDateString('fr-FR')}`, {
x: 20,
y: yPosition,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
yPosition -= 7;
page.drawText(`Nom du fichier: ${certificateData.metadata.fileName}`, {
x: 20,
y: yPosition,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
yPosition -= 7;
page.drawText(`ID de transaction: ${certificateData.metadata.commitmentId}`, {
x: 20,
y: yPosition,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
yPosition -= 7;
page.drawText(`Dernière modification: ${certificateData.metadata.updatedAt.toLocaleDateString('fr-FR')}`, {
x: 20,
y: yPosition,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
yPosition -= 7;
page.drawText(`Statut: ${certificateData.metadata.isDeleted ? 'Supprimé' : 'Actif'}`, {
x: 20,
y: yPosition,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
yPosition -= 15;
// Document Hash Section
doc.setFont('helvetica', 'bold');
doc.text('Intégrité du Document', 20, yPosition);
yPosition += 10;
page.drawText('Intégrité du Document', {
x: 20,
y: yPosition,
size: 12,
font: helveticaBoldFont,
color: rgb(0, 0, 0)
});
yPosition -= 10;
doc.setFont('helvetica', 'normal');
doc.text(`Hash SHA256 du Document:`, 20, yPosition);
yPosition += 7;
page.drawText(`Hash SHA256 du Document:`, {
x: 20,
y: yPosition,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
yPosition -= 7;
// Split hash into multiple lines if needed
const hash = certificateData.documentHash;
const maxWidth = 170; // Available width for text
const hashLines = this.splitTextToFit(doc, hash, maxWidth);
const hashLines = this.splitTextToFit(helveticaFont, hash, maxWidth, 12);
for (const line of hashLines) {
doc.text(line, 25, yPosition);
yPosition += 7;
page.drawText(line, {
x: 25,
y: yPosition,
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0)
});
yPosition -= 7;
}
yPosition += 8; // Extra space after hash
yPosition -= 8; // Extra space after hash
yPosition -= 5;
// Footer
const pageCount = doc.getNumberOfPages();
for (let i = 1; i <= pageCount; i++) {
doc.setPage(i);
doc.setFontSize(10);
doc.setFont('helvetica', 'italic');
doc.text(`Page ${i} sur ${pageCount}`, 105, 280, { align: 'center' });
doc.text(`Certificat Notarial - Généré le ${new Date().toLocaleString('fr-FR')}`, 105, 285, { align: 'center' });
const footerText1 = `Page 1 sur 1`;
const footerText2 = `Certificat Notarial - Généré le ${new Date().toLocaleString('fr-FR')}`;
const footerWidth1 = helveticaObliqueFont.widthOfTextAtSize(footerText1, 10);
const footerWidth2 = helveticaObliqueFont.widthOfTextAtSize(footerText2, 10);
page.drawText(footerText1, {
x: (width - footerWidth1) / 2,
y: 30,
size: 10,
font: helveticaObliqueFont,
color: rgb(0, 0, 0)
});
page.drawText(footerText2, {
x: (width - footerWidth2) / 2,
y: 25,
size: 10,
font: helveticaObliqueFont,
color: rgb(0, 0, 0)
});
// Add verification data as base64 in small font
const verificationData = {
documentHash: certificateData.documentHash,
commitmentId: certificateData.metadata.commitmentId,
merkleProof: certificateData.metadata.merkleProof || "N/A"
};
const verificationDataBase64 = btoa(JSON.stringify(verificationData));
// Split into chunks if too long
const chunkSize = 80;
const chunks = [];
for (let j = 0; j < verificationDataBase64.length; j += chunkSize) {
chunks.push(verificationDataBase64.slice(j, j + chunkSize));
}
return doc.output('blob');
chunks.forEach((chunk, index) => {
page.drawText(chunk, {
x: 20,
y: 15 - (index * 3),
size: 6,
font: helveticaFont,
color: rgb(0, 0, 0)
});
});
// Save the PDF
const pdfBytes = await pdfDoc.save();
return new Blob([pdfBytes], { type: 'application/pdf' });
} catch (error) {
console.error('Error generating notary certificate:', error);
throw new Error('Failed to generate notary certificate');
@ -309,4 +601,141 @@ export default class PdfService {
throw error;
}
}
/**
* Parse a PDF certificate and extract document information
* @param pdfBlob - The PDF file as a blob
* @returns Promise<{documentHash: string, documentUid: string, commitmentId: string, merkleProof?: string}> - Extracted information
*/
public async parseCertificate(pdfBlob: Blob): Promise<{documentHash: string, documentUid: string, commitmentId: string, merkleProof?: string}> {
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
fileReader.onload = async () => {
try {
// Convert PDF to text using browser's PDF capabilities
const arrayBuffer = fileReader.result as ArrayBuffer;
const pdfData = new Uint8Array(arrayBuffer);
console.log("PDF data:", pdfData);
// Use a simple text extraction approach
// This is a basic implementation - for production, consider using pdfjs-dist
const text = await this.extractTextFromPdf(pdfData);
// Parse the extracted text to find our certificate data
const parsedData = this.parseCertificateText(text);
if (!parsedData.documentHash) {
throw new Error('Document hash not found in certificate');
}
resolve(parsedData);
} catch (error) {
reject(error);
}
};
fileReader.onerror = () => {
reject(new Error('Failed to read PDF file'));
};
fileReader.readAsArrayBuffer(pdfBlob);
});
}
/**
* Extract text from PDF using browser capabilities
* @param pdfData - PDF data as Uint8Array
* @returns Promise<string> - Extracted text
*/
private async extractTextFromPdf(pdfData: Uint8Array): Promise<string> {
console.log("extractTextFromPdf");
// Convert PDF data to string to search for base64 patterns
const pdfString = new TextDecoder('utf-8').decode(pdfData);
// Look for base64 patterns in the PDF content
// This is a simple approach that should work for our embedded data
const base64Matches = pdfString.match(/([A-Za-z0-9+/]{80,}={0,2})/g);
if (base64Matches && base64Matches.length > 0) {
console.log('Found base64 patterns in PDF:', base64Matches.length);
// Return the longest base64 string (most likely our verification data)
const longestBase64 = base64Matches.reduce((a, b) => a.length > b.length ? a : b);
return longestBase64;
}
// If no base64 found, return empty string
console.log('No base64 patterns found in PDF');
return '';
}
/**
* Parse certificate text to extract specific fields
* @param text - Extracted text from PDF (could be base64 or regular text)
* @returns Parsed certificate data
*/
private parseCertificateText(text: string): {documentHash: string, documentUid: string, commitmentId: string, merkleProof?: string} {
const result = {
documentHash: '',
documentUid: '',
commitmentId: '',
merkleProof: undefined as string | undefined
};
// Check if the text is a base64 string (our new format)
if (text.match(/^[A-Za-z0-9+/]+={0,2}$/)) {
try {
console.log('Attempting to decode base64 data:', text.substring(0, 50) + '...');
const decodedData = atob(text);
const verificationData = JSON.parse(decodedData);
console.log('Successfully decoded verification data:', verificationData);
if (verificationData.documentHash) {
result.documentHash = verificationData.documentHash;
}
if (verificationData.commitmentId) {
result.commitmentId = verificationData.commitmentId;
}
if (verificationData.merkleProof && verificationData.merkleProof !== "N/A") {
result.merkleProof = verificationData.merkleProof;
}
// If we successfully extracted data from base64, return early
if (result.documentHash) {
return result;
}
} catch (error) {
console.log('Failed to decode base64 data:', error);
}
}
// Fallback to text parsing for older certificates
// Extract document hash (64 character hex string)
const hashMatch = text.match(/Hash SHA256 du Document:\s*([a-fA-F0-9]{64})/);
if (hashMatch && hashMatch[1]) {
result.documentHash = hashMatch[1];
}
// Extract document UID
const uidMatch = text.match(/UID du Document:\s*([^\n\r]+)/);
if (uidMatch && uidMatch[1]) {
result.documentUid = uidMatch[1].trim();
}
// Extract commitment ID
const commitmentMatch = text.match(/ID de transaction:\s*([^\n\r]+)/);
if (commitmentMatch && commitmentMatch[1]) {
result.commitmentId = commitmentMatch[1].trim();
}
// Extract merkle proof
const merkleProofMatch = text.match(/Preuve Merkle \(Blockchain\):\s*([^\n\r]+)/);
if (merkleProofMatch && merkleProofMatch[1]) {
result.merkleProof = merkleProofMatch[1].trim();
}
return result;
}
}

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