我的知识记录

Python Word转PDF:LibreOffice批量转换教程

用Python调用LibreOffice无头模式把docx批量转成PDF,跨Windows/Mac/Linux,不依赖Word授权,适合服务器批量处理合同、报告、通知。

场景痛点

公司每天要把一堆docx合同、通知、报价单发出去,Word格式对方打开排版可能乱,必须转成PDF。手动打开Word另存为,一个文件点三四下,几十个文件下来鼠标都点酸。用Python调LibreOffice无头模式,一条命令批量转完,跨平台不依赖Office授权。

用到的库

# Python 侧只用标准库 subprocess
# 系统需要装 LibreOffice(免费):
#   Windows:  https://www.libreoffice.org/download/
#   Ubuntu:   sudo apt install libreoffice --no-install-recommends
#   Mac:      brew install --cask libreoffice

完整代码

# -*- coding: utf-8 -*-
"""
用 LibreOffice 无头模式把 docx 批量转成 PDF。
"""
import shutil
import subprocess
from pathlib import Path


def find_soffice() -> str:
"""自动找 soffice 可执行文件路径,Windows/Mac/Linux 都兼容。"""
exe = shutil.which("soffice") or shutil.which("libreoffice")
if exe:
return exe
# Windows 常见安装路径
candidates = [
r"C:\Program Files\LibreOffice\program\soffice.exe",
r"C:\Program Files (x86)\LibreOffice\program\soffice.exe",
"/Applications/LibreOffice.app/Contents/MacOS/soffice",
]
for c in candidates:
if Path(c).exists():
return c
raise RuntimeError("没找到 LibreOffice,请先安装:https://www.libreoffice.org/")


def word_to_pdf(docx_path: str, output_dir: str) -> str:
soffice = find_soffice()
out = Path(output_dir)
out.mkdir(parents=True, exist_ok=True)

# --headless 无头模式,不弹界面;--convert-to pdf 指定输出格式
cmd = [
soffice,
"--headless",
"--norestore",
"--convert-to", "pdf",
"--outdir", str(out),
str(docx_path),
]
subprocess.run(cmd, check=True, capture_output=True)

pdf_file = out / (Path(docx_path).stem + ".pdf")
print(f"转换完成:{pdf_file}")
return str(pdf_file)


def batch_word_to_pdf(input_dir: str, output_dir: str):
src = Path(input_dir)
docx_files = list(src.glob("*.docx")) + list(src.glob("*.doc"))
print(f"共发现 {len(docx_files)} 个 Word 文件")

for f in docx_files:
try:
word_to_pdf(str(f), output_dir)
except subprocess.CalledProcessError as e:
print(f"失败:{f.name},原因:{e.stderr.decode(errors='ignore')}")


if __name__ == "__main__":
batch_word_to_pdf(
input_dir="word_docs",
output_dir="pdf_output",
)

代码讲解

  • find_soffice() 自动找LibreOffice命令:先看PATH里有没有,没有再按Windows/Mac默认安装路径猜。
  • --headless --norestore 关键参数,告诉LibreOffice不要弹GUI窗口,纯命令行运行。
  • --convert-to pdf --outdir 输出目录 指定转换格式和输出位置,输入文件作为最后一个参数。
  • subprocess.run(capture_output=True) 捕获输出,失败时把错误信息打印出来,方便排查。
  • 批量模式遍历目录下所有.docx.doc,逐个转换,单个失败不影响其他。

运行结果

把docx文件放进word_docs/,跑完在pdf_output/里得到同名.pdf文件,排版、字体、图片都和Word里一致。打开PDF检查页眉页脚、目录页码是否正常。

注意事项

  • 方案本质是"调LibreOffice命令行",不是纯Python库,所以系统必须装LibreOffice。Windows如果装了Office,也可以用docx2pdf库(底层调Word COM接口),但只能在Windows上跑。
  • LibreOffice对Office高级特性(复杂宏、ActiveX、某些WordArt)支持不完全,转换后排版可能有细微差异,重要文档转换完要抽查。
  • 并发别开太高,LibreOffice单实例多进程同时跑会锁用户配置目录,串行最稳。
  • 字体缺失会导致替换字体,转出来和原Word不一样,服务器上要把常用字体(宋体、微软雅黑)一并装上。

Python Word转PDF:LibreOffice批量转换教程

标签:

更新时间:2026-09-14 21:31:45

上一篇:Python文件备份到另一目录教程:shutil一键同步

下一篇:Python拆分PDF按页码 一页一个文件方法