Files
rental-contract-pdf/README.MD
2026-05-15 15:19:56 +08:00

127 lines
2.8 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 租屋契約 PDF 產生器
這是一個 Node.js 網頁工具,用指定的 Word `.docx` 範本產生租屋契約 PDF。網頁會帶入
- `{{每月租金}}`:預設 `8000`
- `{{繳款日期}}`:預設 `18`
- `{{保證金}}`:預設 `16000`
產生流程:
1.`templates/` 複製指定的 `.docx` 範本到暫存資料夾。
2. 替換暫存 `.docx` 裡的三個佔位符。
3. 呼叫 LibreOffice headless 將暫存 `.docx` 轉成 PDF。
4. 將 PDF 回傳給網頁下載;手機瀏覽器支援時可直接分享。
5. 刪除暫存 `.docx` 與轉檔過程產生的檔案。
## 專案結構
```text
.
├─ public/ # 前端網頁
├─ src/contractService.js # 複製範本、替換文字、轉 PDF
├─ templates/ # 放 Word .docx 範本
├─ fonts/ # 自訂字體(隨 Docker image 一起打包)
├─ server.js # Express API
├─ Dockerfile
└─ README.MD
```
## 範本準備
把 Word 範本放到 `templates/` 資料夾,範本內請保留以下文字:
```text
{{每月租金}}
{{繳款日期}}
{{保證金}}
```
支援 `.docx` 格式。佔位符若被 Word 拆成多個 run程式會自動合併處理。
## 自訂字體
`.ttf``.otf``.ttc` 字體檔放到 `fonts/` 資料夾:
- **本機執行**:轉換時自動載入至 LibreOffice profile。
- **Docker**build image 時安裝至系統字體LibreOffice 直接讀取。
## 本機執行
本機需要先安裝:
- Node.js 20 或更新版本
- LibreOfficeWindows 預設路徑為 `C:\Program Files\LibreOffice\program\soffice.exe`
安裝套件:
```powershell
npm install
```
啟動:
```powershell
npm start
```
開啟:
```text
http://localhost:3005
```
## Docker 執行
建立 image
```bash
sudo docker build -t rental-contract-pdf .
```
啟動 container
```bash
sudo docker run -d -p 3005:3005 --name rental-contract-pdf rental-contract-pdf
```
若要把本機 `templates/` 掛進 container
```bash
sudo docker run -d -p 3005:3005 -v /path/to/templates:/app/templates --name rental-contract-pdf rental-contract-pdf
```
開啟:
```text
http://localhost:3005
```
## 手機下載或分享
手機連到這個網站後,產生 PDF 時會優先使用瀏覽器的檔案分享功能。若瀏覽器或連線環境不支援檔案分享,網頁會保留下載 PDF 按鈕。
注意:多數手機瀏覽器的檔案分享功能需要 HTTPS 或 localhost。若用區網 IP 開啟,例如 `http://192.168.x.x:3005`,可能只能下載,不能直接分享。
## API
產生 PDF
```http
POST /api/contracts/pdf
Content-Type: application/json
```
Body
```json
{
"template": "租屋契約-內容_逢甲 A.docx",
"monthlyRent": "8000",
"paymentDay": "18",
"deposit": "16000"
}
```
成功時會回傳 `application/pdf`