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("解密成功!")

总结

这是自己学的的例子,欢迎交流 每天进步一点点

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值