Python一键批量改PDF文字:拖进来秒出新文件------再也不用Acrobat来回导
PDF文字替换, 批量导出, 零依赖转档, 一键完成, 瑞士军刀
故事开场:一把瑞士军刀救了周五下班的你
周五 18:00,老板甩来 50 份合同 PDF:
"把里面的'2023'全部改成'2024',今晚就要!"
你打开 Acrobat,发现要:
- 先导出 Word
- 逐个查找替换
- 再导回 PDF
来回三遍,眼睛已花。
这时,你从 U 盘掏出"小白瑞士军刀"------pdf_editor.py
。
把 PDF 拖进去,一行命令:
bash
python pdf_editor.py
30 秒后,50 份新 PDF 整整齐齐躺在文件夹,老板直呼"效率王"!
痛点解决:再也不用巨软全家桶,一键改字、一键导出。
完整代码(≤1000字符,直接展示)
python
from docx import Document
from pdf2docx import parse
import subprocess, os
def 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
,保留格式。
python
parse(pdf_file, 'word.docx')
功能块 2:全文快速替换
遍历所有段落,直接 str.replace
,比 Word 查找更快。
python
for p in doc.paragraphs:
if find in p.text:
p.text = p.text.replace(find, replacement)
功能块 3:Word → PDF 一键回
用 LibreOffice 无头模式批量转 PDF,再清理中间文件。
python
subprocess.run(["libreoffice", "--headless", "--convert-to", "pdf", 'converted.docx'])
如果还想更厉害
扩展点子 1:批量文件夹
把整目录 PDF 一次性改字,自动按原名输出。
python
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
做窗口,拖文件+输入框即完成。
python
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