diff --git a/.idea/workspace.xml b/.idea/workspace.xml
index f249b83..ebf63fa 100644
--- a/.idea/workspace.xml
+++ b/.idea/workspace.xml
@@ -4,8 +4,17 @@
-
+
+
+
+
+
+
+
+
+
+
@@ -311,11 +320,11 @@
+
-
@@ -406,22 +415,8 @@
-
-
-
- 1740884332734
-
-
-
- 1740884332735
-
-
-
- 1740884971377
-
-
-
- 1740884971378
+
+
@@ -799,7 +794,23 @@
1743647707334
-
+
+
+ 1743691399769
+
+
+
+ 1743691399769
+
+
+
+ 1743691471368
+
+
+
+ 1743691471368
+
+
@@ -846,8 +857,6 @@
-
-
@@ -871,7 +880,9 @@
-
+
+
+
diff --git a/src/lib/ghostscript/background-worker.js b/src/lib/ghostscript/background-worker.js
index 1bfe7c2..3bee269 100644
--- a/src/lib/ghostscript/background-worker.js
+++ b/src/lib/ghostscript/background-worker.js
@@ -1,10 +1,12 @@
+import { COMPRESS_ACTION, PROTECT_ACTION } from './worker-init';
+
function loadScript() {
import('./gs-worker.js');
}
var Module;
-function _GSPS2PDF(dataStruct, responseCallback) {
+function compressPdf(dataStruct, responseCallback) {
const compressionLevel = dataStruct.compressionLevel || 'medium';
// Set PDF settings based on compression level
@@ -44,7 +46,11 @@ function _GSPS2PDF(dataStruct, responseCallback) {
});
var blob = new Blob([uarray], { type: 'application/octet-stream' });
var pdfDataURL = self.URL.createObjectURL(blob);
- responseCallback({ pdfDataURL: pdfDataURL, url: dataStruct.url });
+ responseCallback({
+ pdfDataURL: pdfDataURL,
+ url: dataStruct.url,
+ type: COMPRESS_ACTION
+ });
}
],
arguments: [
@@ -76,6 +82,77 @@ function _GSPS2PDF(dataStruct, responseCallback) {
xhr.send();
}
+function protectPdf(dataStruct, responseCallback) {
+ const password = dataStruct.password || '';
+
+ // Validate password
+ if (!password) {
+ responseCallback({
+ error: 'Password is required for encryption',
+ url: dataStruct.url
+ });
+ return;
+ }
+ var xhr = new XMLHttpRequest();
+ xhr.open('GET', dataStruct.psDataURL);
+ xhr.responseType = 'arraybuffer';
+ xhr.onload = function () {
+ console.log('onload');
+ // release the URL
+ self.URL.revokeObjectURL(dataStruct.psDataURL);
+ //set up EMScripten environment
+ Module = {
+ preRun: [
+ function () {
+ self.Module.FS.writeFile('input.pdf', new Uint8Array(xhr.response));
+ }
+ ],
+ postRun: [
+ function () {
+ var uarray = self.Module.FS.readFile('output.pdf', {
+ encoding: 'binary'
+ });
+ var blob = new Blob([uarray], { type: 'application/octet-stream' });
+ var pdfDataURL = self.URL.createObjectURL(blob);
+ responseCallback({
+ pdfDataURL: pdfDataURL,
+ url: dataStruct.url,
+ type: PROTECT_ACTION
+ });
+ }
+ ],
+ arguments: [
+ '-sDEVICE=pdfwrite',
+ '-dCompatibilityLevel=1.4',
+ `-sOwnerPassword=${password}`,
+ `-sUserPassword=${password}`,
+ // Permissions (prevent copying/printing/etc)
+ '-dEncryptionPermissions=-4',
+ '-DNOPAUSE',
+ '-dQUIET',
+ '-dBATCH',
+ '-sOutputFile=output.pdf',
+ 'input.pdf'
+ ],
+ print: function (text) {},
+ printErr: function (text) {},
+ totalDependencies: 0,
+ noExitRuntime: 1
+ };
+ // Module.setStatus("Loading Ghostscript...");
+ if (!self.Module) {
+ self.Module = Module;
+ loadScript();
+ } else {
+ self.Module['calledRun'] = false;
+ self.Module['postRun'] = Module.postRun;
+ self.Module['preRun'] = Module.preRun;
+ self.Module.callMain();
+ }
+ };
+ xhr.send();
+}
+
self.addEventListener('message', function ({ data: e }) {
console.log('message', e);
// e.data contains the message sent to the worker.
@@ -83,7 +160,14 @@ self.addEventListener('message', function ({ data: e }) {
return;
}
console.log('Message received from main script', e.data);
- _GSPS2PDF(e.data, ({ pdfDataURL }) => self.postMessage(pdfDataURL));
+ const responseCallback = ({ pdfDataURL, type }) => {
+ self.postMessage(pdfDataURL);
+ };
+ if (e.data.type === COMPRESS_ACTION) {
+ compressPdf(e.data, responseCallback);
+ } else if (e.data.type === PROTECT_ACTION) {
+ protectPdf(e.data, responseCallback);
+ }
});
console.log('Worker ready');
diff --git a/src/lib/ghostscript/worker-init.js b/src/lib/ghostscript/worker-init.js
deleted file mode 100644
index e3fc39f..0000000
--- a/src/lib/ghostscript/worker-init.js
+++ /dev/null
@@ -1,15 +0,0 @@
-export async function compressWithGhostScript(dataStruct) {
- const worker = new Worker(
- new URL('./background-worker.js', import.meta.url),
- { type: 'module' }
- );
- worker.postMessage({ data: dataStruct, target: 'wasm' });
- return new Promise((resolve, reject) => {
- const listener = (e) => {
- resolve(e.data);
- worker.removeEventListener('message', listener);
- setTimeout(() => worker.terminate(), 0);
- };
- worker.addEventListener('message', listener);
- });
-}
diff --git a/src/lib/ghostscript/worker-init.ts b/src/lib/ghostscript/worker-init.ts
new file mode 100644
index 0000000..9fad88f
--- /dev/null
+++ b/src/lib/ghostscript/worker-init.ts
@@ -0,0 +1,41 @@
+export const COMPRESS_ACTION = 'compress-pdf';
+export const PROTECT_ACTION = 'protect-pdf';
+
+export async function compressWithGhostScript(dataStruct: {
+ psDataURL: string;
+}): Promise {
+ const worker = getWorker();
+ worker.postMessage({
+ data: { ...dataStruct, type: COMPRESS_ACTION },
+ target: 'wasm'
+ });
+ return getListener(worker);
+}
+
+export async function protectWithGhostScript(dataStruct: {
+ psDataURL: string;
+}): Promise {
+ const worker = getWorker();
+ worker.postMessage({
+ data: { ...dataStruct, type: PROTECT_ACTION },
+ target: 'wasm'
+ });
+ return getListener(worker);
+}
+
+const getListener = (worker: Worker): Promise => {
+ return new Promise((resolve, reject) => {
+ const listener = (e: MessageEvent) => {
+ resolve(e.data);
+ worker.removeEventListener('message', listener);
+ setTimeout(() => worker.terminate(), 0);
+ };
+ worker.addEventListener('message', listener);
+ });
+};
+
+const getWorker = () => {
+ return new Worker(new URL('./background-worker.js', import.meta.url), {
+ type: 'module'
+ });
+};
diff --git a/src/pages/tools/pdf/compress-pdf/service.ts b/src/pages/tools/pdf/compress-pdf/service.ts
index 2aa3c28..29b5ab4 100644
--- a/src/pages/tools/pdf/compress-pdf/service.ts
+++ b/src/pages/tools/pdf/compress-pdf/service.ts
@@ -1,5 +1,6 @@
import { InitialValuesType } from './types';
import { compressWithGhostScript } from '../../../../lib/ghostscript/worker-init';
+import { loadPDFData } from '../utils';
/**
* Compresses a PDF file using either Ghostscript WASM (preferred)
@@ -25,20 +26,3 @@ export async function compressPdf(
const compressedFileUrl: string = await compressWithGhostScript(dataObject);
return await loadPDFData(compressedFileUrl, pdfFile.name);
}
-
-function loadPDFData(url: string, filename: string): Promise {
- return new Promise((resolve) => {
- const xhr = new XMLHttpRequest();
- xhr.open('GET', url);
- xhr.responseType = 'arraybuffer';
- xhr.onload = function () {
- window.URL.revokeObjectURL(url);
- const blob = new Blob([xhr.response], { type: 'application/pdf' });
- const newFile = new File([blob], filename, {
- type: 'application/pdf'
- });
- resolve(newFile);
- };
- xhr.send();
- });
-}
diff --git a/src/pages/tools/pdf/index.ts b/src/pages/tools/pdf/index.ts
index a1e8475..4b74428 100644
--- a/src/pages/tools/pdf/index.ts
+++ b/src/pages/tools/pdf/index.ts
@@ -1,10 +1,12 @@
import { tool as pdfRotatePdf } from './rotate-pdf/meta';
import { meta as splitPdfMeta } from './split-pdf/meta';
import { tool as compressPdfTool } from './compress-pdf/meta';
+import { tool as protectPdfTool } from './protect-pdf/meta';
import { DefinedTool } from '@tools/defineTool';
export const pdfTools: DefinedTool[] = [
splitPdfMeta,
pdfRotatePdf,
- compressPdfTool
+ compressPdfTool,
+ protectPdfTool
];
diff --git a/src/pages/tools/pdf/protect-pdf/index.tsx b/src/pages/tools/pdf/protect-pdf/index.tsx
new file mode 100644
index 0000000..7692695
--- /dev/null
+++ b/src/pages/tools/pdf/protect-pdf/index.tsx
@@ -0,0 +1,110 @@
+import { Box } from '@mui/material';
+import React, { useContext, useState } from 'react';
+import ToolContent from '@components/ToolContent';
+import { ToolComponentProps } from '@tools/defineTool';
+import ToolPdfInput from '@components/input/ToolPdfInput';
+import ToolFileResult from '@components/result/ToolFileResult';
+import { InitialValuesType } from './types';
+import { protectPdf } from './service';
+import TextFieldWithDesc from '@components/options/TextFieldWithDesc';
+import { CustomSnackBarContext } from '../../../../contexts/CustomSnackBarContext';
+
+const initialValues: InitialValuesType = {
+ password: '',
+ confirmPassword: ''
+};
+
+export default function ProtectPdf({
+ title,
+ longDescription
+}: ToolComponentProps) {
+ const [input, setInput] = useState(null);
+ const [result, setResult] = useState(null);
+ const [isProcessing, setIsProcessing] = useState(false);
+ const { showSnackBar } = useContext(CustomSnackBarContext);
+
+ const compute = async (values: InitialValuesType, input: File | null) => {
+ if (!input) return;
+
+ try {
+ // Validate passwords match
+ if (values.password !== values.confirmPassword) {
+ showSnackBar('Passwords do not match', 'error');
+ return;
+ }
+
+ // Validate password is not empty
+ if (!values.password) {
+ showSnackBar('Password cannot be empty', 'error');
+ return;
+ }
+
+ setIsProcessing(true);
+ const protectedPdf = await protectPdf(input, values);
+ setResult(protectedPdf);
+ } catch (error) {
+ console.error('Error protecting PDF:', error);
+ showSnackBar(
+ `Failed to protect PDF: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ 'error'
+ );
+ setResult(null);
+ } finally {
+ setIsProcessing(false);
+ }
+ };
+
+ return (
+
+ }
+ resultComponent={
+
+ }
+ getGroups={({ values, updateField }) => [
+ {
+ title: 'Password Settings',
+ component: (
+
+ updateField('password', value)}
+ />
+ updateField('confirmPassword', value)}
+ />
+
+ )
+ }
+ ]}
+ />
+ );
+}
diff --git a/src/pages/tools/pdf/protect-pdf/meta.ts b/src/pages/tools/pdf/protect-pdf/meta.ts
new file mode 100644
index 0000000..51ecd53
--- /dev/null
+++ b/src/pages/tools/pdf/protect-pdf/meta.ts
@@ -0,0 +1,27 @@
+import { defineTool } from '@tools/defineTool';
+import { lazy } from 'react';
+
+export const tool = defineTool('pdf', {
+ name: 'Protect PDF',
+ path: 'protect-pdf',
+ icon: 'material-symbols:lock',
+ description:
+ 'Add password protection to your PDF files securely in your browser',
+ shortDescription: 'Password protect PDF files securely',
+ keywords: [
+ 'pdf',
+ 'protect',
+ 'password',
+ 'secure',
+ 'encrypt',
+ 'lock',
+ 'private',
+ 'confidential',
+ 'security',
+ 'browser',
+ 'encryption'
+ ],
+ longDescription:
+ 'Add password protection to your PDF files securely in your browser. Your files never leave your device, ensuring complete privacy while securing your documents with password encryption. Perfect for protecting sensitive information, confidential documents, or personal data.',
+ component: lazy(() => import('./index'))
+});
diff --git a/src/pages/tools/pdf/protect-pdf/service.ts b/src/pages/tools/pdf/protect-pdf/service.ts
new file mode 100644
index 0000000..6619a50
--- /dev/null
+++ b/src/pages/tools/pdf/protect-pdf/service.ts
@@ -0,0 +1,45 @@
+import { PDFDocument } from 'pdf-lib';
+import { InitialValuesType } from './types';
+import {
+ compressWithGhostScript,
+ protectWithGhostScript
+} from '../../../../lib/ghostscript/worker-init';
+import { loadPDFData } from '../utils';
+
+/**
+ * Protects a PDF file with a password
+ *
+ * @param pdfFile - The PDF file to protect
+ * @param options - Protection options including password and protection type
+ * @returns A Promise that resolves to a password-protected PDF File
+ */
+export async function protectPdf(
+ pdfFile: File,
+ options: InitialValuesType
+): Promise {
+ // Check if file is a PDF
+ if (pdfFile.type !== 'application/pdf') {
+ throw new Error('The provided file is not a PDF');
+ }
+
+ // Check if passwords match
+ if (options.password !== options.confirmPassword) {
+ throw new Error('Passwords do not match');
+ }
+
+ // Check if password is empty
+ if (!options.password) {
+ throw new Error('Password cannot be empty');
+ }
+
+ const dataObject = {
+ psDataURL: URL.createObjectURL(pdfFile),
+ password: options.password
+ };
+ const protectedFileUrl: string = await protectWithGhostScript(dataObject);
+ console.log('protected', protectedFileUrl);
+ return await loadPDFData(
+ protectedFileUrl,
+ pdfFile.name.replace('.pdf', '-protected.pdf')
+ );
+}
diff --git a/src/pages/tools/pdf/protect-pdf/types.ts b/src/pages/tools/pdf/protect-pdf/types.ts
new file mode 100644
index 0000000..a029070
--- /dev/null
+++ b/src/pages/tools/pdf/protect-pdf/types.ts
@@ -0,0 +1,6 @@
+export type ProtectionType = 'owner' | 'user';
+
+export type InitialValuesType = {
+ password: string;
+ confirmPassword: string;
+};
diff --git a/src/pages/tools/pdf/utils.ts b/src/pages/tools/pdf/utils.ts
new file mode 100644
index 0000000..98fe7e5
--- /dev/null
+++ b/src/pages/tools/pdf/utils.ts
@@ -0,0 +1,16 @@
+export function loadPDFData(url: string, filename: string): Promise {
+ return new Promise((resolve) => {
+ const xhr = new XMLHttpRequest();
+ xhr.open('GET', url);
+ xhr.responseType = 'arraybuffer';
+ xhr.onload = function () {
+ window.URL.revokeObjectURL(url);
+ const blob = new Blob([xhr.response], { type: 'application/pdf' });
+ const newFile = new File([blob], filename, {
+ type: 'application/pdf'
+ });
+ resolve(newFile);
+ };
+ xhr.send();
+ });
+}