Search code examples
pythonms-worddocxwin32comdoc

UnProtect DOC and DOCX using WIN32COM with Python


I´m trying to unprotect a word document file using win32com but the code below run without error and not unprotect.

I did some searches here and I have tried some variations with this code but no success.

My word document test was created with protection_type = 2 and the code below is recognizing ok I just need a way to unprotect with this code or another free code.

Appreciate any help !

import win32com.client

def protect_file(pFileName, pPassword):
    word = win32com.client.gencache.EnsureDispatch('Word.Application')    
    
    word.Visible = False

    doc = word.Documents.Open(pFileName, PasswordDocument=pPassword)
    
    doc.Protect(Type=2, NoReset=True, Password=pPassword)
    
    doc.Save()

    doc.Close()
    
    word.Quit()


def unprotect_file(pFileName, pPassword):
    
  word_app = win32com.client.gencache.EnsureDispatch('Word.Application')
  word_app.Visible = False

  try:
    
    doc = word_app.Documents.Open(pFileName, PasswordDocument=pPassword)

    protection_type = doc.ProtectionType

    if protection_type != -1:
      
      if protection_type == 2:
        
        print(f'Protection Type : {protection_type} -> wdAllowOnlyComments' )
      
      elif protection_type == 3:
        
        print(f'Protection Type : {protection_type} -> wdAllowOnlyRevisions' )
      
      elif protection_type == 4:
                
        print(f'Protection Type : {protection_type} -> wdAllowOnlyFormFields' )
      
      doc.Unprotect
      doc.Save()
      
      print(f'Document saved !')

    else:  
        print(f'{pFileName} inst protected !')

  except Exception as e:
    
    print(f'Error : {e}')

  finally:
    if doc:
      doc.Close(SaveChanges=True)
      word_app.Quit()

I tried to use import Comtypes with some variations with no success I tried to use chat gpt too with some variations with no success


Solution

  • Ok Guys ! Here´s the code below working ! I Hope that its usefull for someone

    import win32com.client
    
    # pip install pywin32
    
    def protect_file(pFileName, pPassword):
      word_app = win32com.client.gencache.EnsureDispatch('Word.Application')    
      
      doc = word_app.Documents.Open(pFileName, PasswordDocument=pPassword)
       
      if doc.ProtectionType == -1:
       
        doc.PrintPreview()
       
        doc.Protect(2, True, pPassword)
       
        doc.Save()
    
    
    def unprotect_file(pFileName, pPassword):
      word_app = win32com.client.gencache.EnsureDispatch('Word.Application')    
      
      doc = word_app.Documents.Open(pFileName, PasswordDocument=pPassword)
       
      if doc.ProtectionType != -1:
       
        doc.PrintPreview()
       
        doc.Unprotect(pPassword) 
       
        doc.Save()