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