明白了,下面给你一个Linux/macOS环境下的完整 Python 脚本示例,实现:
- 自动启动 LibreOffice headless 服务(如果没启动则启动)
- 通过 UNO 连接该服务
- 支持批量 Word 到 PDF 转换
- 使用线程池并发转换(线程数可调)
- 兼顾错误重连机制
- 要求你有 LibreOffice 的 soffice 命令在 PATH 下
代码说明
LibreOfficeService 类封装 soffice headless 服务启动与管理,进程守护
LibreOfficeConverter 类封装连接、转换逻辑
batch_convert() 函数演示批量多线程转换调用
- 须用 LibreOffice 自带的 Python 运行,或确保当前环境能导入
uno
- 使用
subprocess.Popen 后台启动 soffice
脚本内容
import os
import subprocess
import sys
import time
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
import uno
from com.sun.star.beans import PropertyValue
from com.sun.star.connection import NoConnectException
class LibreOfficeService:
def __init__(self, host="127.0.0.1", port=2002, soffice_cmd="soffice"):
self.host = host
self.port = port
self.soffice_cmd = soffice_cmd
self.process = None
def is_running(self):
import socket
s = socket.socket()
try:
s.settimeout(1)
s.connect((self.host, self.port))
s.close()
return True
except Exception:
return False
def start(self):
if self.is_running():
print(f"LibreOffice headless 服务已在 {self.host}:{self.port} 运行")
return
cmd = [
self.soffice_cmd,
"--headless",
f'--accept=socket,host={self.host},port={self.port};urp;',
"--norestore",
"--nofirststartwizard",
"--nodefault",
"--nolockcheck",
"--invisible",
]
print("启动 LibreOffice headless 服务...")
self.process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# 等待服务启动,尝试连接最多10秒
for i in range(20):
if self.is_running():
print("LibreOffice headless 服务启动成功")
return
time.sleep(0.5)
raise RuntimeError("启动 LibreOffice 服务失败,未能连接到 socket")
def stop(self):
if self.process:
self.process.terminate()
self.process.wait(timeout=5)
print("LibreOffice headless 服务已停止")
self.process = None
class LibreOfficeConverter:
def __init__(self, host="127.0.0.1", port=2002, timeout=30):
self.host = host
self.port = port
self.timeout = timeout
self._lock = threading.Lock()
self.desktop = self._connect()
def _connect(self):
local_context = uno.getComponentContext()
resolver = local_context.ServiceManager.createInstanceWithContext(
"com.sun.star.bridge.UnoUrlResolver", local_context
)
for attempt in range(5):
try:
context = resolver.resolve(
f"uno:socket,host={self.host},port={self.port};urp;StarOffice.ComponentContext"
)
smgr = context.ServiceManager
desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", context)
return desktop
except NoConnectException:
print(f"连接LibreOffice服务失败,重试 {attempt + 1}/5...")
time.sleep(1)
raise RuntimeError("无法连接 LibreOffice headless 服务")
def _path_to_url(self, path):
import pathlib
p = pathlib.Path(path).absolute()
return uno.systemPathToFileUrl(str(p))
def convert_to_pdf(self, input_path, output_path):
with self._lock:
input_url = self._path_to_url(input_path)
output_url = self._path_to_url(output_path)
load_props = (PropertyValue(Name="Hidden", Value=True),)
try:
document = self.desktop.loadComponentFromURL(input_url, "_blank", 0, load_props)
export_props = (PropertyValue(Name="FilterName", Value="writer_pdf_Export"),)
document.storeToURL(output_url, export_props)
document.close(True)
print(f"转换成功: {input_path} -> {output_path}")
except Exception as e:
print(f"转换失败: {input_path} -> {output_path},错误: {e}")
raise
def batch_convert(file_pairs, max_workers=4):
"""
file_pairs: [(input_path1, output_path1), (input_path2, output_path2), ...]
max_workers: 线程池最大线程数
"""
service = LibreOfficeService()
service.start()
converter = LibreOfficeConverter()
def worker(in_out):
input_file, output_file = in_out
try:
converter.convert_to_pdf(input_file, output_file)
return (input_file, True, None)
except Exception as e:
return (input_file, False, e)
results = []
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = [executor.submit(worker, pair) for pair in file_pairs]
for future in as_completed(futures):
results.append(future.result())
service.stop()
return results
def main():
if len(sys.argv) < 3:
print(
f"用法:\n {sys.argv[0]} input1.docx output1.pdf [input2.docx output2.pdf ...]"
)
sys.exit(1)
args = sys.argv[1:]
if len(args) % 2 != 0:
print("错误:输入输出文件数量不对应(必须成对)")
sys.exit(1)
file_pairs = [(args[i], args[i + 1]) for i in range(0, len(args), 2)]
# 最大线程数,建议根据CPU和LibreOffice性能调节
max_threads = 4
results = batch_convert(file_pairs, max_workers=max_threads)
print("\n转换结果:")
for src, success, err in results:
if success:
print(f"✅ {src}")
else:
print(f"❌ {src} 失败 [{err}]")
if __name__ == "__main__":
main()
使用说明
- 确保你的系统环境
- LibreOffice 已安装,并且
soffice 命令可用(which soffice 可定位)
- 使用 LibreOffice 自带 Python 运行脚本,或者把
uno 模块配置好(见上一条回复)
-
保存脚本: 如 libreoffice_batch_convert.py
-
执行示例 (用 LibreOffice Python):
$ /usr/lib/libreoffice/program/python3 libreoffice_batch_convert.py \
/path/to/1.docx /path/to/1.pdf \
/path/to/2.docx /path/to/2.pdf \
/path/to/3.docx /path/to/3.pdf
- 脚本会自动启动 LibreOffice headless 并行服务(如果未启动),批量多线程转换。
备注
- 转换失败会打印错误,并继续执行其他文件
- 线程池共享一个连接(通过锁保护UNO调用,防止线程安全问题)
- 你可调节
max_threads 控制并发数量,LibreOffice 并发转换能力有限,通常建议 2-8 线程
- Linux/macOS 下启动和停止 soffice 进程通过
subprocess.Popen 管理,Windows 下可能要改启动命令
- 如果需要支持监听端口超时自动断线重连,可以改进
LibreOfficeConverter
如果你在 Windows 或其他具体环境需要适配,或者想做成永远守护的服务接口,再告诉我。