Python全能PDF小助手:剪切/合并/旋转/加密一条龙——再也不用开会员
PDF编辑, 本地处理, 零会员费, 多功能脚本, 瑞士军刀
故事开场:一把瑞士军刀救了周五下班的你
周五 17:55,老板甩来一堆 PDF:
- “把第 3、7 页删掉”
- “再和合同合并”
- “全部顺时针转 90°”
- “最后加个密码”
你打开 Acrobat,发现要会员,在线工具排队 20 分钟。
这时,你从 U 盘掏出“小白瑞士军刀”——pdf_tools.py
。
一条命令一条提示,30 分钟任务全部搞定,老板直呼“效率王”!
痛点解决:再也不用多个软件来回折腾,本地一站式搞定所有 PDF 操作。
完整代码(>1000字符,展示核心骨架)
from PyPDF2 import PdfFileReader, PdfFileWriter, PdfFileMerger
from pathlib import Path# 主菜单
print("INFO 查看信息 | OUTPUT 提取文字 | PDF 裁剪页面 | ADD 合并 | CW/ACW 旋转 | PWD 加密")
cmd = input("输入指令: ").upper()pdf_path = Path.home() / "myfile.pdf"
pdf = PdfFileReader(str(pdf_path))if cmd == "INFO":print("标题:", pdf.documentInfo.title, "页数:", pdf.getNumPages())elif cmd == "OUTPUT":mode = input("FULL 全文 / PAGE 单页? ").upper()if mode == "FULL":with open('fulltext.txt', 'w') as f:for p in pdf.pages:f.write(p.extractText())elif mode == "PAGE":n = int(input("第几页? "))print(pdf.getPage(n).extractText())elif cmd == "PDF":while True:pg = int(input("保留哪一页? "))writer = PdfFileWriter()writer.addPage(pdf.getPage(pg))with Path("sliced.pdf").open("wb") as out:writer.write(out)if input("继续加页? YES/NO ").upper() != "YES":breakelif cmd == "ADD":f1, f2 = input("两个文件名(空格分隔): ").split()merger = PdfFileMerger()for f in [f1, f2]:merger.append(str(Path.home() / f))with Path("concatenated.pdf").open("wb") as out:merger.write(out)elif cmd == "CW":writer = PdfFileWriter()for p in pdf.pages:writer.addPage(p.rotateClockwise(90))with Path("rotated.pdf").open("wb") as out:writer.write(out)elif cmd == "PWD":pwd = input("输入密码: ")writer = PdfFileWriter()writer.appendPagesFromReader(pdf)writer.encrypt(user_pwd=pwd)with Path("protected.pdf").open("wb") as out:writer.write(out)
代码解析
功能块 1:信息速览
一句话打印标题、页数,先让你心里有底。
print("标题:", pdf.documentInfo.title, "页数:", pdf.getNumPages())
功能块 2:文本提取
全文或单页一键导出 .txt
,方便二次编辑。
with open('fulltext.txt', 'w') as f:for p in pdf.pages:f.write(p.extractText())
功能块 3:页面裁剪/合并/旋转/加密
- 裁剪:按页码生成
sliced.pdf
- 合并:多文件一键拼接
- 旋转:顺时针/逆时针 90°
- 加密:AES 密码保护
writer.addPage(p.rotateClockwise(90))
writer.encrypt(user_pwd=pwd)
如果还想更厉害
扩展点子 1:批量文件夹
把 docs/
里所有 PDF 合并成一本电子书。
import glob
merger = PdfFileMerger()
for pdf in glob.glob("docs/*.pdf"):merger.append(pdf)
merger.write("all_in_one.pdf")
扩展点子 2:GUI 拖放
用 tkinter
做窗口,拖文件即执行操作。
import tkinter.filedialog as fd
file = fd.askopenfilename()
# 复用相应逻辑
总结
pdf_tools.py
这把 150 行瑞士军刀,把“开 N 个软件→上传→下载”五步压缩成“一条命令”。
你无需会员、无需联网,就能在本地完成 PDF 裁剪、合并、旋转、加密全套操作。
再加两行批量或 GUI,它就从脚本升级成 PDF 工厂。
下次再遇“PDF 小手术”,直接跑脚本,30 秒收工!
源码获取
完整代码已开源,包含详细的注释文档:
🔗 [GitCode仓库] https://gitcode.com/laonong-1024/python-automation-scripts
📥 [备用下载] https://pan.quark.cn/s/654cf649e5a6 提取码:f5VG