import pathlib from pypdf import PdfReader, PdfWriter def unlock_pdfs(): # 讓用戶輸入密碼 (執行時會暫停並詢問) password = input("請輸入要解除 PDF 的密碼: ") print("-" * 30) # 掃描當前資料夾底下所有的 .pdf 檔案 for file_path in pathlib.Path(".").glob("*.pdf"): # 避免重複處理已經解密過的檔案 if file_path.name.startswith("已解鎖_"): continue try: reader = PdfReader(file_path) # 檢查檔案是否有上鎖 if reader.is_encrypted: # 嘗試使用提供的密碼解密 # pypdf 的 decrypt 支援密文解鎖,解鎖成功會回傳整數 (通常是 1 或 2),失敗回傳 0 if reader.decrypt(password): writer = PdfWriter() # 將解密後的每一頁複製到新的畫布上 for page in reader.pages: writer.add_page(page) # 儲存成全新的、沒有密碼的檔案 new_name = f"已解鎖_{file_path.name}" with open(new_name, "wb") as output_file: writer.write(output_file) print(f"✅ 成功解鎖: {file_path.name} -> {new_name}") else: print(f"❌ 密碼錯誤: {file_path.name}") else: print(f"⚠️ 無需解鎖 (原本就沒上鎖): {file_path.name}") except Exception as e: print(f"⚠️ 處理 {file_path.name} 時發生錯誤: {e}") if __name__ == "__main__": unlock_pdfs() print("-" * 30) input("處理完畢!請按 Enter 鍵結束...")