mirror of
https://github.com/arsvendg/Stirling-PDF.git
synced 2026-07-16 11:23:10 +02:00
Feature/v2/improve sign (#4627)
# Description of Changes <!-- Please provide a summary of the changes, including: - What was changed - Why the change was made - Any challenges encountered Closes #(issue_number) --> --- ## Checklist ### General - [ ] I have read the [Contribution Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md) - [ ] I have read the [Stirling-PDF Developer Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md) (if applicable) - [ ] I have read the [How to add new languages to Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md) (if applicable) - [ ] I have performed a self-review of my own code - [ ] My changes generate no new warnings ### Documentation - [ ] I have updated relevant docs on [Stirling-PDF's doc repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/) (if functionality has heavily changed) - [ ] I have read the section [Add New Translation Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags) (for new translation tags only) ### UI Changes (if applicable) - [ ] Screenshots or videos demonstrating the UI changes are attached (e.g., as comments or direct attachments in the PR) ### Testing (if applicable) - [ ] I have tested my changes locally. Refer to the [Testing Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md#6-testing) for more details. --------- Co-authored-by: Copilot <[email protected]> Co-authored-by: James Brunton <[email protected]> Co-authored-by: Claude <[email protected]>
This commit is contained in:
co-authored by
Copilot
James Brunton
Claude
parent
2158ee4db6
commit
b695e3900e
@@ -1,7 +1,7 @@
|
||||
import { PDFDocument, rgb } from 'pdf-lib';
|
||||
import { generateThumbnailWithMetadata } from './thumbnailUtils';
|
||||
import { createProcessedFile } from '../contexts/file/fileActions';
|
||||
import { createNewStirlingFileStub, createStirlingFile, StirlingFile, FileId, StirlingFileStub } from '../types/fileContext';
|
||||
import { createProcessedFile, createChildStub } from '../contexts/file/fileActions';
|
||||
import { createStirlingFile, StirlingFile, FileId, StirlingFileStub } from '../types/fileContext';
|
||||
import type { SignatureAPI } from '../components/viewer/SignatureAPIBridge';
|
||||
|
||||
interface MinimalFileContextSelectors {
|
||||
@@ -17,13 +17,18 @@ interface SignatureFlatteningOptions {
|
||||
saveAsCopy: () => Promise<ArrayBuffer | null>;
|
||||
};
|
||||
selectors: MinimalFileContextSelectors;
|
||||
consumeFiles: (inputFileIds: FileId[], outputStirlingFiles: StirlingFile[], outputStirlingFileStubs: StirlingFileStub[]) => Promise<FileId[]>;
|
||||
originalFile?: StirlingFile;
|
||||
getScrollState: () => { currentPage: number; totalPages: number };
|
||||
}
|
||||
|
||||
export async function flattenSignatures(options: SignatureFlatteningOptions): Promise<boolean> {
|
||||
const { signatureApiRef, getImageData, exportActions, selectors, consumeFiles, originalFile, getScrollState } = options;
|
||||
export interface SignatureFlatteningResult {
|
||||
inputFileIds: FileId[];
|
||||
outputStirlingFile: StirlingFile;
|
||||
outputStub: StirlingFileStub;
|
||||
}
|
||||
|
||||
export async function flattenSignatures(options: SignatureFlatteningOptions): Promise<SignatureFlatteningResult | null> {
|
||||
const { signatureApiRef, getImageData, exportActions, selectors, originalFile, getScrollState } = options;
|
||||
|
||||
try {
|
||||
// Step 1: Extract all annotations from EmbedPDF before export
|
||||
@@ -66,8 +71,6 @@ export async function flattenSignatures(options: SignatureFlatteningOptions): Pr
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`Total annotations found: ${allAnnotations.reduce((sum, page) => sum + page.annotations.length, 0)}`);
|
||||
|
||||
// Step 2: Delete ONLY session annotations from EmbedPDF before export (they'll be rendered manually)
|
||||
// Leave old annotations alone - they will remain as annotations in the PDF
|
||||
if (allAnnotations.length > 0 && signatureApiRef?.current) {
|
||||
@@ -85,7 +88,7 @@ export async function flattenSignatures(options: SignatureFlatteningOptions): Pr
|
||||
// Step 3: Use EmbedPDF's saveAsCopy to get the base PDF (now without annotations)
|
||||
if (!exportActions) {
|
||||
console.error('No export actions available');
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
const pdfArrayBuffer = await exportActions.saveAsCopy();
|
||||
|
||||
@@ -111,7 +114,7 @@ export async function flattenSignatures(options: SignatureFlatteningOptions): Pr
|
||||
|
||||
if (!currentFile) {
|
||||
console.error('No file available to replace');
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
|
||||
let signedFile = new File([blob], currentFile.name, { type: 'application/pdf' });
|
||||
@@ -119,7 +122,6 @@ export async function flattenSignatures(options: SignatureFlatteningOptions): Pr
|
||||
// Step 4: Manually render extracted annotations onto the PDF using PDF-lib
|
||||
if (allAnnotations.length > 0) {
|
||||
try {
|
||||
console.log('Manually rendering annotations onto PDF...');
|
||||
const pdfArrayBufferForFlattening = await signedFile.arrayBuffer();
|
||||
|
||||
// Try different loading options to handle problematic PDFs
|
||||
@@ -150,7 +152,6 @@ export async function flattenSignatures(options: SignatureFlatteningOptions): Pr
|
||||
|
||||
const pages = pdfDoc.getPages();
|
||||
|
||||
|
||||
for (const pageData of allAnnotations) {
|
||||
const { pageIndex, annotations } = pageData;
|
||||
|
||||
@@ -189,6 +190,7 @@ export async function flattenSignatures(options: SignatureFlatteningOptions): Pr
|
||||
|
||||
if (imageDataUrl && typeof imageDataUrl === 'string' && imageDataUrl.startsWith('data:image')) {
|
||||
try {
|
||||
|
||||
// Convert data URL to bytes
|
||||
const base64Data = imageDataUrl.split(',')[1];
|
||||
const imageBytes = Uint8Array.from(atob(base64Data), c => c.charCodeAt(0));
|
||||
@@ -215,6 +217,7 @@ export async function flattenSignatures(options: SignatureFlatteningOptions): Pr
|
||||
console.error('Failed to render image annotation:', imageError);
|
||||
}
|
||||
} else if (annotation.content || annotation.text) {
|
||||
console.warn('Rendering text annotation instead');
|
||||
// Handle text annotations
|
||||
page.drawText(annotation.content || annotation.text, {
|
||||
x: pdfX,
|
||||
@@ -287,23 +290,30 @@ export async function flattenSignatures(options: SignatureFlatteningOptions): Pr
|
||||
const record = selectors.getStirlingFileStub(currentFile.fileId);
|
||||
if (!record) {
|
||||
console.error('No file record found for:', currentFile.fileId);
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
|
||||
// Create output stub and file
|
||||
const outputStub = createNewStirlingFileStub(signedFile, undefined, thumbnailResult.thumbnail, processedFileMetadata);
|
||||
// Create output stub and file as a child of the original (increments version)
|
||||
const outputStub = createChildStub(
|
||||
record,
|
||||
{ toolId: 'sign', timestamp: Date.now() },
|
||||
signedFile,
|
||||
thumbnailResult.thumbnail,
|
||||
processedFileMetadata
|
||||
);
|
||||
const outputStirlingFile = createStirlingFile(signedFile, outputStub.id);
|
||||
|
||||
// Replace the original file with the signed version
|
||||
await consumeFiles(inputFileIds, [outputStirlingFile], [outputStub]);
|
||||
|
||||
console.log('✓ Signature flattening completed successfully');
|
||||
return true;
|
||||
// Return the flattened file data for consumption by caller
|
||||
return {
|
||||
inputFileIds,
|
||||
outputStirlingFile,
|
||||
outputStub
|
||||
};
|
||||
}
|
||||
|
||||
return false;
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error('Error flattening signatures:', error);
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user