2025-10-12 11:55:45 +05:30
|
|
|
import { showLoader, hideLoader, showAlert } from '../ui.js';
|
|
|
|
|
import { downloadFile } from '../utils/helpers.js';
|
|
|
|
|
import { state } from '../state.js';
|
|
|
|
|
|
2026-03-31 17:59:49 +05:30
|
|
|
import type { RedactionRect } from '@/types';
|
|
|
|
|
|
2025-10-12 11:55:45 +05:30
|
|
|
// @ts-expect-error TS(2339) FIXME: Property 'PDFLib' does not exist on type 'Window &... Remove this comment to see the full error message
|
|
|
|
|
const { rgb } = window.PDFLib;
|
|
|
|
|
|
2026-03-31 17:59:49 +05:30
|
|
|
export async function redact(redactions: RedactionRect[], canvasScale: number) {
|
2025-10-17 11:37:32 +05:30
|
|
|
showLoader('Applying redactions...');
|
|
|
|
|
try {
|
|
|
|
|
const pdfPages = state.pdfDoc.getPages();
|
|
|
|
|
const conversionScale = 1 / canvasScale;
|
2025-10-12 11:55:45 +05:30
|
|
|
|
2026-03-31 17:59:49 +05:30
|
|
|
redactions.forEach((r: RedactionRect) => {
|
2025-10-17 11:37:32 +05:30
|
|
|
const page = pdfPages[r.pageIndex];
|
|
|
|
|
const { height: pageHeight } = page.getSize();
|
2025-10-12 11:55:45 +05:30
|
|
|
|
2025-10-17 11:37:32 +05:30
|
|
|
// Convert canvas coordinates back to PDF coordinates
|
|
|
|
|
const pdfX = r.canvasX * conversionScale;
|
|
|
|
|
const pdfWidth = r.canvasWidth * conversionScale;
|
|
|
|
|
const pdfHeight = r.canvasHeight * conversionScale;
|
|
|
|
|
const pdfY = pageHeight - r.canvasY * conversionScale - pdfHeight;
|
2025-10-12 11:55:45 +05:30
|
|
|
|
2025-10-17 11:37:32 +05:30
|
|
|
page.drawRectangle({
|
|
|
|
|
x: pdfX,
|
|
|
|
|
y: pdfY,
|
|
|
|
|
width: pdfWidth,
|
|
|
|
|
height: pdfHeight,
|
|
|
|
|
color: rgb(0, 0, 0),
|
|
|
|
|
});
|
|
|
|
|
});
|
2025-10-12 11:55:45 +05:30
|
|
|
|
2025-10-17 11:37:32 +05:30
|
|
|
const redactedBytes = await state.pdfDoc.save();
|
|
|
|
|
downloadFile(
|
2026-03-31 17:59:49 +05:30
|
|
|
new Blob([new Uint8Array(redactedBytes)], { type: 'application/pdf' }),
|
2025-10-17 11:37:32 +05:30
|
|
|
'redacted.pdf'
|
|
|
|
|
);
|
|
|
|
|
} catch (e) {
|
|
|
|
|
console.error(e);
|
|
|
|
|
showAlert('Error', 'Failed to apply redactions.');
|
|
|
|
|
} finally {
|
|
|
|
|
hideLoader();
|
|
|
|
|
}
|
|
|
|
|
}
|