-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupload_template.py
More file actions
60 lines (45 loc) · 1.79 KB
/
Copy pathupload_template.py
File metadata and controls
60 lines (45 loc) · 1.79 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
"""
Bytedoc — Upload a template
Uploads a PDF, HTML, or DOCX file as a reusable template.
Requires: pip install requests
"""
import os
from pathlib import Path
import requests
API_KEY = os.environ["BYTEDOC_API_KEY"]
BASE_URL = "https://api.bytedoc.dev/v1"
def upload_template(file_path: str, name: str) -> dict:
"""Upload a file as a Bytedoc template and return the template metadata."""
path = Path(file_path)
if not path.exists():
raise FileNotFoundError(f"File not found: {file_path}")
# Determine MIME type from extension
mime_types = {
".pdf": "application/pdf",
".html": "text/html",
".htm": "text/html",
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
}
mime_type = mime_types.get(path.suffix.lower(), "application/octet-stream")
with open(path, "rb") as f:
response = requests.post(
f"{BASE_URL}/templates",
headers={"Authorization": f"Bearer {API_KEY}"},
files={"file": (path.name, f, mime_type)},
data={"name": name},
)
if not response.ok:
error = response.json()
raise RuntimeError(
f"Bytedoc error ({response.status_code}): {error['error']['message']}"
)
return response.json()
# ---------------------------------------------------------------------------
# Usage — Upload a PDF template from disk
# ---------------------------------------------------------------------------
if __name__ == "__main__":
template = upload_template("./invoice-template.pdf", "Invoice Template")
print(f"Template ID : {template['id']}")
print(f"Name : {template['name']}")
print(f"Type : {template['type']}")
print(f"Fields : {', '.join(template.get('fields', []))}")