Golang Office文档转PDF开源方案
有没有成熟的开源方案可以用Golang将Office文档(Word/Excel/PPT)转换成PDF?最好能支持Linux服务器环境部署,转换效果要保证和原文档格式一致。目前看到有几个Java的方案,但想找纯Go实现的方案,不知道有没有推荐?
2 回复
在Golang中实现Office文档转PDF,推荐以下开源方案:
1. unidoc/unioffice
推荐度:★★★★★
import "github.com/unidoc/unioffice/document"
func ConvertDocxToPDF(inputPath, outputPath string) error {
doc, err := document.Open(inputPath)
if err != nil {
return err
}
defer doc.Close()
// 转换为PDF
return doc.ExportToPdf(outputPath)
}
特点:
- 纯Go实现,无外部依赖
- 支持DOCX、XLSX、PPTX格式
- 跨平台兼容性好
- 开源协议:AGPL(商业使用需购买许可证)
2. 基于LibreOffice的调用
import "os/exec"
func ConvertViaLibreOffice(inputPath, outputPath string) error {
cmd := exec.Command("libreoffice",
"--headless",
"--convert-to", "pdf",
"--outdir", outputDir,
inputPath)
return cmd.Run()
}
特点:
- 转换质量高
- 支持格式全面
- 需要安装LibreOffice
- 性能相对较慢
3. gotenberg/gotenberg
import "net/http"
func ConvertViaGotenberg(inputPath, outputPath string) error {
// 通过HTTP API调用Gotenberg服务
// 适合微服务架构
}
特点:
- 基于Docker的文档转换服务
- RESTful API接口
- 支持多种文档格式
- 适合分布式部署
选择建议:
- 优先推荐unioffice:纯Go实现,集成简单
- 需要高质量转换:选择LibreOffice方案
- 微服务架构:考虑Gotenberg
注意检查各项目的许可证,确保符合你的使用场景。


