Skip to content

leokwsw/libreoffice-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

LibreOffice API

一個以 FastAPI 建立、使用 LibreOffice 在無頭模式下執行文件轉檔的輕量服務。

目前支援上傳以下 Office 檔案並轉成 PDF:

  • .doc
  • .docx
  • .ppt
  • .pptx

此專案適合用在:

  • 文件預覽前的 PDF 轉檔流程
  • 後端檔案處理服務
  • 以 Docker 快速部署的內部轉檔 API

功能特色

  • 使用 FastAPI 提供簡單 HTTP API
  • 透過 LibreOffice --headless 執行文件轉 PDF
  • 使用 docker-compose 快速啟動
  • 內建 Nginx 反向代理與上傳大小限制
  • 轉檔完成後自動清理暫存檔案

專案結構

.
├── app/
│   └── app.py
├── nginx/
│   └── nginx.conf
├── Dockerfile
├── docker-compose.yml
├── requirements.txt
└── README.md

執行方式

需求

  • Docker
  • Docker Compose

使用 Docker Compose 啟動

docker compose up --build -d

服務啟動後,對外入口為:

  • API Base URL: http://localhost:8080

API 說明

GET /health

用來檢查服務是否正常運作。

範例:

curl http://localhost:8080/health

預期回應:

{"status":"ok"}

POST /convert

上傳文件並回傳轉好的 PDF 檔案。

Request

  • Method: POST
  • Content-Type: multipart/form-data
  • 欄位名稱: file

支援格式

  • .doc
  • .docx
  • .ppt
  • .pptx

範例

curl -X POST "http://localhost:8080/convert" \
  -F "file=@sample.docx" \
  --output sample.pdf

如果成功,回應內容會直接是 PDF 檔案串流。

錯誤回應

常見錯誤狀況如下:

  • 400 Bad Request: 上傳的副檔名不支援
  • 504 Gateway Timeout: LibreOffice 轉檔超時
  • 500 Internal Server Error: LibreOffice 執行失敗或 PDF 未成功產生

系統限制

  • 單次請求最大上傳大小由 Nginx 設為 25MB
  • 目前僅支援轉出 PDF
  • 目前僅允許 Word 與 PowerPoint 格式,不含 Excel
  • 轉檔流程使用暫存目錄 /tmp/convert
  • 每次轉檔逾時限制為 60

本機直接執行

如果你不想透過 Docker,也可以直接在本機執行 API,但需自行安裝 LibreOffice。

安裝 Python 套件

pip install -r requirements.txt

啟動服務

uvicorn app.app:app --host 0.0.0.0 --port 8000

接著可直接呼叫:

  • http://localhost:8000/health
  • http://localhost:8000/convert

Docker 說明

Dockerfile 內安裝了以下主要元件:

  • LibreOffice
  • LibreOffice Writer
  • LibreOffice Impress
  • 常見字型:fonts-notofonts-noto-cjkfonts-dejavu

這些字型有助於降低文件轉 PDF 時的字型缺失問題,尤其是中日韓文字內容。

部署架構

docker-compose.yml 會啟動兩個服務:

  • api: FastAPI + LibreOffice 轉檔服務
  • nginx: 對外提供 8080,並代理到 api:8000

開發備註

  • API 應用程式入口位於 app/app.py
  • Nginx 設定位於 nginx/nginx.conf
  • 預設啟動指令使用 uvicorn 單一 worker

About

LibreOffice API

Topics

Resources

Stars

Watchers

Forks

Contributors