Skip to content

Instantly share code, notes, and snippets.

@rayyildiz
Created October 18, 2024 16:19
Show Gist options
  • Select an option

  • Save rayyildiz/3fe06821f742a917796650d9ad38f1f1 to your computer and use it in GitHub Desktop.

Select an option

Save rayyildiz/3fe06821f742a917796650d9ad38f1f1 to your computer and use it in GitHub Desktop.
from typing import Optional
import aspose.words as aw
file = 'file.docx' # file
def ask_password() -> str:
"""
Ask the user to enter a password through a simple dialog window.
:return: The password entered by the user as a string.
"""
import tkinter.simpledialog
pwd = tkinter.simpledialog.askstring("Password", "Enter password:", show="*")
return pwd
def open_file(file, pwd: Optional[str] = None):
"""
:param file: Path to the file that needs to be opened.
:param pwd: Optional password for locked documents.
:return: None
"""
try:
if pwd is not None:
doc = aw.Document(file, aw.loading.LoadOptions(pwd))
doc.unprotect()
else:
doc = aw.Document(file)
except Exception as e:
print("Exception while opening file", e)
def check_protected(file):
"""
:param file: The file path or file object to be checked.
:return: None. Prints whether the file is protected and attempts to open it.
"""
try:
info = aw.FileFormatUtil.detect_file_format(file)
if info.is_encrypted:
print("The file is protected")
pwd = ask_password()
open_file(file, pwd)
else:
print("The file is not protected")
open_file(file, None)
except Exception as e:
print("Exception in encrypted file", e)
if __name__ == "__main__":
check_protected(file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment