初始化專案:租屋契約 PDF 產生器

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-15 12:04:54 +08:00
commit e1fcf3eb77
13 changed files with 1768 additions and 0 deletions

7
.dockerignore Normal file
View File

@@ -0,0 +1,7 @@
node_modules
npm-debug.log
.git
.gitignore
tmp
*.pdf
*.log

4
.gitignore vendored Normal file
View File

@@ -0,0 +1,4 @@
node_modules/
tmp/
*.pdf
*.log

24
Dockerfile Normal file
View File

@@ -0,0 +1,24 @@
FROM node:20-bookworm-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
libreoffice-writer \
fonts-noto-cjk \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
ENV NODE_ENV=production
ENV PORT=3000
ENV TEMPLATE_DIR=/app/templates
ENV TEMP_DIR=/tmp/rental-contracts
ENV SOFFICE_BIN=soffice
EXPOSE 3000
CMD ["npm", "start"]

118
README.MD Normal file
View File

@@ -0,0 +1,118 @@
# 租屋契約 PDF 產生器
這是一個 Node.js 網頁工具,用指定的 Word `.doc` 範本產生租屋契約 PDF。網頁會帶入
- `{{每月租金}}`:預設 `8000`
- `{{繳款日期}}`:預設 `18`
- `{{保證金}}`:預設 `16000`
產生流程:
1. 從 `templates/` 複製指定的 `.doc` 範本到暫存資料夾。
2. 替換暫存 `.doc` 裡的三個佔位符。
3. 呼叫 LibreOffice headless 將暫存 `.doc` 轉成 PDF。
4. 將 PDF 回傳給網頁下載;手機瀏覽器支援時可直接分享。
5. 刪除暫存 `.doc` 與轉檔過程產生的檔案。
## 專案結構
```text
.
├─ public/ # 前端網頁
├─ src/contractService.js # 複製範本、替換文字、轉 PDF
├─ templates/ # 放 Word .doc 範本
├─ server.js # Express API
├─ Dockerfile
└─ README.MD
```
## 範本準備
把 Word 範本放到 `templates/` 資料夾,範本內請保留以下文字:
```text
{{每月租金}}
{{繳款日期}}
{{保證金}}
```
目前程式針對舊版 `.doc` 以固定長度替換,填入的值不能比佔位符字數更長。金額與日期這類短數字可以正常使用。
## 本機執行
本機需要先安裝:
- Node.js 20 或更新版本
- LibreOffice且 `soffice` 指令可在命令列執行
安裝套件:
```powershell
npm install
```
啟動:
```powershell
npm start
```
開啟:
```text
http://localhost:3000
```
## Docker 執行
建立 image
```powershell
docker build -t rental-contract-pdf .
```
啟動 container
```powershell
docker run --rm -p 3000:3000 rental-contract-pdf
```
若要把本機 `templates/` 掛進 container
```powershell
docker run --rm -p 3000:3000 -v "${PWD}\templates:/app/templates" rental-contract-pdf
```
開啟:
```text
http://localhost:3000
```
## 手機下載或分享
手機連到這個網站後,產生 PDF 時會優先使用瀏覽器的檔案分享功能。若瀏覽器或連線環境不支援檔案分享,網頁會保留下載 PDF 按鈕。
注意:多數手機瀏覽器的檔案分享功能需要 HTTPS 或 localhost。若用區網 IP 開啟,例如 `http://192.168.x.x:3000`,可能只能下載,不能直接分享。
## API
產生 PDF
```http
POST /api/contracts/pdf
Content-Type: application/json
```
Body
```json
{
"template": "租屋契約-內容_逢甲 A.doc",
"monthlyRent": "8000",
"paymentDay": "18",
"deposit": "16000"
}
```
成功時會回傳 `application/pdf`。

830
package-lock.json generated Normal file
View File

@@ -0,0 +1,830 @@
{
"name": "rental-contract-pdf",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "rental-contract-pdf",
"version": "1.0.0",
"dependencies": {
"express": "^4.21.2"
},
"engines": {
"node": ">=20"
}
},
"node_modules/accepts": {
"version": "1.3.8",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
"integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==",
"license": "MIT",
"dependencies": {
"mime-types": "~2.1.34",
"negotiator": "0.6.3"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/array-flatten": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",
"license": "MIT"
},
"node_modules/body-parser": {
"version": "1.20.5",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.5.tgz",
"integrity": "sha512-3grm+/2tUOvu2cjJkvsIxrv/wVpfXQW4PsQHYm7yk4vfpu7Ekl6nEsYBoJUL6qDwZUx8wUhQ8tR2qz+ad9c9OA==",
"license": "MIT",
"dependencies": {
"bytes": "~3.1.2",
"content-type": "~1.0.5",
"debug": "2.6.9",
"depd": "2.0.0",
"destroy": "~1.2.0",
"http-errors": "~2.0.1",
"iconv-lite": "~0.4.24",
"on-finished": "~2.4.1",
"qs": "~6.15.1",
"raw-body": "~2.5.3",
"type-is": "~1.6.18",
"unpipe": "~1.0.0"
},
"engines": {
"node": ">= 0.8",
"npm": "1.2.8000 || >= 1.4.16"
}
},
"node_modules/bytes": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
"integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/call-bind-apply-helpers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/call-bound": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
"integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"get-intrinsic": "^1.3.0"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/content-disposition": {
"version": "0.5.4",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
"integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==",
"license": "MIT",
"dependencies": {
"safe-buffer": "5.2.1"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/content-type": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
"integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/cookie": {
"version": "0.7.2",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
"integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/cookie-signature": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz",
"integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==",
"license": "MIT"
},
"node_modules/debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
"license": "MIT",
"dependencies": {
"ms": "2.0.0"
}
},
"node_modules/depd": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
"integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/destroy": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz",
"integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",
"license": "MIT",
"engines": {
"node": ">= 0.8",
"npm": "1.2.8000 || >= 1.4.16"
}
},
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.1",
"es-errors": "^1.3.0",
"gopd": "^1.2.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/ee-first": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
"license": "MIT"
},
"node_modules/encodeurl": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
"integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/es-define-property": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-errors": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-object-atoms": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
"integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/escape-html": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
"integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
"license": "MIT"
},
"node_modules/etag": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
"integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/express": {
"version": "4.22.2",
"resolved": "https://registry.npmjs.org/express/-/express-4.22.2.tgz",
"integrity": "sha512-IuL+Elrou2ZvCFHs18/CIzy2Nzvo25nZ1/D2eIZlz7c+QUayAcYoiM2BthCjs+EBHVpjYjcuLDAiCWgeIX3X1Q==",
"license": "MIT",
"dependencies": {
"accepts": "~1.3.8",
"array-flatten": "1.1.1",
"body-parser": "~1.20.5",
"content-disposition": "~0.5.4",
"content-type": "~1.0.4",
"cookie": "~0.7.1",
"cookie-signature": "~1.0.6",
"debug": "2.6.9",
"depd": "2.0.0",
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"finalhandler": "~1.3.1",
"fresh": "~0.5.2",
"http-errors": "~2.0.0",
"merge-descriptors": "1.0.3",
"methods": "~1.1.2",
"on-finished": "~2.4.1",
"parseurl": "~1.3.3",
"path-to-regexp": "~0.1.12",
"proxy-addr": "~2.0.7",
"qs": "~6.15.1",
"range-parser": "~1.2.1",
"safe-buffer": "5.2.1",
"send": "~0.19.0",
"serve-static": "~1.16.2",
"setprototypeof": "1.2.0",
"statuses": "~2.0.1",
"type-is": "~1.6.18",
"utils-merge": "1.0.1",
"vary": "~1.1.2"
},
"engines": {
"node": ">= 0.10.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/finalhandler": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz",
"integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==",
"license": "MIT",
"dependencies": {
"debug": "2.6.9",
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"on-finished": "~2.4.1",
"parseurl": "~1.3.3",
"statuses": "~2.0.2",
"unpipe": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/forwarded": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
"integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/fresh": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
"integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/function-bind": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-intrinsic": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"es-define-property": "^1.0.1",
"es-errors": "^1.3.0",
"es-object-atoms": "^1.1.1",
"function-bind": "^1.1.2",
"get-proto": "^1.0.1",
"gopd": "^1.2.0",
"has-symbols": "^1.1.0",
"hasown": "^2.0.2",
"math-intrinsics": "^1.1.0"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
"license": "MIT",
"dependencies": {
"dunder-proto": "^1.0.1",
"es-object-atoms": "^1.0.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/gopd": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/has-symbols": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/hasown": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.3.tgz",
"integrity": "sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg==",
"license": "MIT",
"dependencies": {
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/http-errors": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
"integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
"license": "MIT",
"dependencies": {
"depd": "~2.0.0",
"inherits": "~2.0.4",
"setprototypeof": "~1.2.0",
"statuses": "~2.0.2",
"toidentifier": "~1.0.1"
},
"engines": {
"node": ">= 0.8"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/iconv-lite": {
"version": "0.4.24",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
"integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
"license": "MIT",
"dependencies": {
"safer-buffer": ">= 2.1.2 < 3"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"license": "ISC"
},
"node_modules/ipaddr.js": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
"integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
"license": "MIT",
"engines": {
"node": ">= 0.10"
}
},
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/media-typer": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
"integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/merge-descriptors": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz",
"integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/methods": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz",
"integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
"integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==",
"license": "MIT",
"bin": {
"mime": "cli.js"
},
"engines": {
"node": ">=4"
}
},
"node_modules/mime-db": {
"version": "1.52.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime-types": {
"version": "2.1.35",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"license": "MIT",
"dependencies": {
"mime-db": "1.52.0"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
"license": "MIT"
},
"node_modules/negotiator": {
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
"integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/object-inspect": {
"version": "1.13.4",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
"integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/on-finished": {
"version": "2.4.1",
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
"integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
"license": "MIT",
"dependencies": {
"ee-first": "1.1.1"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/parseurl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
"integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/path-to-regexp": {
"version": "0.1.13",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz",
"integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==",
"license": "MIT"
},
"node_modules/proxy-addr": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
"integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
"license": "MIT",
"dependencies": {
"forwarded": "0.2.0",
"ipaddr.js": "1.9.1"
},
"engines": {
"node": ">= 0.10"
}
},
"node_modules/qs": {
"version": "6.15.1",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.15.1.tgz",
"integrity": "sha512-6YHEFRL9mfgcAvql/XhwTvf5jKcOiiupt2FiJxHkiX1z4j7WL8J/jRHYLluORvc1XxB5rV20KoeK00gVJamspg==",
"license": "BSD-3-Clause",
"dependencies": {
"side-channel": "^1.1.0"
},
"engines": {
"node": ">=0.6"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/range-parser": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
"integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/raw-body": {
"version": "2.5.3",
"resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz",
"integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==",
"license": "MIT",
"dependencies": {
"bytes": "~3.1.2",
"http-errors": "~2.0.1",
"iconv-lite": "~0.4.24",
"unpipe": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/safe-buffer": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
"node_modules/send": {
"version": "0.19.2",
"resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz",
"integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==",
"license": "MIT",
"dependencies": {
"debug": "2.6.9",
"depd": "2.0.0",
"destroy": "1.2.0",
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"fresh": "~0.5.2",
"http-errors": "~2.0.1",
"mime": "1.6.0",
"ms": "2.1.3",
"on-finished": "~2.4.1",
"range-parser": "~1.2.1",
"statuses": "~2.0.2"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/send/node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/serve-static": {
"version": "1.16.3",
"resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz",
"integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==",
"license": "MIT",
"dependencies": {
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"parseurl": "~1.3.3",
"send": "~0.19.1"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/setprototypeof": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
"license": "ISC"
},
"node_modules/side-channel": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",
"integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"object-inspect": "^1.13.3",
"side-channel-list": "^1.0.0",
"side-channel-map": "^1.0.1",
"side-channel-weakmap": "^1.0.2"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-list": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",
"integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"object-inspect": "^1.13.4"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-map": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
"integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.5",
"object-inspect": "^1.13.3"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-weakmap": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
"integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.5",
"object-inspect": "^1.13.3",
"side-channel-map": "^1.0.1"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/statuses": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
"integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/toidentifier": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
"integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
"license": "MIT",
"engines": {
"node": ">=0.6"
}
},
"node_modules/type-is": {
"version": "1.6.18",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
"integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
"license": "MIT",
"dependencies": {
"media-typer": "0.3.0",
"mime-types": "~2.1.24"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/unpipe": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
"integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/utils-merge": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
"integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==",
"license": "MIT",
"engines": {
"node": ">= 0.4.0"
}
},
"node_modules/vary": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
"integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
}
}
}

16
package.json Normal file
View File

@@ -0,0 +1,16 @@
{
"name": "rental-contract-pdf",
"version": "1.0.0",
"description": "用 Node.js 產生租屋契約 PDF",
"main": "server.js",
"scripts": {
"start": "node server.js",
"dev": "node --watch server.js"
},
"dependencies": {
"express": "^4.21.2"
},
"engines": {
"node": ">=20"
}
}

166
public/app.js Normal file
View File

@@ -0,0 +1,166 @@
const form = document.querySelector('#contractForm');
const templateSelect = document.querySelector('#template');
const submitButton = document.querySelector('#submitButton');
const downloadButton = document.querySelector('#downloadButton');
const shareButton = document.querySelector('#shareButton');
const message = document.querySelector('#message');
const resultTitle = document.querySelector('#resultTitle');
const connectionStatus = document.querySelector('#connectionStatus');
let currentPdfBlob = null;
let currentPdfFileName = '租屋契約.pdf';
loadTemplates();
form.addEventListener('submit', async (event) => {
event.preventDefault();
setBusy(true);
resetPdf();
try {
const formData = new FormData(form);
const response = await fetch('/api/contracts/pdf', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
template: formData.get('template'),
monthlyRent: formData.get('monthlyRent'),
paymentDay: formData.get('paymentDay'),
deposit: formData.get('deposit'),
}),
});
if (!response.ok) {
const errorBody = await response.json().catch(() => ({}));
throw new Error(errorBody.error || 'PDF 產生失敗。');
}
currentPdfBlob = await response.blob();
currentPdfFileName = getFileNameFromDisposition(response.headers.get('Content-Disposition'))
|| buildDefaultFileName(formData.get('template'));
resultTitle.textContent = 'PDF 已產生';
message.textContent = currentPdfFileName;
downloadButton.disabled = false;
shareButton.disabled = !canShareCurrentPdf();
} catch (error) {
resultTitle.textContent = '產生失敗';
message.textContent = error.message;
} finally {
setBusy(false);
}
});
downloadButton.addEventListener('click', () => {
if (!currentPdfBlob) {
return;
}
downloadPdf();
});
shareButton.addEventListener('click', async () => {
if (!currentPdfBlob) {
return;
}
const file = new File([currentPdfBlob], currentPdfFileName, { type: 'application/pdf' });
if (!navigator.canShare || !navigator.canShare({ files: [file] })) {
downloadPdf();
return;
}
try {
await navigator.share({
title: '租屋契約 PDF',
files: [file],
});
} catch (error) {
if (error.name !== 'AbortError') {
message.textContent = '分享失敗,已保留下載按鈕。';
}
}
});
async function loadTemplates() {
try {
const response = await fetch('/api/templates');
if (!response.ok) {
throw new Error('無法讀取範本。');
}
const body = await response.json();
templateSelect.replaceChildren(
...body.templates.map((name) => new Option(name, name)),
);
if (body.templates.length === 0) {
templateSelect.append(new Option('templates 資料夾沒有 .doc 範本', ''));
templateSelect.disabled = true;
submitButton.disabled = true;
connectionStatus.textContent = '缺少範本';
message.textContent = '請先將 .doc 範本放進 templates 資料夾。';
return;
}
connectionStatus.textContent = '可使用';
} catch (error) {
templateSelect.append(new Option('讀取失敗', ''));
templateSelect.disabled = true;
submitButton.disabled = true;
connectionStatus.textContent = '離線';
message.textContent = error.message;
}
}
function setBusy(isBusy) {
submitButton.disabled = isBusy || templateSelect.disabled;
submitButton.textContent = isBusy ? '產生中' : '產生 PDF';
}
function resetPdf() {
currentPdfBlob = null;
downloadButton.disabled = true;
shareButton.disabled = true;
resultTitle.textContent = '產生中';
message.textContent = '正在建立 PDF。';
}
function canShareCurrentPdf() {
if (!currentPdfBlob || !navigator.canShare) {
return false;
}
const file = new File([currentPdfBlob], currentPdfFileName, { type: 'application/pdf' });
return navigator.canShare({ files: [file] });
}
function downloadPdf() {
const url = URL.createObjectURL(currentPdfBlob);
const link = document.createElement('a');
link.href = url;
link.download = currentPdfFileName;
document.body.append(link);
link.click();
link.remove();
URL.revokeObjectURL(url);
}
function getFileNameFromDisposition(disposition) {
if (!disposition) {
return '';
}
const utf8Match = disposition.match(/filename\*=UTF-8''([^;]+)/i);
if (utf8Match) {
return decodeURIComponent(utf8Match[1]);
}
const asciiMatch = disposition.match(/filename="([^"]+)"/i);
return asciiMatch ? asciiMatch[1] : '';
}
function buildDefaultFileName(templateName) {
const baseName = String(templateName || '租屋契約').replace(/\.[^.]+$/, '');
return `${baseName}.pdf`;
}

69
public/index.html Normal file
View File

@@ -0,0 +1,69 @@
<!doctype html>
<html lang="zh-Hant">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>租屋契約 PDF 產生器</title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<main class="app-shell">
<header class="topbar">
<div>
<p class="eyebrow">Word to PDF</p>
<h1>租屋契約 PDF 產生器</h1>
</div>
<span id="connectionStatus" class="status-pill">連線中</span>
</header>
<section class="workspace" aria-label="租屋契約資料">
<form id="contractForm" class="tool-panel">
<label class="field">
<span>Word 範本</span>
<select id="template" name="template" required></select>
</label>
<div class="field-grid">
<label class="field">
<span>每月租金</span>
<input name="monthlyRent" type="number" inputmode="numeric" min="1" step="1" value="8000" required>
</label>
<label class="field">
<span>繳款日期</span>
<input name="paymentDay" type="number" inputmode="numeric" min="1" max="31" step="1" value="18" required>
</label>
<label class="field">
<span>保證金</span>
<input name="deposit" type="number" inputmode="numeric" min="1" step="1" value="16000" required>
</label>
</div>
<button id="submitButton" class="primary-button" type="submit">
產生 PDF
</button>
</form>
<section class="result-panel" aria-label="PDF 結果">
<div>
<p class="eyebrow">PDF</p>
<h2 id="resultTitle">尚未產生</h2>
<p id="message" class="message">請輸入資料後產生 PDF。</p>
</div>
<div class="result-actions">
<button id="downloadButton" class="secondary-button" type="button" disabled>
下載 PDF
</button>
<button id="shareButton" class="secondary-button" type="button" disabled>
分享 PDF
</button>
</div>
</section>
</section>
</main>
<script src="/app.js" defer></script>
</body>
</html>

214
public/styles.css Normal file
View File

@@ -0,0 +1,214 @@
:root {
color-scheme: light;
--bg: #f6f8f7;
--surface: #ffffff;
--surface-muted: #eef4f1;
--border: #cfdbd5;
--text: #18201d;
--muted: #64716b;
--accent: #0f766e;
--accent-hover: #0b5f59;
--warning: #9a5b00;
--shadow: 0 18px 45px rgba(15, 35, 30, 0.08);
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-height: 100vh;
background:
linear-gradient(180deg, #ffffff 0, var(--bg) 260px),
var(--bg);
color: var(--text);
font-family: "Noto Sans TC", "Microsoft JhengHei", system-ui, sans-serif;
}
button,
input,
select {
font: inherit;
}
.app-shell {
width: min(1080px, calc(100% - 32px));
margin: 0 auto;
padding: 32px 0;
}
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
margin-bottom: 24px;
}
.eyebrow {
margin: 0 0 6px;
color: var(--accent);
font-size: 0.78rem;
font-weight: 700;
text-transform: uppercase;
}
h1,
h2 {
margin: 0;
letter-spacing: 0;
}
h1 {
font-size: clamp(1.7rem, 2.3vw, 2.45rem);
}
h2 {
font-size: 1.35rem;
}
.status-pill {
flex: 0 0 auto;
min-width: 76px;
border: 1px solid var(--border);
border-radius: 999px;
background: var(--surface-muted);
padding: 7px 12px;
color: var(--muted);
font-size: 0.9rem;
text-align: center;
}
.workspace {
display: grid;
grid-template-columns: minmax(0, 1.35fr) minmax(280px, 0.65fr);
gap: 20px;
align-items: start;
}
.tool-panel,
.result-panel {
border: 1px solid var(--border);
border-radius: 8px;
background: var(--surface);
box-shadow: var(--shadow);
}
.tool-panel {
display: grid;
gap: 18px;
padding: 22px;
}
.field-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 14px;
}
.field {
display: grid;
gap: 8px;
color: var(--muted);
font-size: 0.92rem;
font-weight: 700;
}
.field input,
.field select {
width: 100%;
min-height: 46px;
border: 1px solid var(--border);
border-radius: 6px;
background: #ffffff;
color: var(--text);
padding: 10px 12px;
outline: none;
}
.field input:focus,
.field select:focus {
border-color: var(--accent);
box-shadow: 0 0 0 3px rgba(15, 118, 110, 0.15);
}
.primary-button,
.secondary-button {
min-height: 46px;
border: 0;
border-radius: 6px;
padding: 0 16px;
cursor: pointer;
font-weight: 800;
}
.primary-button {
justify-self: start;
min-width: 150px;
background: var(--accent);
color: #ffffff;
}
.primary-button:hover:not(:disabled) {
background: var(--accent-hover);
}
.secondary-button {
border: 1px solid var(--border);
background: #ffffff;
color: var(--text);
}
.primary-button:disabled,
.secondary-button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.result-panel {
display: grid;
gap: 24px;
min-height: 216px;
padding: 22px;
}
.message {
min-height: 46px;
margin: 10px 0 0;
color: var(--muted);
line-height: 1.6;
overflow-wrap: anywhere;
}
.result-actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
align-self: end;
}
@media (max-width: 760px) {
.app-shell {
width: min(100% - 24px, 560px);
padding: 20px 0;
}
.topbar,
.workspace,
.field-grid {
grid-template-columns: 1fr;
}
.topbar {
display: grid;
}
.status-pill {
justify-self: start;
}
.primary-button {
width: 100%;
}
}

60
server.js Normal file
View File

@@ -0,0 +1,60 @@
const express = require('express');
const path = require('node:path');
const {
createContractPdf,
listTemplates,
} = require('./src/contractService');
const app = express();
const port = Number(process.env.PORT || 3005);
app.use(express.json({ limit: '1mb' }));
app.use(express.static(path.join(__dirname, 'public')));
app.get('/api/health', (_req, res) => {
res.json({ ok: true });
});
app.get('/api/templates', async (_req, res, next) => {
try {
res.json({ templates: await listTemplates() });
} catch (error) {
next(error);
}
});
app.post('/api/contracts/pdf', async (req, res) => {
try {
const result = await createContractPdf({
template: req.body.template,
monthlyRent: req.body.monthlyRent,
paymentDay: req.body.paymentDay,
deposit: req.body.deposit,
});
res.setHeader('Content-Type', 'application/pdf');
res.setHeader(
'Content-Disposition',
`attachment; filename="rental-contract.pdf"; filename*=UTF-8''${encodeURIComponent(result.fileName)}`,
);
res.setHeader('Cache-Control', 'no-store');
res.send(result.buffer);
} catch (error) {
console.error(error);
const status = error.exposeToClient ? 400 : 500;
res.status(status).json({
error: error.exposeToClient
? error.message
: 'PDF 產生失敗,請確認 LibreOffice 已安裝且範本格式正確。',
});
}
});
app.use((error, _req, res, _next) => {
console.error(error);
res.status(500).json({ error: '伺服器發生錯誤。' });
});
app.listen(port, () => {
console.log(`Rental contract PDF app is running at http://localhost:${port}`);
});

260
src/contractService.js Normal file
View File

@@ -0,0 +1,260 @@
const crypto = require('node:crypto');
const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const { spawn } = require('node:child_process');
const { pathToFileURL } = require('node:url');
const TEMPLATE_DIR = path.resolve(process.env.TEMPLATE_DIR || path.join(process.cwd(), 'templates'));
const TEMP_DIR = path.resolve(process.env.TEMP_DIR || path.join(os.tmpdir(), 'rental-contracts'));
const SOFFICE_BIN = process.env.SOFFICE_BIN || 'soffice';
const SUPPORTED_TEMPLATE_EXTENSIONS = new Set(['.doc']);
const PLACEHOLDERS = [
['{{每月租金}}', 'monthlyRent', '每月租金'],
['{{繳款日期}}', 'paymentDay', '繳款日期'],
['{{保證金}}', 'deposit', '保證金'],
];
async function listTemplates() {
await fs.mkdir(TEMPLATE_DIR, { recursive: true });
const entries = await fs.readdir(TEMPLATE_DIR, { withFileTypes: true });
return entries
.filter((entry) => entry.isFile())
.filter((entry) => SUPPORTED_TEMPLATE_EXTENSIONS.has(path.extname(entry.name).toLowerCase()))
.map((entry) => entry.name)
.sort((a, b) => a.localeCompare(b, 'zh-Hant'));
}
async function createContractPdf(input) {
const values = normalizeContractInput(input);
const templatePath = await resolveTemplatePath(input.template);
const workDir = await createWorkDir();
try {
const extension = path.extname(templatePath);
const copiedDocPath = path.join(workDir, `contract-${crypto.randomUUID()}${extension}`);
await fs.copyFile(templatePath, copiedDocPath);
const replacementCounts = await applyPlaceholdersToDoc(copiedDocPath, values);
assertAllPlaceholdersWereFound(replacementCounts);
const pdfPath = await convertToPdf(copiedDocPath, workDir);
const buffer = await fs.readFile(pdfPath);
return {
buffer,
fileName: buildPdfFileName(templatePath),
};
} finally {
await removeWorkDir(workDir);
}
}
function normalizeContractInput(input) {
return {
monthlyRent: normalizePositiveInteger(input.monthlyRent, '每月租金'),
paymentDay: normalizePaymentDay(input.paymentDay),
deposit: normalizePositiveInteger(input.deposit, '保證金'),
};
}
function normalizePositiveInteger(value, label) {
const text = String(value ?? '').trim();
if (!/^[1-9]\d*$/.test(text)) {
throwClientError(`${label}只能輸入正整數。`);
}
return text;
}
function normalizePaymentDay(value) {
const text = String(value ?? '').trim();
const day = Number(text);
if (!/^\d+$/.test(text) || day < 1 || day > 31) {
throwClientError('繳款日期只能輸入 1 到 31。');
}
return text;
}
async function resolveTemplatePath(templateName) {
const name = String(templateName ?? '').trim();
if (!name) {
throwClientError('請選擇 Word 範本。');
}
if (name !== path.basename(name)) {
throwClientError('範本檔名不正確。');
}
const templatePath = path.resolve(TEMPLATE_DIR, name);
if (!isInsideDirectory(TEMPLATE_DIR, templatePath)) {
throwClientError('範本路徑不正確。');
}
if (!SUPPORTED_TEMPLATE_EXTENSIONS.has(path.extname(templatePath).toLowerCase())) {
throwClientError('目前僅支援 .doc 範本。');
}
try {
await fs.access(templatePath);
} catch {
throwClientError('找不到指定的 Word 範本。');
}
return templatePath;
}
async function createWorkDir() {
const workDir = path.resolve(TEMP_DIR, crypto.randomUUID());
if (!isInsideDirectory(TEMP_DIR, workDir)) {
throw new Error('Temporary directory resolved outside of TEMP_DIR.');
}
await fs.mkdir(workDir, { recursive: true });
return workDir;
}
async function removeWorkDir(workDir) {
if (!workDir || !isInsideDirectory(TEMP_DIR, workDir)) {
return;
}
await fs.rm(workDir, { recursive: true, force: true });
}
async function applyPlaceholdersToDoc(docPath, values) {
const buffer = await fs.readFile(docPath);
const counts = new Map();
for (const [placeholder, key, label] of PLACEHOLDERS) {
const value = values[key];
if ([...value].length > [...placeholder].length) {
throwClientError(`${label}的字數不可超過 ${[...placeholder].length} 個字。`);
}
counts.set(placeholder, replaceUtf16Le(buffer, placeholder, value));
}
await fs.writeFile(docPath, buffer);
return counts;
}
function replaceUtf16Le(buffer, placeholder, value) {
const search = Buffer.from(placeholder, 'utf16le');
const replacement = Buffer.from(value.padEnd([...placeholder].length, ' '), 'utf16le');
let count = 0;
let index = buffer.indexOf(search);
while (index !== -1) {
replacement.copy(buffer, index);
count += 1;
index = buffer.indexOf(search, index + replacement.length);
}
return count;
}
function assertAllPlaceholdersWereFound(replacementCounts) {
const missing = [...replacementCounts.entries()]
.filter(([, count]) => count === 0)
.map(([placeholder]) => placeholder);
if (missing.length > 0) {
throwClientError(`範本缺少佔位符:${missing.join('、')}`);
}
}
async function convertToPdf(inputPath, outputDir) {
const libreOfficeProfileDir = path.join(outputDir, 'lo-profile');
await fs.mkdir(libreOfficeProfileDir, { recursive: true });
const args = [
`-env:UserInstallation=${pathToFileURL(libreOfficeProfileDir).href}`,
'--headless',
'--nologo',
'--nofirststartwizard',
'--nolockcheck',
'--convert-to',
'pdf',
'--outdir',
outputDir,
inputPath,
];
await runProcess(SOFFICE_BIN, args);
const expectedPdfPath = path.join(
outputDir,
`${path.basename(inputPath, path.extname(inputPath))}.pdf`,
);
try {
await fs.access(expectedPdfPath);
return expectedPdfPath;
} catch {
const files = await fs.readdir(outputDir);
const pdf = files.find((file) => path.extname(file).toLowerCase() === '.pdf');
if (pdf) {
return path.join(outputDir, pdf);
}
throw new Error('LibreOffice did not create a PDF file.');
}
}
function runProcess(command, args) {
return new Promise((resolve, reject) => {
const child = spawn(command, args, {
windowsHide: true,
env: process.env,
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => {
stdout += chunk.toString();
});
child.stderr.on('data', (chunk) => {
stderr += chunk.toString();
});
child.on('error', (error) => {
reject(new Error(`無法執行 LibreOffice (${command})${error.message}`));
});
child.on('close', (code) => {
if (code === 0) {
resolve();
return;
}
reject(new Error(`LibreOffice 轉檔失敗:${stderr || stdout || `exit code ${code}`}`));
});
});
}
function buildPdfFileName(templatePath) {
const baseName = path.basename(templatePath, path.extname(templatePath));
const timestamp = new Date()
.toISOString()
.replace(/[-:]/g, '')
.replace(/\.\d{3}Z$/, '');
return `${baseName}-${timestamp}.pdf`;
}
function isInsideDirectory(parentDir, targetPath) {
const relative = path.relative(path.resolve(parentDir), path.resolve(targetPath));
return Boolean(relative) && !relative.startsWith('..') && !path.isAbsolute(relative);
}
function throwClientError(message) {
const error = new Error(message);
error.exposeToClient = true;
throw error;
}
module.exports = {
createContractPdf,
listTemplates,
};

Binary file not shown.

Binary file not shown.