Skip to content

Instantly share code, notes, and snippets.

@promto-c
Created April 5, 2024 15:51
Show Gist options
  • Save promto-c/26a42d8608936371f9e9540b6600542f to your computer and use it in GitHub Desktop.
Save promto-c/26a42d8608936371f9e9540b6600542f to your computer and use it in GitHub Desktop.
Python function to unlock a password-protected PDF using PyPDF2
import PyPDF2
def unlock_pdf(input_pdf_path, password, output_pdf_path):
"""Unlocks a password-protected PDF file and saves an unlocked version.
This function attempts to unlock a PDF file using the provided password. If successful,
it creates a new PDF file without the password protection. It handles both cases where
the PDF is encrypted and when it's not. In case of failure due to an incorrect password
or any other issue, it prints an error message.
Args:
input_pdf_path: A string representing the path to the locked PDF file.
password: A string representing the password for the PDF file.
output_pdf_path: A string representing the path where the unlocked PDF will be saved.
Returns:
None
"""
with open(input_pdf_path, 'rb') as input_file:
reader = PyPDF2.PdfReader(input_file)
if not reader.is_encrypted:
print("The PDF is not encrypted.")
return
if not reader.decrypt(password):
print("Failed to unlock the PDF. The password may be incorrect.")
writer = PyPDF2.PdfWriter()
for page in reader.pages:
writer.add_page(page)
with open(output_pdf_path, 'wb') as output_file:
writer.write(output_file)
print("PDF unlocked successfully.")
# Example usage
if __name__ == '__main__':
unlock_pdf('path/to/your/locked.pdf', 'your_password', 'path/to/your/unlocked.pdf')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment