Ben Traje
← Back to python

Remove Passwords from PDF using Python

20 Feb 26 (Today)

No, this does not magically decrypt your encrypted PDF. You still need password to access it. I usually remove passwords just for archival purposes and easy future viewing.

Not highly recommended for super sensitive document. Unlock at your own risk.

Requirements: pip install pypdf

from pypdf import PdfReader, PdfWriter
from pypdf.errors import PdfReadError
import sys

# ---- Edit these variables ----
input_path = ""   # path to the source PDF (possibly encrypted)
output_path = ""  # path where the unencrypted PDF will be saved
password = ""     # set to None or "" if you want to try an empty password
# ------------------------------

def remove_password(input_path: str, output_path: str, password):
    try:
        reader = PdfReader(input_path)
    except FileNotFoundError:
        print(f"Input file not found: {input_path}", file=sys.stderr)
        return False
    except PdfReadError as e:
        print(f"Error reading PDF: {e}", file=sys.stderr)
        return False

    if reader.is_encrypted:
        # Try provided password (if not None), then empty string
        tried = []
        success = False
        if password is not None:
            tried.append(password)
            try:
                success = bool(reader.decrypt(password))
            except Exception:
                success = False
        if not success:
            tried.append("")
            try:
                success = bool(reader.decrypt(""))
            except Exception:
                success = False

        if not success:
            print("Failed to decrypt PDF. Tried passwords:", tried, file=sys.stderr)
            print("Make sure you set the correct password in the script.", file=sys.stderr)
            return False
    else:
        print("PDF is not encrypted — copying as-is.")

    writer = PdfWriter()
    for page in reader.pages:
        writer.add_page(page)

    try:
        with open(output_path, "wb") as f_out:
            writer.write(f_out)
    except Exception as e:
        print(f"Failed to write output PDF: {e}", file=sys.stderr)
        return False

    print(f"Saved unencrypted PDF to: {output_path}")
    return True

if __name__ == "__main__":
    ok = remove_password(input_path, output_path, password)
    if not ok:
        sys.exit(1)