-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfill_pdf.py
More file actions
80 lines (64 loc) · 2.01 KB
/
fill_pdf.py
File metadata and controls
80 lines (64 loc) · 2.01 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"""
Bytedoc — Fill a PDF form
Fills AcroForm fields in a PDF template with provided data.
Requires: pip install requests
"""
import os
import sys
import requests
API_KEY = os.environ["BYTEDOC_API_KEY"]
BASE_URL = "https://api.bytedoc.dev/v1"
def fill_pdf(
template_id: str,
data: dict,
flatten: bool = True,
filename: str | None = None,
) -> dict:
"""Fill a PDF template and return the document metadata."""
response = requests.post(
f"{BASE_URL}/documents/fill",
headers={"Authorization": f"Bearer {API_KEY}"},
json={
"template_id": template_id,
"data": data,
"options": {
"flatten": flatten,
"filename": filename,
},
},
)
if not response.ok:
error = response.json()
raise RuntimeError(
f"Bytedoc error ({response.status_code}): {error['error']['message']}"
)
return response.json()
def download_document(download_url: str, output_path: str) -> None:
"""Download a generated document to a local file."""
response = requests.get(
download_url,
headers={"Authorization": f"Bearer {API_KEY}"},
)
response.raise_for_status()
with open(output_path, "wb") as f:
f.write(response.content)
# ---------------------------------------------------------------------------
# Usage
# ---------------------------------------------------------------------------
if __name__ == "__main__":
result = fill_pdf(
template_id="tpl_abc123",
data={
"full_name": "John Doe",
"email": "john@example.com",
"agree_terms": True,
},
flatten=True,
filename="filled-form.pdf",
)
print(f"Document ID : {result['id']}")
print(f"Download URL: {result['download_url']}")
print(f"Expires at : {result['expires_at']}")
# Optionally download the file
download_document(result["download_url"], "filled-form.pdf")
print("Saved to filled-form.pdf")