""" Removes PDF password protection: both an open/user password (if supplied and correct) and any owner-only permission restrictions (no printing, no copying, etc), which QPDF can always strip without needing the owner password - only the user/open password, when one is set, actually gates access and must be supplied by the caller. Flask-free per this repo's tool convention (see CLAUDE.md). """ import pikepdf class WrongPasswordError(Exception): """Raised when the PDF has an open password and none/the wrong one was supplied.""" def unlock_pdf(input_path, output_path, password=None): """ Decrypt the PDF at input_path and write an unprotected copy to output_path. Returns True if the source PDF was actually protected (open password and/or owner restrictions), False if it was already a plain, unprotected PDF - so the caller can give an accurate status message either way. """ try: pdf = pikepdf.open(input_path, password=password or "") except pikepdf.PasswordError: raise WrongPasswordError( "Incorrect password for this PDF." if password else "This PDF requires a password to open - enter it and try again." ) was_protected = pdf.is_encrypted pdf.save(output_path, encryption=False) pdf.close() return was_protected