跳到主要内容
版本:3.0.0

LibreOffice 文档转换(Aegis.Documents.Conversion.LibreOffice)

Aegis.Documents.Conversion.LibreOffice 负责 Word 转 PDF。Word -> OFD 也是先经过这层转换,所以这页主要回答的是 Word 文档如何进入整个文档输出链路。

组件概览

字段说明
组件名称LibreOffice 文档转换
真实类库Aegis.Documents.Conversion.LibreOffice
组件定位基于 LibreOffice 的 Word 转 PDF 引擎
默认接入方式通过 文档处理(Aegis.Documents) 一起装配
主要接口IWordToPdfConverter
主要配置Documents:LibreOffice
常见配套OFD 文档转换文档处理

什么时候重点看这页

适合场景:

  • 你要上传 .doc / .docx 后导出 PDF
  • 你要排查 LibreOffice 路径、Linux server 模式或超时问题
  • 你要做 Word -> OFD 之前的中间转换

标准接法

标准 Aegis 项目里,仍然先启用根组件 Documents,然后补齐 Documents:LibreOffice 配置:

{
"Documents": {
"LibreOffice": {
"LibreOfficePath": null,
"MaxConcurrency": 5,
"ConversionTimeoutSeconds": 300,
"AutoStart": true,
"ServerHost": "127.0.0.1",
"ServerPort": 2003
}
}
}

最小使用示例

[HttpPost("word-to-pdf")]
public async Task<IActionResult> ConvertWordToPdf(
IFormFile file,
[FromServices] IWordToPdfConverter converter)
{
var format = Path.GetExtension(file.FileName).ToLower() == ".docx"
? DocFormat.Docx
: DocFormat.Doc;

await using var stream = file.OpenReadStream();
var pdfBytes = await converter.ConvertAsync(stream, format);

return File(
pdfBytes,
"application/pdf",
Path.ChangeExtension(file.FileName, ".pdf"));
}

运行模式怎么理解

框架会按操作系统自动选择运行模式:

操作系统模式说明
Windows / macOSDirect直接调用 soffice
LinuxServer通过 unoserver 服务转换

这意味着:

  • Windows 环境更关注 LibreOfficePath 是否可找到
  • Linux 环境除了 LibreOffice,还要确认 Python 和 unoserver 依赖是否可用

关键配置怎么理解

配置项作用推荐理解
LibreOfficePathLibreOffice 安装目录非标准路径时必须显式配置
ConversionTimeoutSeconds单次转换超时大文档或服务器慢时调大
MaxConcurrency最大并发转换数结合服务器 CPU / 内存调整
EnableStartupDiagnostics启动诊断日志建议保留开启
AutoStartLinux 下自动启动 unoserver一般保持 true
ServerHost / ServerPortLinux server 模式地址默认即可,除非端口冲突

常见场景

批量转换 Word

public async Task BatchConvertAsync(
IEnumerable<string> files,
IWordToPdfConverter converter)
{
foreach (var file in files)
{
await using var stream = File.OpenRead(file);
var format = Path.GetExtension(file).ToLower() == ".docx"
? DocFormat.Docx
: DocFormat.Doc;

var pdfBytes = await converter.ConvertAsync(stream, format);
await File.WriteAllBytesAsync(
Path.ChangeExtension(file, ".pdf"),
pdfBytes);
}
}

先填充 Word 模板,再转 PDF

var wordBytes = await _wordDocumentEditor.FillTemplateAsync(templateStream, new Dictionary<string, string>
{
["PatientName"] = "张三",
["VisitNo"] = "ZY20260318001"
});

await using var wordStream = new MemoryStream(wordBytes);
var pdfBytes = await _wordToPdfConverter.ConvertAsync(wordStream, DocFormat.Docx);

接入后怎么确认生效

通常用下面几项验收就够了:

  • IWordToPdfConverter 可以正常注入
  • 本地或服务器执行 soffice --version 可得到 7.0+
  • 上传简单 .docx 后能成功导出 PDF
  • Linux 环境下转换不出现 unoserver 启动失败

常见问题

找不到 LibreOffice

优先检查:

  • 是否已经安装 LibreOffice 7.0+
  • 安装路径是否不是标准目录
  • 非标准目录时是否已经配置 LibreOfficePath

Linux 下启动就报依赖错误

优先检查:

  • python3 --version
  • python3-uno / libreoffice-pyuno
  • unoserver 是否可正常启动

转出来字体不对

这通常是服务器缺少原始 Word 使用的字体,不是转换接口本身的问题。需要补齐字体后再验证。