-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfill_docx.py
More file actions
62 lines (50 loc) · 1.6 KB
/
fill_docx.py
File metadata and controls
62 lines (50 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
"""
Bytedoc — Fill a DOCX template
Replaces {placeholder} tags in a DOCX template with provided data.
Requires: pip install requests
"""
import os
import requests
API_KEY = os.environ["BYTEDOC_API_KEY"]
BASE_URL = "https://api.bytedoc.dev/v1"
def fill_docx(
template_id: str,
data: dict,
filename: str | None = None,
) -> dict:
"""Fill a DOCX template and return the document metadata."""
response = requests.post(
f"{BASE_URL}/documents/fill-docx",
headers={"Authorization": f"Bearer {API_KEY}"},
json={
"template_id": template_id,
"data": data,
"options": {
"filename": filename,
},
},
)
if not response.ok:
error = response.json()
raise RuntimeError(
f"Bytedoc error ({response.status_code}): {error['error']['message']}"
)
return response.json()
# ---------------------------------------------------------------------------
# Usage — Fill a contract template
# ---------------------------------------------------------------------------
if __name__ == "__main__":
result = fill_docx(
template_id="tpl_docx789",
data={
"client_name": "Jane Smith",
"contract_date": "2026-03-01",
"contract_value": "15,000",
"payment_terms": "Net 30",
"company_name": "Acme Corp",
},
filename="contract-jane-smith.docx",
)
print(f"Document ID : {result['id']}")
print(f"Download URL: {result['download_url']}")
print(f"Expires at : {result['expires_at']}")