#第十三章 PDF偏执狂
#①使用os.work()函数遍历文件夹下所有pdf文件,存储在fileList[]中
#②判断这些pdf是否已经加密,如果没有是,顺次读取这些pdf并用123456加密
#③给加密后的pdf以原名称加上_encrypted后缀重命名,保存为新的文件
#④读取这些加密后的pdf,并用12345解密,确保加密的正确性
#⑤如果口令错误,则输出“密码输入错误,错误文件为:xxx”
import os,PyPDF2
#获取文件夹中所有pdf,加密并重命名
def pdfParanoid(fileList=[],path='.'):
for fpath,dir,fileNames in os.walk(path):
for fileName in fileNames:
if fileName.endswith('.pdf'):
fullFile=os.path.join(fpath,fileName)
fileList.append(fullFile)
for pdfFile in fileList:
file=open(pdfFile,'rb')
pdfReader = PyPDF2.PdfFileReader(file)
if pdfReader.isEncrypted==False:
pdfWriter = PyPDF2.PdfFileWriter()
for pageNum in range(pdfReader.numPages):
pdfWriter.addPage(pdfReader.getPage(pageNum))
pdfWriter.encrypt('123456')
resultName = os.path.join('.\\pdf\\'+pdfFile.rstrip('.pdf')+'_encrypted.pdf')
resultPdf = open(resultName, 'wb')
pdfWriter.write(resultPdf)
file.close()
resultPdf.close()
print("======文件加密结束======")
#验证加密的正确性,并解密
def encrypedPdf(path='.'):
for fold,subFold,fileNames in os.walk(path):
for fileName in fileNames:
if fileName.endswith('.pdf'):
file = open(os.path.join(fold,fileName),'rb')
pdfReader = PyPDF2.PdfFileReader(file)
pdfWriter = PyPDF2.PdfFileWriter()
if pdfReader.isEncrypted==True:
try:
pdfReader.decrypt('123456')
for pageNum in range(pdfReader.numPages):
pageObj = pdfReader.getPage(pageNum)
pdfWriter.addPage(pageObj)
resultFile = os.path.join('.\\pdf\\'+fileName.rstrip('_encrypted.pdf')+'.pdf')
finalFile = open(resultFile,'wb')
pdfWriter.write(finalFile)
file.close()
finalFile.close()
except:
print("密码输入错误,错误文件为:"+os.path.join(fold,fileName))
print("======文件加密正确,解密成功======")
pdfParanoid()
encrypedPdf()
第13章 PDF偏执狂
最新推荐文章于 2021-12-27 11:09:10 发布