Repository navigation
Replies: 1 comment
|
Hi @joeuy-dev, yes, you can prompt the user for a password to open an encrypted PDF, and then export/save an unencrypted copy. However, how you achieve this depends on whether you are using PDF.js (a reader engine) or a full PDF manipulation library (like pdf-lib or pdfcpu).
Opening: PDF.js natively handles password-protected files via the onPassword callback on getDocument(). Removing the password: PDF.js cannot directly re-serialize/save the PDF binary without encryption. If you need to output an unencrypted PDF file (e.g., for downloading), you must use a PDF manipulation library alongside PDF.js or directly in a backend node service / full-stack JS environment.
Step 1: Open and Prompt for Password with PDF.js import * as pdfjsLib from 'pdfjs-dist';
async function loadProtectedPDF(pdfArrayBuffer) {
const loadingTask = pdfjsLib.getDocument({
data: pdfArrayBuffer,
// Provide password or handle onPassword event callback
password: 'user_entered_password'
});
loadingTask.onPassword = (updatePassword, reason) => {
// Prompt the user in UI, then call:
const userEnteredPassword = prompt('Please enter the PDF password:');
updatePassword(userEnteredPassword);
};
const pdfDoc = await loadingTask.promise;
console.log('PDF unlocked and loaded successfully! Total pages:', pdfDoc.numPages);
}Step 2: Remove Password and Save Unlocked Copy using pdf-lib import { PDFDocument } from 'pdf-lib';
async function removePasswordAndDownload(pdfArrayBuffer, userPassword) {
// Load the encrypted PDF using the validated password
const pdfDoc = await PDFDocument.load(pdfArrayBuffer, {
password: userPassword
});
// Exporting / saving automatically strips the password protection
const unlockedPdfBytes = await pdfDoc.save();
// Trigger browser download of the unlocked file
const blob = new Blob([unlockedPdfBytes], { type: 'application/pdf' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'unlocked_document.pdf';
link.click();
}
Node.js: You can use pdf-lib or qpdf wrappers. QPDF (CLI / Native Tool): qpdf --password=USER_PASSWORD --decrypt input_protected.pdf output_unlocked.pdf
Python (pypdf / pikepdf):import pikepdf
# Opens encrypted PDF with password and saves an unencrypted copy
with pikepdf.open('input.pdf', password='user_password') as pdf:
pdf.save('unlocked.pdf')Awesome! If this solution solves the issue for you, feel free to hit "Mark as answer" on the thread so others facing the same issue can find it easily! 🚀 |
Uh oh!
There was an error while loading. Please reload this page.
As titled
All reactions