【问题描述】用Python如何为PDF文档批量加密和解密呢?
【小千解答】使用scandir获取文件清单,使用PyPDF2库实现加密和解密。
代码如下:
import os from PyPDF2 import PdfFileReader,PdfFileWriter xqpath = 'd:\\xqoffice' # 加密 for xqfile in os.scandir(xqpath): pdf_reader = PdfFileReader(xqfile.path) pdf_writer = PdfFileWriter() for pagenum in range(pdf_reader.getNumPages()): pageobj = pdf_reader.getPage(pagenum) pdf_writer.addPage(pageobj) pdf_writer.encrypt('xqoffice.cn') with open(xqfile.path,'wb') as xqpdf: pdf_writer.write(xqpdf) # 解密 for xqfile in os.scandir(xqpath): pdf_reader = PdfFileReader(xqfile.path) pdf_reader.decrypt('xqoffice.cn') pdf_writer = PdfFileWriter() for pagenum in range(pdf_reader.getNumPages()): pageobj = pdf_reader.getPage(pagenum) pdf_writer.addPage(pageobj) with open(xqfile.path,'wb') as xqpdf: pdf_writer.write(xqpdf)
注:如果运行代码报错如下,参照参考资料3修改PyPDF2库的源码。
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 8-9: ordinal not in range(256)
【参考资料】