一、LibreOffice简介 #
LibreOffice 是一套开源的办公软件套件,支持文档、表格、演示、绘图等多种格式,兼容Microsoft Office。
二、安装方法 #
介绍如何安装LibreOffice及其Python自动化依赖。
# Windows下下载安装包:https://zh.libreoffice.org/download/
# Linux下可用包管理器安装
sudo apt install libreoffice
# Python自动化需安装python-uno模块(部分系统已自带)三、基本用法 #
本节介绍如何用LibreOffice命令行和Python进行文档转换与自动化。
1. 命令行文档格式转换 #
展示如何用命令行将Word、Excel、PPT等批量转换为PDF。
`bash
将Word文档转换为PDF #
libreoffice --headless --convert-to pdf example.docx
将Excel文档转换为PDF #
libreoffice --headless --convert-to pdf example.xlsx
将PPT转换为PDF #
libreoffice --headless --convert-to pdf example.pptx
### 2. Python UNO自动化操作
> 展示如何用Python通过UNO接口操作LibreOffice。
```python
# 导入UNO相关模块
import uno
from com.sun.star.beans import PropertyValue
# 连接到正在运行的LibreOffice实例
local_ctx = uno.getComponentContext()
resolver = local_ctx.ServiceManager.createInstanceWithContext(
"com.sun.star.bridge.UnoUrlResolver", local_ctx)
# 连接到LibreOffice(需先用命令行启动监听端口:soffice --accept="socket,host=127.0.0.1,port=2002;urp;" --headless)
ctx = resolver.resolve(
"uno:socket,host=127.0.0.1,port=2002;urp;StarOffice.ComponentContext")
smgr = ctx.ServiceManager
# 创建Desktop对象
desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)
# 打开文档
file_url = uno.systemPathToFileUrl("example.docx")
props = tuple([PropertyValue("Hidden", 0, True, 0)])
doc = desktop.loadComponentFromURL(file_url, "_blank", 0, props)
# 导出为PDF
pdf_url = uno.systemPathToFileUrl("output.pdf")
export_props = (PropertyValue("FilterName", 0, "writer_pdf_Export", 0),)
doc.storeToURL(pdf_url, export_props)
# 关闭文档
doc.close(True)四、进阶用法 #
本节介绍批量转换、格式控制、宏等高级用法。
1. 批量文档转换脚本 #
展示如何用Python批量转换目录下所有Word为PDF。
`python
导入所需模块 #
import os import uno from com.sun.star.beans import PropertyValue
连接到LibreOffice #
local_ctx = uno.getComponentContext() resolver = local_ctx.ServiceManager.createInstanceWithContext( "com.sun.star.bridge.UnoUrlResolver", local_ctx) ctx = resolver.resolve( "uno:socket,host=127.0.0.1,port=2002;urp;StarOffice.ComponentContext") smgr = ctx.ServiceManager
desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)
批量转换当前目录下所有docx为pdf #
for filename in os.listdir('.'): if filename.endswith('.docx'): file_url = uno.systemPathToFileUrl(os.path.abspath(filename)) doc = desktop.loadComponentFromURL(file_url, "_blank", 0, (PropertyValue("Hidden", 0, True, 0),)) pdf_url = uno.systemPathToFileUrl(os.path.abspath(filename.replace('.docx', '.pdf'))) doc.storeToURL(pdf_url, (PropertyValue("FilterName", 0, "writer_pdf_Export", 0),)) doc.close(True)
### 2. 宏与格式控制
> 展示如何录制和运行宏、设置导出参数。
```python
# 以Python脚本设置PDF导出参数(如只导出部分页码)
from com.sun.star.beans import PropertyValue
export_props = (
PropertyValue("FilterName", 0, "writer_pdf_Export", 0),
PropertyValue("PageRange", 0, "1-2", 0), # 只导出第1-2页
)
doc.storeToURL("file:///output.pdf", export_props)五、常见应用场景 #
LibreOffice 常用于以下场景:
- 批量文档格式转换(如Office转PDF)
- 自动化生成、处理、批量修改文档
- 跨平台办公自动化、无界面服务器文档处理
- 结合Python实现复杂文档流程
六、参考资料 #
推荐学习和查阅的LibreOffice相关资料。