Advertisement
Guest User

Untitled

a guest
Aug 21st, 2019
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. import os # a library to manage copying and pasting
  2. import pikepdf # A well written library to work with python
  3. from pikepdf import Pdf
  4.  
  5. password = 'some password'
  6. path = 'C:/Users/asad/desktop/pdfs'
  7.  
  8. def protect(file, password=password):
  9. '''
  10. This function takes a file as an input and creates another file in the same destination
  11. This file is encrypted with the password defined earlier
  12. '''
  13. pdf = Pdf.open(file)
  14. pdf.save(os.path.splitext(file)[0] + '_encrypted.pdf',
  15. encryption=pikepdf.Encryption(owner=password, user=password, R=4))
  16. # you can change the 4 to 6 for 256 aes encryption but that file won't open on Acrobat versions lower than 10.0
  17. pdf.close()
  18. return
  19.  
  20. def remove_originals(file):
  21. '''
  22. This will remove the files that don't end with _encrypted.pdf in their names
  23. '''
  24. if file.endswith(('.pdf', '.PDF')):
  25. if not file.endswith('_encrypted.pdf'):
  26. os.remove(file)
  27.  
  28. #protecting
  29. for folder, subfolders, files in os.walk(path):
  30. for file in files:
  31. if file.endswith(('.pdf', '.PDF')):
  32. protect(os.path.join(folder, file))
  33.  
  34. #removing originals
  35. for folder, subfolders, files in os.walk(path):
  36. for file in files:
  37. if file.endswith(('.pdf', '.PDF')):
  38. remove_originals(os.path.join(folder, file))
  39.  
  40. #renaming the encrypted files to match the original filenames
  41. for folder, subfolders, files in os.walk(path):
  42. for file in files:
  43. if file.endswith(('.pdf', '.PDF')):
  44. os.rename(os.path.join(folder, file), os.path.join(folder, file.replace('_encrypted', '')))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement