Python一鍵批量改PDF文字:拖進來秒出新文件——再也不用Acrobat來回導
PDF文字替換, 批量導出, 零依賴轉檔, 一鍵完成, 瑞士軍刀
故事開場:一把瑞士軍刀救了周五下班的你
周五 18:00,老板甩來 50 份合同 PDF:
“把里面的‘2023’全部改成‘2024’,今晚就要!”
你打開 Acrobat,發現要:
- 先導出 Word
- 逐個查找替換
- 再導回 PDF
來回三遍,眼睛已花。
這時,你從 U 盤掏出“小白瑞士軍刀”——pdf_editor.py
。
把 PDF 拖進去,一行命令:
python pdf_editor.py
30 秒后,50 份新 PDF 整整齊齊躺在文件夾,老板直呼“效率王”!
痛點解決:再也不用巨軟全家桶,一鍵改字、一鍵導出。
完整代碼(≤1000字符,直接展示)
from docx import Document
from pdf2docx import parse
import subprocess, osdef pdf_to_word(pdf_file):parse(pdf_file, 'word.docx')def edit_word(find, replacement):doc = Document('word.docx')for p in doc.paragraphs:if find in p.text:p.text = p.text.replace(find, replacement)doc.save('converted.docx')def word_to_pdf():subprocess.run(["libreoffice", "--headless", "--convert-to", "pdf", 'converted.docx'])for tmp in ['word.docx', 'converted.docx']:if os.path.exists(tmp):os.remove(tmp)if __name__ == "__main__":file, find, replace = input("格式:文件 舊文本 新文本> ").split()pdf_to_word(file)edit_word(find, replace)word_to_pdf()
代碼解析
功能塊 1:PDF → Word 零門檻
pdf2docx.parse
一行把 PDF 變成可編輯的 .docx
,保留格式。
parse(pdf_file, 'word.docx')
功能塊 2:全文快速替換
遍歷所有段落,直接 str.replace
,比 Word 查找更快。
for p in doc.paragraphs:if find in p.text:p.text = p.text.replace(find, replacement)
功能塊 3:Word → PDF 一鍵回
用 LibreOffice 無頭模式批量轉 PDF,再清理中間文件。
subprocess.run(["libreoffice", "--headless", "--convert-to", "pdf", 'converted.docx'])
如果還想更厲害
擴展點子 1:批量文件夾
把整目錄 PDF 一次性改字,自動按原名輸出。
import glob
for pdf in glob.glob('*.pdf'):pdf_to_word(pdf)edit_word('2023', '2024')word_to_pdf()os.rename('converted.pdf', pdf.replace('.pdf', '_new.pdf'))
擴展點子 2:GUI拖放窗口
用 tkinter
做窗口,拖文件+輸入框即完成。
import tkinter.filedialog as fd
pdf_path = fd.askopenfilename()
# 復用上面三步
總結
pdf_editor.py
這把 40 行瑞士軍刀,把“PDF→Word→替換→PDF”四步壓縮成“拖進去+回車”。
你無需安裝 Acrobat,就能在 Linux/Mac/Windows 上批量改字、批量導出。
再加兩行循環或 GUI,它就從腳本升級成 PDF 工廠。
下次再遇“批量改合同”,直接跑腳本,省時省力!
源碼獲取
完整代碼已開源,包含詳細的注釋文檔:
🔗 [GitCode倉庫] https://gitcode.com/laonong-1024/python-automation-scripts
📥 [備用下載] https://pan.quark.cn/s/654cf649e5a6 提取碼:f5VG