天天看点

python 操作pdf文件-加密与解密 (二)

python 操作pdf 的基本使用

一、PyPDF2 插件库

官方文档示例地址:​​Welcome to PyPDF2 — PyPDF2 documentation​​

二、使用步骤

1.引入库,安装过的忽略此步骤

pip install PyPDF2      

2.pdf文件加密

## 解析 pdf 文件 安装 pip install PyPDF2
from PyPDF2 import PdfReader
from PyPDF2 import PdfWriter

## 加密 pdf

## 路径增加 r 代表处理中文路径问题
reader = PdfReader(r"julong_test\mybatis – MyBatis 3 _ 简介.pdf")
## 创建写入对象
writer = PdfWriter()

# Add all pages to the writer
for page in reader.pages:
    writer.add_page(page)

# Add a password to the new PDF 加密为新的pdf
writer.encrypt("julong")

# Save the new PDF to a file 生成pdf文件
with open(r"julong_test\encrypted-pdf.pdf", "wb") as file_object:
    writer.write(file_object)
print("加密成功!")      

3.pdf文件解密

## 解析 pdf 文件 安装 pip install PyPDF2
from PyPDF2 import PdfReader
from PyPDF2 import PdfWriter

## 解密 pdf

## 路径增加 r 代表处理中文路径问题
reader = PdfReader(r"julong_test\encrypted-pdf.pdf")
## 创建写入对象
writer = PdfWriter()
## 判断是否加密
if reader.is_encrypted:
    ## 解密
    reader.decrypt("julong")

# Add all pages to the writer
for page in reader.pages:
    writer.add_page(page)

# Save the new PDF to a file 生成pdf文件
with open(r"julong_test\decrypted-pdf.pdf", "wb") as file_object:
    writer.write(file_object)
print("解密成功!")      

总结