33
loading...
This website collects cookies to deliver better user experience
PyPDF2
to encrypt and decrypt pdf files hence hence enhancing security of contained information.PyPDF2
is not an in-built library therefore it needs to be installed before use by:pip3 install PyPDF2
# Import the required module and sub-modules
from PyPDF2 import PdfFileWriter
from PyPDF2 import PdfFileReader
# Create a PdfFileWriter object
result = PdfFileWriter()
# Open the pdf file to encrypt
file = PdfFileReader('Magazine.pdf')
# Retrieve the number of pages to iterate in the original document
length = file.numPages
# Iterates through every page and adds it to the new file (a copy of the original)
for i in range(length):
pages = file.getPage(i)
result.addPage(pages)
# Creates a variable password.
password = 'pam&Lab890'
# Encrypt the file using the created password
result.encrypt(password)
# Open a new file 'Magazines.pdf' and write the encrypted pdf file
with open('Magazines.pdf','wb') as f:
result.write(f)
# Import the required module and sub-modules
from PyPDF2 import PdfFileWriter
from PyPDF2 import PdfFileReader
# Create a PdfFileWriter object
result = PdfFileWriter()
# Open the password - secured pdf file to decrypt
file = PdfFileReader('Magazines.pdf')
# Creates a variable password.
password = 'pam&Lab890'
# First, check if the file is encrypted then proceed if encrypted
if file.isEncrypted:
# Decrypt the file using the givenpassword
file.decrypt(password)
# Iterates through every page and adds it to the new file
for i in range(31):
pages = file.getPage(i)
result.addPage(pages)
# Open a new file 'Magazines1.pdf' and write the encrypted
pdf file
with open('Magazines1.pdf','wb') as f:
result.write(f)
print('File decrypted successfully')
else:
print('File is not encrypted')