Compare commits
2 Commits
31ca61963a
...
747328324a
Author | SHA1 | Date | |
---|---|---|---|
![]() |
747328324a | ||
![]() |
84366e749e |
@ -32,6 +32,7 @@
|
|||||||
"jwt-decode": "^3.1.2",
|
"jwt-decode": "^3.1.2",
|
||||||
"le-coffre-resources": "file:../lecoffre-ressources",
|
"le-coffre-resources": "file:../lecoffre-ressources",
|
||||||
"next": "^14.2.3",
|
"next": "^14.2.3",
|
||||||
|
"pdf-lib": "^1.17.1",
|
||||||
"prettier": "^2.8.7",
|
"prettier": "^2.8.7",
|
||||||
"react": "18.2.0",
|
"react": "18.2.0",
|
||||||
"react-dom": "18.2.0",
|
"react-dom": "18.2.0",
|
||||||
|
@ -10,6 +10,7 @@ import Confirm from "@Front/Components/DesignSystem/OldModal/Confirm";
|
|||||||
import FileService from "src/common/Api/LeCoffreApi/sdk/FileService";
|
import FileService from "src/common/Api/LeCoffreApi/sdk/FileService";
|
||||||
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
|
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
|
||||||
import { FileBlob, FileData } from "@Front/Api/Entities/types";
|
import { FileBlob, FileData } from "@Front/Api/Entities/types";
|
||||||
|
import WatermarkService from "@Front/Services/WatermarkService";
|
||||||
|
|
||||||
type IProps = {
|
type IProps = {
|
||||||
document: any;
|
document: any;
|
||||||
@ -31,50 +32,101 @@ export default function DepositDocumentComponent(props: IProps) {
|
|||||||
}, [document.files]);
|
}, [document.files]);
|
||||||
|
|
||||||
const addFile = useCallback(
|
const addFile = useCallback(
|
||||||
(file: File) => {
|
async (file: File) => {
|
||||||
return new Promise<void>(
|
try {
|
||||||
(resolve: () => void) => {
|
// Add watermark to the file before processing
|
||||||
const reader = new FileReader();
|
const watermarkedFile = await WatermarkService.getInstance().addWatermark(file);
|
||||||
reader.onload = (event) => {
|
|
||||||
if (event.target?.result) {
|
return new Promise<void>(
|
||||||
const arrayBuffer = event.target.result as ArrayBuffer;
|
(resolve: () => void) => {
|
||||||
const uint8Array = new Uint8Array(arrayBuffer);
|
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 = {
|
const fileBlob: FileBlob = {
|
||||||
type: file.type,
|
type: watermarkedFile.type,
|
||||||
data: uint8Array
|
data: uint8Array
|
||||||
};
|
};
|
||||||
|
|
||||||
const fileData: FileData = {
|
const fileData: FileData = {
|
||||||
file_blob: fileBlob,
|
file_blob: fileBlob,
|
||||||
file_name: file.name
|
file_name: watermarkedFile.name
|
||||||
};
|
};
|
||||||
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
||||||
|
|
||||||
FileService.createFile(fileData, validatorId).then((processCreated: any) => {
|
FileService.createFile(fileData, validatorId).then((processCreated: any) => {
|
||||||
const fileUid: string = processCreated.processData.uid;
|
const fileUid: string = processCreated.processData.uid;
|
||||||
|
|
||||||
DocumentService.getDocumentByUid(document.uid!).then((process: any) => {
|
DocumentService.getDocumentByUid(document.uid!).then((process: any) => {
|
||||||
if (process) {
|
if (process) {
|
||||||
const document: any = process.processData;
|
const document: any = process.processData;
|
||||||
|
|
||||||
let files: any[] = document.files;
|
let files: any[] = document.files;
|
||||||
if (!files) {
|
if (!files) {
|
||||||
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(watermarkedFile);
|
||||||
reader.readAsArrayBuffer(file);
|
})
|
||||||
})
|
.then(onChange)
|
||||||
.then(onChange)
|
.then(() => ToasterService.getInstance().success({ title: "Succès !", description: "Fichier uploadé avec succès!" }))
|
||||||
.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) => 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],
|
[document.uid, onChange],
|
||||||
);
|
);
|
||||||
|
@ -210,40 +210,34 @@ export default function DocumentTables(props: IProps) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Fetch folder data to get office/notary information
|
// Get the specific document that was clicked
|
||||||
// const folderProcess = await FolderService.getFolderByUid(folderUid, false, true);
|
const documentProcess = await DocumentService.getDocumentByUid(doc.uid);
|
||||||
// const folderData = folderProcess?.processData;
|
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 hash = fileProcess.lastUpdatedFileState.pcd_commitment.file_blob;
|
||||||
|
certificateData.documentHash = hash;
|
||||||
|
|
||||||
const documentProcesses = await DocumentService.getDocuments();
|
const proof = await MessageBus.getInstance().generateMerkleProof(fileProcess.lastUpdatedFileState, 'file_blob');
|
||||||
documentProcesses.filter((process: any) => process.processData.folder.uid === folderUid);
|
console.log('[DocumentTables] onDownloadCertificate: proof', proof);
|
||||||
|
|
||||||
// console.log('[DocumentTables] onDownloadCertificate: documentProcesses', documentProcesses);
|
const metadata: Metadata = {
|
||||||
|
fileName: fileProcess.processData.file_name,
|
||||||
for (const document of documentProcesses) {
|
isDeleted: false,
|
||||||
for (const file of document.processData.files) {
|
updatedAt: new Date(fileProcess.processData.updated_at),
|
||||||
await FileService.getFileByUid(file.uid).then((res: any) => {
|
commitmentId: fileProcess.lastUpdatedFileState.commited_in,
|
||||||
console.log('[DocumentTables] onDownloadCertificate: fileProcess', res);
|
createdAt: new Date(fileProcess.processData.created_at),
|
||||||
const hash = res.lastUpdatedFileState.pcd_commitment.file_blob;
|
documentUid: doc.uid,
|
||||||
certificateData.documentHash = hash;
|
documentType: doc.document_type.name,
|
||||||
|
merkleProof: proof
|
||||||
MessageBus.getInstance().generateMerkleProof(res.lastUpdatedFileState, 'file_blob').then((proof) => {
|
};
|
||||||
console.log('[DocumentTables] onDownloadCertificate: proof', proof);
|
certificateData.metadata = metadata;
|
||||||
const metadata: Metadata = {
|
|
||||||
fileName: res.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,
|
|
||||||
documentType: doc.document_type.name,
|
|
||||||
merkleProof: proof
|
|
||||||
};
|
|
||||||
certificateData.metadata = metadata;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
)}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('[DocumentTables] onDownloadCertificate: certificateData', certificateData);
|
console.log('[DocumentTables] onDownloadCertificate: certificateData', certificateData);
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
import { saveAs } from 'file-saver';
|
import { saveAs } from 'file-saver';
|
||||||
import jsPDF from 'jspdf';
|
import { PDFDocument, rgb, StandardFonts } from 'pdf-lib';
|
||||||
|
|
||||||
export interface CustomerInfo {
|
export interface CustomerInfo {
|
||||||
firstName: string;
|
firstName: string;
|
||||||
@ -49,92 +49,218 @@ export default class PdfService {
|
|||||||
*/
|
*/
|
||||||
public async generateCertificate(certificateData: CertificateData): Promise<Blob> {
|
public async generateCertificate(certificateData: CertificateData): Promise<Blob> {
|
||||||
try {
|
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)
|
// Notary Information Section (Top Left)
|
||||||
doc.setFontSize(12);
|
page.drawText('Notaire Validateur:', {
|
||||||
doc.setFont('helvetica', 'bold');
|
x: leftMargin,
|
||||||
doc.text('Notaire Validateur:', 20, 30);
|
y: y,
|
||||||
doc.setFont('helvetica', 'normal');
|
size: 12,
|
||||||
doc.text(certificateData.notary.name, 20, 37);
|
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)
|
// Customer Information Section (Top Right)
|
||||||
doc.setFont('helvetica', 'bold');
|
let yRight = height - 40;
|
||||||
doc.text('Fournisseur de Document:', 120, 30);
|
page.drawText('Fournisseur de Document:', {
|
||||||
doc.setFont('helvetica', 'normal');
|
x: rightSectionX,
|
||||||
doc.text(`${certificateData.customer.firstName} ${certificateData.customer.lastName}`, 120, 37);
|
y: yRight,
|
||||||
doc.text(certificateData.customer.email, 120, 44);
|
size: 12,
|
||||||
doc.text(certificateData.customer.postalAddress, 120, 51);
|
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
|
// Centered Title
|
||||||
doc.setFontSize(20);
|
y -= 4 * lineSpacing; // Add more space between header and title
|
||||||
doc.setFont('helvetica', 'bold');
|
const titleText = 'Certificat de Validation de Document';
|
||||||
doc.text('Certificat de Validation de Document', 105, 80, { align: 'center' });
|
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
|
// Add a line separator
|
||||||
doc.setLineWidth(0.5);
|
page.drawLine({
|
||||||
doc.line(20, 90, 190, 90);
|
start: { x: leftMargin, y: y },
|
||||||
|
end: { x: width - leftMargin, y: y },
|
||||||
// Reset font for content
|
thickness: 0.5,
|
||||||
doc.setFontSize(12);
|
color: rgb(0, 0, 0)
|
||||||
doc.setFont('helvetica', 'normal');
|
});
|
||||||
|
y -= lineSpacing;
|
||||||
let yPosition = 110;
|
|
||||||
|
|
||||||
// Document Information Section
|
// Document Information Section
|
||||||
doc.setFont('helvetica', 'bold');
|
page.drawText('Informations du Document', {
|
||||||
doc.text('Informations du Document', 20, yPosition);
|
x: leftMargin,
|
||||||
yPosition += 10;
|
y: y,
|
||||||
|
size: 12,
|
||||||
doc.setFont('helvetica', 'normal');
|
font: helveticaBoldFont,
|
||||||
doc.text(`UID du Document: ${certificateData.metadata.documentUid}`, 20, yPosition);
|
color: rgb(0, 0, 0)
|
||||||
yPosition += 7;
|
});
|
||||||
doc.text(`Type de Document: ${certificateData.metadata.documentType}`, 20, yPosition);
|
y -= lineSpacing;
|
||||||
yPosition += 7;
|
page.drawText(`UID du Dossier: ${certificateData.folderUid}`, {
|
||||||
doc.text(`UID du Dossier: ${certificateData.folderUid}`, 20, yPosition);
|
x: leftMargin,
|
||||||
yPosition += 7;
|
y: y,
|
||||||
doc.text(`Créé le: ${certificateData.metadata.createdAt.toLocaleDateString('fr-FR')}`, 20, yPosition);
|
size: 12,
|
||||||
yPosition += 7;
|
font: helveticaFont,
|
||||||
doc.text(`Nom du fichier: ${certificateData.metadata.fileName}`, 20, yPosition);
|
color: rgb(0, 0, 0)
|
||||||
yPosition += 7;
|
});
|
||||||
doc.text(`ID de transaction: ${certificateData.metadata.commitmentId}`, 20, yPosition);
|
y -= lineSpacing;
|
||||||
yPosition += 7;
|
page.drawText(`Type de Document: ${certificateData.metadata.documentType}`, {
|
||||||
doc.text(`Dernière modification: ${certificateData.metadata.updatedAt.toLocaleDateString('fr-FR')}`, 20, yPosition);
|
x: leftMargin,
|
||||||
yPosition += 7;
|
y: y,
|
||||||
doc.text(`Statut: ${certificateData.metadata.isDeleted ? 'Supprimé' : 'Actif'}`, 20, yPosition);
|
size: 12,
|
||||||
yPosition += 15;
|
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
|
// Document Hash Section
|
||||||
doc.setFont('helvetica', 'bold');
|
page.drawText('Intégrité du Document', {
|
||||||
doc.text('Intégrité du Document', 20, yPosition);
|
x: leftMargin,
|
||||||
yPosition += 10;
|
y: y,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaBoldFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
y -= lineSpacing;
|
||||||
|
|
||||||
|
// 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));
|
||||||
|
|
||||||
doc.setFont('helvetica', 'normal');
|
// Calculate proper chunk size based on available width and font size
|
||||||
doc.text(`Hash SHA256 du Document:`, 20, yPosition);
|
const availableWidth = width - (2 * leftMargin) - 20; // Full width minus margins and safety buffer
|
||||||
yPosition += 7;
|
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
|
||||||
|
|
||||||
// Split hash into multiple lines if needed
|
const chunks = [];
|
||||||
const hash = certificateData.documentHash;
|
for (let j = 0; j < verificationDataBase64.length; j += chunkSize) {
|
||||||
const maxWidth = 170; // Available width for text
|
chunks.push(verificationDataBase64.slice(j, j + chunkSize));
|
||||||
const hashLines = this.splitTextToFit(doc, hash, maxWidth);
|
|
||||||
|
|
||||||
for (const line of hashLines) {
|
|
||||||
doc.text(line, 25, yPosition);
|
|
||||||
yPosition += 7;
|
|
||||||
}
|
}
|
||||||
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
|
// Footer
|
||||||
const pageCount = doc.getNumberOfPages();
|
const footerText1 = `Page 1 sur 1`;
|
||||||
for (let i = 1; i <= pageCount; i++) {
|
const footerText2 = `Généré le ${new Date().toLocaleString('fr-FR')}`;
|
||||||
doc.setPage(i);
|
const footerWidth1 = helveticaObliqueFont.widthOfTextAtSize(footerText1, 10);
|
||||||
doc.setFontSize(10);
|
const footerWidth2 = helveticaObliqueFont.widthOfTextAtSize(footerText2, 10);
|
||||||
doc.setFont('helvetica', 'italic');
|
page.drawText(footerText1, {
|
||||||
doc.text(`Page ${i} sur ${pageCount}`, 105, 280, { align: 'center' });
|
x: (width - footerWidth1) / 2,
|
||||||
doc.text(`Généré le ${new Date().toLocaleString('fr-FR')}`, 105, 285, { align: 'center' });
|
y: 35,
|
||||||
}
|
size: 10,
|
||||||
|
font: helveticaObliqueFont,
|
||||||
return doc.output('blob');
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
page.drawText(footerText2, {
|
||||||
|
x: (width - footerWidth2) / 2,
|
||||||
|
y: 25,
|
||||||
|
size: 10,
|
||||||
|
font: helveticaObliqueFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
|
||||||
|
const pdfBytes = await pdfDoc.save();
|
||||||
|
return new Blob([pdfBytes], { type: 'application/pdf' });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error generating certificate:', error);
|
console.error('Error generating certificate:', error);
|
||||||
throw new Error('Failed to generate certificate');
|
throw new Error('Failed to generate certificate');
|
||||||
@ -143,21 +269,22 @@ export default class PdfService {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Split text to fit within a specified width
|
* Split text to fit within a specified width
|
||||||
* @param doc - jsPDF document instance
|
* @param font - PDF font instance
|
||||||
* @param text - Text to split
|
* @param text - Text to split
|
||||||
* @param maxWidth - Maximum width in points
|
* @param maxWidth - Maximum width in points
|
||||||
|
* @param fontSize - Font size
|
||||||
* @returns Array of text lines
|
* @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[] = [];
|
const lines: string[] = [];
|
||||||
let currentLine = '';
|
let currentLine = '';
|
||||||
|
|
||||||
// Split by words first
|
// Split by characters (pdf-lib doesn't have word-level text measurement)
|
||||||
const words = text.split('');
|
const chars = text.split('');
|
||||||
|
|
||||||
for (const char of words) {
|
for (const char of chars) {
|
||||||
const testLine = currentLine + char;
|
const testLine = currentLine + char;
|
||||||
const testWidth = doc.getTextWidth(testLine);
|
const testWidth = font.widthOfTextAtSize(testLine, fontSize);
|
||||||
|
|
||||||
if (testWidth <= maxWidth) {
|
if (testWidth <= maxWidth) {
|
||||||
currentLine = testLine;
|
currentLine = testLine;
|
||||||
@ -202,92 +329,257 @@ export default class PdfService {
|
|||||||
*/
|
*/
|
||||||
public async generateNotaryCertificate(certificateData: CertificateData): Promise<Blob> {
|
public async generateNotaryCertificate(certificateData: CertificateData): Promise<Blob> {
|
||||||
try {
|
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)
|
// Notary Information Section (Top Left)
|
||||||
doc.setFontSize(12);
|
page.drawText('Notaire Validateur:', {
|
||||||
doc.setFont('helvetica', 'bold');
|
x: 20,
|
||||||
doc.text('Notaire Validateur:', 20, 30);
|
y: height - 30,
|
||||||
doc.setFont('helvetica', 'normal');
|
size: 12,
|
||||||
doc.text(certificateData.notary.name, 20, 37);
|
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)
|
// Customer Information Section (Top Right)
|
||||||
doc.setFont('helvetica', 'bold');
|
page.drawText('Fournisseur de Document:', {
|
||||||
doc.text('Fournisseur de Document:', 120, 30);
|
x: 120,
|
||||||
doc.setFont('helvetica', 'normal');
|
y: height - 30,
|
||||||
doc.text(`${certificateData.customer.firstName} ${certificateData.customer.lastName}`, 120, 37);
|
size: 12,
|
||||||
doc.text(certificateData.customer.email, 120, 44);
|
font: helveticaBoldFont,
|
||||||
doc.text(certificateData.customer.postalAddress, 120, 51);
|
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
|
// Centered Title
|
||||||
doc.setFontSize(20);
|
const titleText = 'Certificat Notarial de Validation de Document';
|
||||||
doc.setFont('helvetica', 'bold');
|
const titleWidth = helveticaBoldFont.widthOfTextAtSize(titleText, 20);
|
||||||
doc.text('Certificat Notarial de Validation de Document', 105, 80, { align: 'center' });
|
page.drawText(titleText, {
|
||||||
|
x: (width - titleWidth) / 2,
|
||||||
|
y: height - 80,
|
||||||
|
size: 20,
|
||||||
|
font: helveticaBoldFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
|
||||||
// Add a line separator
|
// Add a line separator
|
||||||
doc.setLineWidth(0.5);
|
page.drawLine({
|
||||||
doc.line(20, 90, 190, 90);
|
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
|
let yPosition = height - 110;
|
||||||
doc.setFontSize(12);
|
|
||||||
doc.setFont('helvetica', 'normal');
|
|
||||||
|
|
||||||
let yPosition = 110;
|
|
||||||
|
|
||||||
// Document Information Section
|
// Document Information Section
|
||||||
doc.setFont('helvetica', 'bold');
|
page.drawText('Informations du Document', {
|
||||||
doc.text('Informations du Document', 20, yPosition);
|
x: 20,
|
||||||
yPosition += 10;
|
y: yPosition,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaBoldFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
yPosition -= 10;
|
||||||
|
|
||||||
doc.setFont('helvetica', 'normal');
|
page.drawText(`Identifiant du Document: ${certificateData.metadata.documentUid}`, {
|
||||||
doc.text(`Identifiant du Document: ${certificateData.metadata.documentUid}`, 20, yPosition);
|
x: 20,
|
||||||
yPosition += 7;
|
y: yPosition,
|
||||||
doc.text(`Type de Document: ${certificateData.metadata.documentType}`, 20, yPosition);
|
size: 12,
|
||||||
yPosition += 7;
|
font: helveticaFont,
|
||||||
doc.text(`Numéro de dossier: ${certificateData.folderUid}`, 20, yPosition);
|
color: rgb(0, 0, 0)
|
||||||
yPosition += 7;
|
});
|
||||||
doc.text(`Créé le: ${certificateData.metadata.createdAt.toLocaleDateString('fr-FR')}`, 20, yPosition);
|
yPosition -= 7;
|
||||||
yPosition += 7;
|
|
||||||
doc.text(`Nom du fichier: ${certificateData.metadata.fileName}`, 20, yPosition);
|
page.drawText(`Type de Document: ${certificateData.metadata.documentType}`, {
|
||||||
yPosition += 7;
|
x: 20,
|
||||||
doc.text(`ID de transaction: ${certificateData.metadata.commitmentId}`, 20, yPosition);
|
y: yPosition,
|
||||||
yPosition += 7;
|
size: 12,
|
||||||
doc.text(`Dernière modification: ${certificateData.metadata.updatedAt.toLocaleDateString('fr-FR')}`, 20, yPosition);
|
font: helveticaFont,
|
||||||
yPosition += 7;
|
color: rgb(0, 0, 0)
|
||||||
doc.text(`Statut: ${certificateData.metadata.isDeleted ? 'Supprimé' : 'Actif'}`, 20, yPosition);
|
});
|
||||||
yPosition += 15;
|
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
|
// Document Hash Section
|
||||||
doc.setFont('helvetica', 'bold');
|
page.drawText('Intégrité du Document', {
|
||||||
doc.text('Intégrité du Document', 20, yPosition);
|
x: 20,
|
||||||
yPosition += 10;
|
y: yPosition,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaBoldFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
yPosition -= 10;
|
||||||
|
|
||||||
doc.setFont('helvetica', 'normal');
|
page.drawText(`Hash SHA256 du Document:`, {
|
||||||
doc.text(`Hash SHA256 du Document:`, 20, yPosition);
|
x: 20,
|
||||||
yPosition += 7;
|
y: yPosition,
|
||||||
|
size: 12,
|
||||||
|
font: helveticaFont,
|
||||||
|
color: rgb(0, 0, 0)
|
||||||
|
});
|
||||||
|
yPosition -= 7;
|
||||||
|
|
||||||
// Split hash into multiple lines if needed
|
// Split hash into multiple lines if needed
|
||||||
const hash = certificateData.documentHash;
|
const hash = certificateData.documentHash;
|
||||||
const maxWidth = 170; // Available width for text
|
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) {
|
for (const line of hashLines) {
|
||||||
doc.text(line, 25, yPosition);
|
page.drawText(line, {
|
||||||
yPosition += 7;
|
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
|
// Footer
|
||||||
const pageCount = doc.getNumberOfPages();
|
const footerText1 = `Page 1 sur 1`;
|
||||||
for (let i = 1; i <= pageCount; i++) {
|
const footerText2 = `Certificat Notarial - Généré le ${new Date().toLocaleString('fr-FR')}`;
|
||||||
doc.setPage(i);
|
const footerWidth1 = helveticaObliqueFont.widthOfTextAtSize(footerText1, 10);
|
||||||
doc.setFontSize(10);
|
const footerWidth2 = helveticaObliqueFont.widthOfTextAtSize(footerText2, 10);
|
||||||
doc.setFont('helvetica', 'italic');
|
|
||||||
doc.text(`Page ${i} sur ${pageCount}`, 105, 280, { align: 'center' });
|
page.drawText(footerText1, {
|
||||||
doc.text(`Certificat Notarial - Généré le ${new Date().toLocaleString('fr-FR')}`, 105, 285, { align: 'center' });
|
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) {
|
} catch (error) {
|
||||||
console.error('Error generating notary certificate:', error);
|
console.error('Error generating notary certificate:', error);
|
||||||
throw new Error('Failed to generate notary certificate');
|
throw new Error('Failed to generate notary certificate');
|
||||||
@ -309,4 +601,141 @@ export default class PdfService {
|
|||||||
throw error;
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
211
src/front/Services/WatermarkService/index.ts
Normal file
211
src/front/Services/WatermarkService/index.ts
Normal 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
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user