makespdf 0.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- makespdf/__init__.py +37 -0
- makespdf/client.py +260 -0
- makespdf/errors.py +44 -0
- makespdf/integrations/__init__.py +20 -0
- makespdf/integrations/crewai.py +84 -0
- makespdf/integrations/demo.py +30 -0
- makespdf/integrations/langchain.py +94 -0
- makespdf/integrations/llamaindex.py +93 -0
- makespdf/integrations/mkdocs_plugin.py +338 -0
- makespdf-0.1.1.dist-info/METADATA +175 -0
- makespdf-0.1.1.dist-info/RECORD +13 -0
- makespdf-0.1.1.dist-info/WHEEL +4 -0
- makespdf-0.1.1.dist-info/entry_points.txt +2 -0
makespdf/__init__.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""makesPDF Python client — thin REST wrapper, stdlib only.
|
|
2
|
+
|
|
3
|
+
Plain install has zero required dependencies: every render call is a hosted
|
|
4
|
+
API call (Bearer auth), so billing stays consistent with the web app, CLI,
|
|
5
|
+
and other integrations. Nothing renders offline and no LLM keys are ever
|
|
6
|
+
needed — the client only ever talks to ``/api/v1/*``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from .client import MakesPDFClient, render, render_md, preview, validate_md, validate_preview, verify
|
|
10
|
+
from .errors import (
|
|
11
|
+
MakesPDFError,
|
|
12
|
+
AuthenticationError,
|
|
13
|
+
PaymentRequiredError,
|
|
14
|
+
NotFoundError,
|
|
15
|
+
RateLimitError,
|
|
16
|
+
ValidationError,
|
|
17
|
+
ServerError,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"MakesPDFClient",
|
|
22
|
+
"render",
|
|
23
|
+
"render_md",
|
|
24
|
+
"preview",
|
|
25
|
+
"validate_md",
|
|
26
|
+
"validate_preview",
|
|
27
|
+
"verify",
|
|
28
|
+
"MakesPDFError",
|
|
29
|
+
"AuthenticationError",
|
|
30
|
+
"PaymentRequiredError",
|
|
31
|
+
"NotFoundError",
|
|
32
|
+
"RateLimitError",
|
|
33
|
+
"ValidationError",
|
|
34
|
+
"ServerError",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
__version__ = "0.1.1"
|
makespdf/client.py
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
"""Thin makesPDF API client (stdlib only — no required dependencies).
|
|
2
|
+
|
|
3
|
+
Endpoints wrapped:
|
|
4
|
+
|
|
5
|
+
- ``render_md`` -> ``POST /api/v1/md`` (Markdown to PDF)
|
|
6
|
+
- ``render`` -> ``POST /api/v1/render`` (stored templateId or inline DSL)
|
|
7
|
+
- ``preview`` -> ``POST /api/v1/preview`` (inline DSL draft, free)
|
|
8
|
+
- ``validate_md`` -> ``POST /api/v1/md/validate`` (cheap pre-flight)
|
|
9
|
+
- ``validate_preview`` -> ``POST /api/v1/preview/validate`` (cheap pre-flight)
|
|
10
|
+
- ``verify`` -> ``POST /api/v1/pdf/validate`` (veraPDF compliance check)
|
|
11
|
+
|
|
12
|
+
Auth is a Bearer API key (``MAKESPDF_API_KEY`` env or constructor arg).
|
|
13
|
+
Retries: 429 and 5xx are retried up to ``max_retries`` with exponential
|
|
14
|
+
backoff, honouring ``Retry-After`` when the server sends it. Other 4xx are
|
|
15
|
+
raised immediately — retrying them burns rate limit for nothing.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import base64
|
|
19
|
+
import json
|
|
20
|
+
import os
|
|
21
|
+
import time
|
|
22
|
+
import urllib.error
|
|
23
|
+
import urllib.request
|
|
24
|
+
|
|
25
|
+
from .errors import (
|
|
26
|
+
AuthenticationError,
|
|
27
|
+
MakesPDFError,
|
|
28
|
+
NotFoundError,
|
|
29
|
+
PaymentRequiredError,
|
|
30
|
+
RateLimitError,
|
|
31
|
+
ServerError,
|
|
32
|
+
ValidationError,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
DEFAULT_BASE_URL = "https://makespdf.com"
|
|
36
|
+
DEFAULT_TIMEOUT = 30
|
|
37
|
+
DEFAULT_MAX_RETRIES = 3
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _sleep(seconds):
|
|
41
|
+
time.sleep(seconds)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class MakesPDFClient:
|
|
45
|
+
"""Bearer-authed client for the makesPDF hosted API."""
|
|
46
|
+
|
|
47
|
+
def __init__(self, api_key=None, base_url=None, timeout=DEFAULT_TIMEOUT,
|
|
48
|
+
max_retries=DEFAULT_MAX_RETRIES):
|
|
49
|
+
key = api_key or os.environ.get("MAKESPDF_API_KEY", "")
|
|
50
|
+
self.api_key = key.strip()
|
|
51
|
+
self.base_url = (base_url or os.environ.get("MAKESPDF_BASE_URL")
|
|
52
|
+
or DEFAULT_BASE_URL).rstrip("/")
|
|
53
|
+
self.timeout = timeout
|
|
54
|
+
self.max_retries = max_retries
|
|
55
|
+
|
|
56
|
+
def _headers(self, accept_pdf=False, require_auth=True):
|
|
57
|
+
if require_auth and not self.api_key:
|
|
58
|
+
raise AuthenticationError(
|
|
59
|
+
"Missing API key: pass api_key or set MAKESPDF_API_KEY. "
|
|
60
|
+
"Mint one at https://makespdf.com/settings/api-keys.")
|
|
61
|
+
headers = {"Content-Type": "application/json"}
|
|
62
|
+
if self.api_key:
|
|
63
|
+
headers["Authorization"] = "Bearer " + self.api_key
|
|
64
|
+
if accept_pdf:
|
|
65
|
+
headers["Accept"] = "application/pdf"
|
|
66
|
+
return headers
|
|
67
|
+
|
|
68
|
+
def _post(self, path, payload, *, accept_pdf=False, require_auth=True):
|
|
69
|
+
body = json.dumps(payload).encode("utf-8")
|
|
70
|
+
headers = self._headers(accept_pdf=accept_pdf, require_auth=require_auth)
|
|
71
|
+
last_error = None
|
|
72
|
+
for attempt in range(self.max_retries + 1):
|
|
73
|
+
req = urllib.request.Request(self.base_url + path, data=body,
|
|
74
|
+
headers=headers, method="POST")
|
|
75
|
+
try:
|
|
76
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as res:
|
|
77
|
+
raw = res.read()
|
|
78
|
+
ctype = (res.headers.get("Content-Type") or "")
|
|
79
|
+
if "application/json" in ctype:
|
|
80
|
+
return json.loads(raw.decode("utf-8"))
|
|
81
|
+
return raw
|
|
82
|
+
except urllib.error.HTTPError as exc:
|
|
83
|
+
last_error = exc
|
|
84
|
+
raw = _read_error_body(exc)
|
|
85
|
+
status = exc.code
|
|
86
|
+
retry_after = _retry_after(exc)
|
|
87
|
+
parsed = _parse_json_body(raw)
|
|
88
|
+
if status == 429 or status >= 500:
|
|
89
|
+
if attempt < self.max_retries:
|
|
90
|
+
_sleep(retry_after if retry_after is not None
|
|
91
|
+
else 2 ** attempt)
|
|
92
|
+
continue
|
|
93
|
+
raise _map_error(status, parsed, raw, retry_after)
|
|
94
|
+
except urllib.error.URLError as exc:
|
|
95
|
+
# Network-level failure (DNS, refused, TLS): retry like a 5xx,
|
|
96
|
+
# then surface as ServerError so callers have one retryable type.
|
|
97
|
+
last_error = exc
|
|
98
|
+
if attempt < self.max_retries:
|
|
99
|
+
_sleep(2 ** attempt)
|
|
100
|
+
continue
|
|
101
|
+
raise ServerError("Network error calling makesPDF: %s" % exc,
|
|
102
|
+
body=str(exc))
|
|
103
|
+
raise ServerError("Request failed after retries: %s" % last_error,
|
|
104
|
+
body=str(last_error))
|
|
105
|
+
|
|
106
|
+
# -- render calls (return PDF bytes) ----------------------------------
|
|
107
|
+
|
|
108
|
+
def render_md(self, markdown, options=None):
|
|
109
|
+
"""Render Markdown to PDF bytes via ``POST /api/v1/md``."""
|
|
110
|
+
payload = {"markdown": markdown}
|
|
111
|
+
if options:
|
|
112
|
+
payload["options"] = options
|
|
113
|
+
result = self._post("/api/v1/md", payload, accept_pdf=True)
|
|
114
|
+
return _expect_bytes(result, "/api/v1/md")
|
|
115
|
+
|
|
116
|
+
def render(self, template_id=None, dsl=None, data=None, options=None):
|
|
117
|
+
"""Render production PDF bytes via ``POST /api/v1/render``.
|
|
118
|
+
|
|
119
|
+
Pass exactly one of ``template_id`` (saved/library template) or
|
|
120
|
+
``dsl`` (inline builder-DSL script). ``data`` fills ``{{vars}}``.
|
|
121
|
+
"""
|
|
122
|
+
if (template_id is None) == (dsl is None):
|
|
123
|
+
raise ValidationError(
|
|
124
|
+
"Provide exactly one of: template_id, dsl")
|
|
125
|
+
payload = {"templateId": template_id} if template_id is not None \
|
|
126
|
+
else {"dsl": dsl}
|
|
127
|
+
if data is not None:
|
|
128
|
+
payload["data"] = data
|
|
129
|
+
if options:
|
|
130
|
+
payload["options"] = options
|
|
131
|
+
result = self._post("/api/v1/render", payload, accept_pdf=True)
|
|
132
|
+
return _expect_bytes(result, "/api/v1/render")
|
|
133
|
+
|
|
134
|
+
def preview(self, dsl, data=None, options=None):
|
|
135
|
+
"""Render a draft PDF via ``POST /api/v1/preview`` (free, watermarked)."""
|
|
136
|
+
payload = {"dsl": dsl}
|
|
137
|
+
if data is not None:
|
|
138
|
+
payload["data"] = data
|
|
139
|
+
if options:
|
|
140
|
+
payload["options"] = options
|
|
141
|
+
result = self._post("/api/v1/preview", payload, accept_pdf=True)
|
|
142
|
+
return _expect_bytes(result, "/api/v1/preview")
|
|
143
|
+
|
|
144
|
+
# -- validate calls (return parsed JSON dicts) -------------------------
|
|
145
|
+
|
|
146
|
+
def validate_md(self, markdown, options=None):
|
|
147
|
+
"""Pre-flight Markdown accessibility check (no rendering)."""
|
|
148
|
+
payload = {"markdown": markdown}
|
|
149
|
+
if options:
|
|
150
|
+
payload["options"] = options
|
|
151
|
+
return self._post("/api/v1/md/validate", payload)
|
|
152
|
+
|
|
153
|
+
def validate_preview(self, dsl, data=None):
|
|
154
|
+
"""Pre-flight DSL catalog + accessibility check (no rendering)."""
|
|
155
|
+
payload = {"dsl": dsl}
|
|
156
|
+
if data is not None:
|
|
157
|
+
payload["data"] = data
|
|
158
|
+
return self._post("/api/v1/preview/validate", payload)
|
|
159
|
+
|
|
160
|
+
def verify(self, pdf_bytes):
|
|
161
|
+
"""veraPDF PDF/A + PDF/UA compliance check for existing PDF bytes."""
|
|
162
|
+
payload = {"pdfBase64": base64.b64encode(bytes(pdf_bytes)).decode("ascii")}
|
|
163
|
+
# /pdf/validate is the auth-policy carve-out: reachable without a key
|
|
164
|
+
# (per-IP rate limit), so auth is optional here but sent when present.
|
|
165
|
+
return self._post("/api/v1/pdf/validate", payload, require_auth=False)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _default_client():
|
|
169
|
+
return MakesPDFClient()
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def render_md(markdown, options=None, client=None):
|
|
173
|
+
"""Module convenience: render Markdown with the default (env) client."""
|
|
174
|
+
return (client or _default_client()).render_md(markdown, options)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def render(template_id=None, dsl=None, data=None, options=None, client=None):
|
|
178
|
+
"""Module convenience: production render with the default (env) client."""
|
|
179
|
+
return (client or _default_client()).render(template_id, dsl, data, options)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def preview(dsl, data=None, options=None, client=None):
|
|
183
|
+
"""Module convenience: draft preview with the default (env) client."""
|
|
184
|
+
return (client or _default_client()).preview(dsl, data, options)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def validate_md(markdown, options=None, client=None):
|
|
188
|
+
"""Module convenience: Markdown pre-flight with the default client."""
|
|
189
|
+
return (client or _default_client()).validate_md(markdown, options)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def validate_preview(dsl, data=None, client=None):
|
|
193
|
+
"""Module convenience: DSL pre-flight with the default client."""
|
|
194
|
+
return (client or _default_client()).validate_preview(dsl, data)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def verify(pdf_bytes, client=None):
|
|
198
|
+
"""Module convenience: veraPDF check with the default client."""
|
|
199
|
+
return (client or _default_client()).verify(pdf_bytes)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _read_error_body(exc):
|
|
203
|
+
try:
|
|
204
|
+
return exc.read()
|
|
205
|
+
except Exception:
|
|
206
|
+
return b""
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _parse_json_body(raw):
|
|
210
|
+
try:
|
|
211
|
+
text = (raw or b"").decode("utf-8")
|
|
212
|
+
return json.loads(text) if text else {}
|
|
213
|
+
except Exception:
|
|
214
|
+
return {}
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _retry_after(exc):
|
|
218
|
+
try:
|
|
219
|
+
value = exc.headers.get("Retry-After")
|
|
220
|
+
return int(value) if value is not None else None
|
|
221
|
+
except (TypeError, ValueError):
|
|
222
|
+
return None
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _map_error(status, parsed, raw, retry_after):
|
|
226
|
+
body_text = None
|
|
227
|
+
try:
|
|
228
|
+
body_text = (raw or b"").decode("utf-8") or None
|
|
229
|
+
except Exception:
|
|
230
|
+
body_text = None
|
|
231
|
+
details = parsed.get("details") if isinstance(parsed, dict) else None
|
|
232
|
+
message = None
|
|
233
|
+
if isinstance(parsed, dict):
|
|
234
|
+
message = parsed.get("error") or parsed.get("message")
|
|
235
|
+
if not message:
|
|
236
|
+
message = "makesPDF request failed with status %s" % status
|
|
237
|
+
if body_text:
|
|
238
|
+
message += ": %s" % body_text[:300]
|
|
239
|
+
kwargs = {"status": status, "details": details or [], "body": body_text}
|
|
240
|
+
if status == 401:
|
|
241
|
+
return AuthenticationError(message, **kwargs)
|
|
242
|
+
if status == 402:
|
|
243
|
+
return PaymentRequiredError(message, **kwargs)
|
|
244
|
+
if status == 404:
|
|
245
|
+
return NotFoundError(message, **kwargs)
|
|
246
|
+
if status == 429:
|
|
247
|
+
return RateLimitError(message, retry_after=retry_after, **kwargs)
|
|
248
|
+
if status == 400:
|
|
249
|
+
return ValidationError(message, **kwargs)
|
|
250
|
+
if status >= 500:
|
|
251
|
+
return ServerError(message, **kwargs)
|
|
252
|
+
return MakesPDFError(message, **kwargs)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _expect_bytes(result, path):
|
|
256
|
+
if isinstance(result, (bytes, bytearray)):
|
|
257
|
+
return bytes(result)
|
|
258
|
+
raise ServerError(
|
|
259
|
+
"Unexpected JSON response from %s (wanted PDF bytes)" % path,
|
|
260
|
+
body=json.dumps(result)[:300] if isinstance(result, dict) else str(result))
|
makespdf/errors.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Exception hierarchy for the makesPDF client.
|
|
2
|
+
|
|
3
|
+
Every non-2xx API response maps to one of these. The original response body
|
|
4
|
+
(text) and parsed ``details`` list (when the server sent one) are preserved
|
|
5
|
+
so callers can log or surface them without re-parsing.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class MakesPDFError(Exception):
|
|
10
|
+
"""Base class for all makesPDF client errors."""
|
|
11
|
+
|
|
12
|
+
def __init__(self, message, *, status=None, details=None, body=None):
|
|
13
|
+
super().__init__(message)
|
|
14
|
+
self.status = status
|
|
15
|
+
self.details = details or []
|
|
16
|
+
self.body = body
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class AuthenticationError(MakesPDFError):
|
|
20
|
+
"""401 — missing, malformed, or revoked Bearer token."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class PaymentRequiredError(MakesPDFError):
|
|
24
|
+
"""402 — account out of credits. Top up at /settings/billing."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class NotFoundError(MakesPDFError):
|
|
28
|
+
"""404 — unknown templateId, or not owned by this key."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class RateLimitError(MakesPDFError):
|
|
32
|
+
"""429 — per-key rate limit hit. Honour ``retry_after`` when present."""
|
|
33
|
+
|
|
34
|
+
def __init__(self, message, *, status=None, details=None, body=None, retry_after=None):
|
|
35
|
+
super().__init__(message, status=status, details=details, body=body)
|
|
36
|
+
self.retry_after = retry_after
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class ValidationError(MakesPDFError):
|
|
40
|
+
"""400 — malformed payload, bad DSL, failed catalog validation."""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class ServerError(MakesPDFError):
|
|
44
|
+
"""5xx — transient server failure. Safe to retry with backoff."""
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Optional framework integrations (all lazy — see trap note below).
|
|
2
|
+
|
|
3
|
+
TRAP (from the task): mkdocs-as-extra vs separate package on import-cycle
|
|
4
|
+
risk. Decision: ship every integration — langchain, llamaindex, crewai,
|
|
5
|
+
mkdocs — as an *extra* in this one package, with two rules that remove the
|
|
6
|
+
cycle risk:
|
|
7
|
+
|
|
8
|
+
1. ``makespdf.integrations`` imports NOTHING at package import time (this
|
|
9
|
+
file is empty on purpose). Each submodule imports only stdlib +
|
|
10
|
+
``makespdf.client`` at top level.
|
|
11
|
+
2. Third-party imports (``langchain_core``, ``llama_index``, ``crewai``,
|
|
12
|
+
``mkdocs``) happen INSIDE the factory function that needs them, so
|
|
13
|
+
importing ``makespdf`` never imports a framework, and importing one
|
|
14
|
+
framework shim never imports another.
|
|
15
|
+
|
|
16
|
+
A missing extra raises a plain ``ImportError`` naming the pip extra to add
|
|
17
|
+
(e.g. ``pip install makespdf[langchain]``), never an obscure AttributeError.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
__all__ = []
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""CrewAI tool shim (requires ``pip install makespdf[crewai]``).
|
|
2
|
+
|
|
3
|
+
Two tools (the trap ceiling is 1-2 functions): markdown -> PDF via
|
|
4
|
+
``POST /api/v1/md`` and stored-template/inline-DSL -> PDF via
|
|
5
|
+
``POST /api/v1/render``.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _parse_data_json(data_json):
|
|
12
|
+
"""Parse the ``data_json`` tool arg to a dict for ``{{vars}}``.
|
|
13
|
+
|
|
14
|
+
Agents frequently hand back malformed JSON or an already-decoded dict,
|
|
15
|
+
so fail fast with ``ValidationError`` (not raw ``JSONDecodeError`` /
|
|
16
|
+
``TypeError``) and pass dicts straight through.
|
|
17
|
+
"""
|
|
18
|
+
from ..errors import ValidationError
|
|
19
|
+
|
|
20
|
+
if data_json is None or data_json == "":
|
|
21
|
+
return {}
|
|
22
|
+
if isinstance(data_json, dict):
|
|
23
|
+
return data_json
|
|
24
|
+
if not isinstance(data_json, str):
|
|
25
|
+
raise ValidationError(
|
|
26
|
+
"data_json must be a JSON object string or dict, got %s"
|
|
27
|
+
% type(data_json).__name__)
|
|
28
|
+
try:
|
|
29
|
+
parsed = json.loads(data_json)
|
|
30
|
+
except ValueError as exc:
|
|
31
|
+
raise ValidationError(
|
|
32
|
+
"data_json is not valid JSON: %s" % exc) from exc
|
|
33
|
+
if not isinstance(parsed, dict):
|
|
34
|
+
raise ValidationError(
|
|
35
|
+
"data_json must decode to a JSON object (got %s)"
|
|
36
|
+
% type(parsed).__name__)
|
|
37
|
+
return parsed
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def get_crewai_tools(client=None):
|
|
41
|
+
"""Return CrewAI tools for PDF rendering."""
|
|
42
|
+
try:
|
|
43
|
+
from crewai.tools import BaseTool
|
|
44
|
+
except ImportError as exc:
|
|
45
|
+
raise ImportError(
|
|
46
|
+
"makespdf crewai integration needs the crewai extra: "
|
|
47
|
+
"pip install makespdf[crewai]") from exc
|
|
48
|
+
|
|
49
|
+
from ..client import MakesPDFClient
|
|
50
|
+
|
|
51
|
+
pdf_client = client or MakesPDFClient()
|
|
52
|
+
|
|
53
|
+
class RenderMarkdownTool(BaseTool):
|
|
54
|
+
name: str = "makespdf_render_md"
|
|
55
|
+
description: str = "Render GitHub-flavoured Markdown to a PDF file. Returns the file path."
|
|
56
|
+
|
|
57
|
+
def _run(self, markdown: str) -> str:
|
|
58
|
+
import tempfile
|
|
59
|
+
pdf = pdf_client.render_md(markdown)
|
|
60
|
+
with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as fh:
|
|
61
|
+
fh.write(pdf)
|
|
62
|
+
return fh.name
|
|
63
|
+
|
|
64
|
+
class RenderTemplateTool(BaseTool):
|
|
65
|
+
name: str = "makespdf_render"
|
|
66
|
+
description: str = (
|
|
67
|
+
"Render a stored templateId or inline DSL to a PDF file. "
|
|
68
|
+
"Provide exactly one of template_id, dsl; data_json is a "
|
|
69
|
+
"JSON object for {{vars}}. Returns the file path.")
|
|
70
|
+
|
|
71
|
+
def _run(self, template_id: str = "", dsl: str = "",
|
|
72
|
+
data_json: str = "{}") -> str:
|
|
73
|
+
import tempfile
|
|
74
|
+
data = _parse_data_json(data_json)
|
|
75
|
+
pdf = pdf_client.render(
|
|
76
|
+
template_id=(template_id.strip() or None) if isinstance(template_id, str) else template_id,
|
|
77
|
+
dsl=(dsl if dsl.strip() else None) if isinstance(dsl, str) else dsl,
|
|
78
|
+
data=data,
|
|
79
|
+
)
|
|
80
|
+
with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as fh:
|
|
81
|
+
fh.write(pdf)
|
|
82
|
+
return fh.name
|
|
83
|
+
|
|
84
|
+
return [RenderMarkdownTool(), RenderTemplateTool()]
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Shared demo data for every agent-runtime example (single source).
|
|
2
|
+
|
|
3
|
+
TRAP (from MAK-14): don't fork demo data per runtime. Every framework
|
|
4
|
+
example — LangChain, LlamaIndex, CrewAI, LangGraph (python) and Vercel AI
|
|
5
|
+
SDK (JS) — renders THESE values, imported from here on the python side and
|
|
6
|
+
mirrored literally on the JS side (the site page
|
|
7
|
+
``apps/web/src/routes/docs/integrations/vercel-ai-sdk.tsx`` and its markdown
|
|
8
|
+
twin ``apps/web/src/server/docs-markdown/integrations-vercel-ai-sdk.ts``,
|
|
9
|
+
which note the mirror).
|
|
10
|
+
|
|
11
|
+
The markdown demo is the smallest markdown that still exercises the
|
|
12
|
+
``/md`` path (heading + bold). The DSL demo is the smallest builder-DSL
|
|
13
|
+
script the ``/preview`` + ``/render`` pipeline accepts (a ``doc`` with a
|
|
14
|
+
``sampleData`` fallback, per ``skills/pdf-template-author.md``); ``DATA_DEMO``
|
|
15
|
+
overrides its ``{{name}}`` so examples also exercise the ``data`` field.
|
|
16
|
+
``TEMPLATE_ID_DEMO`` is the stable library slug every caller can read.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
MARKDOWN_DEMO = "# Invoice INV-2026-001\n\nHello **Ada** — total **$7,095.00**.\n"
|
|
20
|
+
|
|
21
|
+
DSL_DEMO = (
|
|
22
|
+
'const template = doc({ size: "A4" }, page(col(s("Hello {{name}}"))));\n'
|
|
23
|
+
"const sampleData = { name: \"World\" };\n"
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
DATA_DEMO = {"name": "Ada"}
|
|
27
|
+
|
|
28
|
+
TEMPLATE_ID_DEMO = "invoice-classic"
|
|
29
|
+
|
|
30
|
+
__all__ = ["MARKDOWN_DEMO", "DSL_DEMO", "DATA_DEMO", "TEMPLATE_ID_DEMO"]
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""LangChain tool shim (requires ``pip install makespdf[langchain]``).
|
|
2
|
+
|
|
3
|
+
Two tools (the trap ceiling is 1-2 functions — no more):
|
|
4
|
+
``makespdf_render_md`` (Markdown -> PDF via ``POST /api/v1/md``) and
|
|
5
|
+
``makespdf_render`` (stored ``templateId`` or inline ``dsl`` via
|
|
6
|
+
``POST /api/v1/render``).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _parse_data_json(data_json):
|
|
13
|
+
"""Parse the ``data_json`` tool arg to a dict for ``{{vars}}``.
|
|
14
|
+
|
|
15
|
+
Agents frequently hand back malformed JSON or an already-decoded dict,
|
|
16
|
+
so fail fast with ``ValidationError`` (not raw ``JSONDecodeError`` /
|
|
17
|
+
``TypeError``) and pass dicts straight through.
|
|
18
|
+
"""
|
|
19
|
+
from ..errors import ValidationError
|
|
20
|
+
|
|
21
|
+
if data_json is None or data_json == "":
|
|
22
|
+
return {}
|
|
23
|
+
if isinstance(data_json, dict):
|
|
24
|
+
return data_json
|
|
25
|
+
if not isinstance(data_json, str):
|
|
26
|
+
raise ValidationError(
|
|
27
|
+
"data_json must be a JSON object string or dict, got %s"
|
|
28
|
+
% type(data_json).__name__)
|
|
29
|
+
try:
|
|
30
|
+
parsed = json.loads(data_json)
|
|
31
|
+
except ValueError as exc:
|
|
32
|
+
raise ValidationError(
|
|
33
|
+
"data_json is not valid JSON: %s" % exc) from exc
|
|
34
|
+
if not isinstance(parsed, dict):
|
|
35
|
+
raise ValidationError(
|
|
36
|
+
"data_json must decode to a JSON object (got %s)"
|
|
37
|
+
% type(parsed).__name__)
|
|
38
|
+
return parsed
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def get_langchain_tools(client=None):
|
|
42
|
+
"""Return LangChain tools for PDF rendering.
|
|
43
|
+
|
|
44
|
+
The heavy ``langchain_core`` import stays inside this factory so plain
|
|
45
|
+
``import makespdf`` never touches LangChain (see integrations docstring).
|
|
46
|
+
"""
|
|
47
|
+
try:
|
|
48
|
+
from langchain_core.tools import tool
|
|
49
|
+
except ImportError as exc:
|
|
50
|
+
raise ImportError(
|
|
51
|
+
"makespdf langchain integration needs the langchain extra: "
|
|
52
|
+
"pip install makespdf[langchain]") from exc
|
|
53
|
+
|
|
54
|
+
from ..client import MakesPDFClient
|
|
55
|
+
|
|
56
|
+
pdf_client = client or MakesPDFClient()
|
|
57
|
+
|
|
58
|
+
@tool("makespdf_render_md")
|
|
59
|
+
def render_md_tool(markdown: str) -> str:
|
|
60
|
+
"""Render Markdown to PDF. Returns the output file path.
|
|
61
|
+
|
|
62
|
+
Args:
|
|
63
|
+
markdown: GitHub-flavoured Markdown source (max 200KB of text;
|
|
64
|
+
inline ``data:`` image payloads are excluded from that budget,
|
|
65
|
+
the request body is capped at 15MB).
|
|
66
|
+
"""
|
|
67
|
+
import tempfile
|
|
68
|
+
pdf = pdf_client.render_md(markdown)
|
|
69
|
+
with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as fh:
|
|
70
|
+
fh.write(pdf)
|
|
71
|
+
return fh.name
|
|
72
|
+
|
|
73
|
+
@tool("makespdf_render")
|
|
74
|
+
def render_tool(template_id: str = "", dsl: str = "",
|
|
75
|
+
data_json: str = "{}") -> str:
|
|
76
|
+
"""Render a stored template or inline DSL to PDF. Returns the file path.
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
template_id: Library/owned template id (e.g. "invoice-classic").
|
|
80
|
+
dsl: Inline builder-DSL script (alternative to template_id).
|
|
81
|
+
data_json: JSON object string filling {{vars}} (default "{}").
|
|
82
|
+
"""
|
|
83
|
+
import tempfile
|
|
84
|
+
data = _parse_data_json(data_json)
|
|
85
|
+
pdf = pdf_client.render(
|
|
86
|
+
template_id=(template_id.strip() or None) if isinstance(template_id, str) else template_id,
|
|
87
|
+
dsl=(dsl if dsl.strip() else None) if isinstance(dsl, str) else dsl,
|
|
88
|
+
data=data,
|
|
89
|
+
)
|
|
90
|
+
with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as fh:
|
|
91
|
+
fh.write(pdf)
|
|
92
|
+
return fh.name
|
|
93
|
+
|
|
94
|
+
return [render_md_tool, render_tool]
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""LlamaIndex tool shim (requires ``pip install makespdf[llamaindex]``).
|
|
2
|
+
|
|
3
|
+
Two FunctionTools (the trap ceiling is 1-2 functions): markdown -> PDF via
|
|
4
|
+
``POST /api/v1/md`` and stored-template/inline-DSL -> PDF via
|
|
5
|
+
``POST /api/v1/render``.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _parse_data_json(data_json):
|
|
12
|
+
"""Parse the ``data_json`` tool arg to a dict for ``{{vars}}``.
|
|
13
|
+
|
|
14
|
+
Agents frequently hand back malformed JSON or an already-decoded dict,
|
|
15
|
+
so fail fast with ``ValidationError`` (not raw ``JSONDecodeError`` /
|
|
16
|
+
``TypeError``) and pass dicts straight through.
|
|
17
|
+
"""
|
|
18
|
+
from ..errors import ValidationError
|
|
19
|
+
|
|
20
|
+
if data_json is None or data_json == "":
|
|
21
|
+
return {}
|
|
22
|
+
if isinstance(data_json, dict):
|
|
23
|
+
return data_json
|
|
24
|
+
if not isinstance(data_json, str):
|
|
25
|
+
raise ValidationError(
|
|
26
|
+
"data_json must be a JSON object string or dict, got %s"
|
|
27
|
+
% type(data_json).__name__)
|
|
28
|
+
try:
|
|
29
|
+
parsed = json.loads(data_json)
|
|
30
|
+
except ValueError as exc:
|
|
31
|
+
raise ValidationError(
|
|
32
|
+
"data_json is not valid JSON: %s" % exc) from exc
|
|
33
|
+
if not isinstance(parsed, dict):
|
|
34
|
+
raise ValidationError(
|
|
35
|
+
"data_json must decode to a JSON object (got %s)"
|
|
36
|
+
% type(parsed).__name__)
|
|
37
|
+
return parsed
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def get_llamaindex_tools(client=None):
|
|
41
|
+
"""Return LlamaIndex FunctionTools for PDF rendering."""
|
|
42
|
+
try:
|
|
43
|
+
from llama_index.core.tools import FunctionTool
|
|
44
|
+
except ImportError as exc:
|
|
45
|
+
raise ImportError(
|
|
46
|
+
"makespdf llamaindex integration needs the llamaindex extra: "
|
|
47
|
+
"pip install makespdf[llamaindex]") from exc
|
|
48
|
+
|
|
49
|
+
from ..client import MakesPDFClient
|
|
50
|
+
|
|
51
|
+
pdf_client = client or MakesPDFClient()
|
|
52
|
+
|
|
53
|
+
def render_markdown_to_pdf(markdown: str) -> str:
|
|
54
|
+
"""Render Markdown to PDF. Returns the output file path."""
|
|
55
|
+
import tempfile
|
|
56
|
+
pdf = pdf_client.render_md(markdown)
|
|
57
|
+
with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as fh:
|
|
58
|
+
fh.write(pdf)
|
|
59
|
+
return fh.name
|
|
60
|
+
|
|
61
|
+
def render_template_to_pdf(template_id: str = "", dsl: str = "",
|
|
62
|
+
data_json: str = "{}") -> str:
|
|
63
|
+
"""Render a stored template or inline DSL to PDF. Returns the file path.
|
|
64
|
+
|
|
65
|
+
Provide exactly one of template_id ("invoice-classic") or dsl
|
|
66
|
+
(builder-DSL script); data_json is a JSON object for {{vars}}.
|
|
67
|
+
"""
|
|
68
|
+
import tempfile
|
|
69
|
+
data = _parse_data_json(data_json)
|
|
70
|
+
pdf = pdf_client.render(
|
|
71
|
+
template_id=(template_id.strip() or None) if isinstance(template_id, str) else template_id,
|
|
72
|
+
dsl=(dsl if dsl.strip() else None) if isinstance(dsl, str) else dsl,
|
|
73
|
+
data=data,
|
|
74
|
+
)
|
|
75
|
+
with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as fh:
|
|
76
|
+
fh.write(pdf)
|
|
77
|
+
return fh.name
|
|
78
|
+
|
|
79
|
+
return [
|
|
80
|
+
FunctionTool.from_defaults(
|
|
81
|
+
fn=render_markdown_to_pdf,
|
|
82
|
+
name="makespdf_render_md",
|
|
83
|
+
description="Render GitHub-flavoured Markdown to a PDF file. Returns the file path.",
|
|
84
|
+
),
|
|
85
|
+
FunctionTool.from_defaults(
|
|
86
|
+
fn=render_template_to_pdf,
|
|
87
|
+
name="makespdf_render",
|
|
88
|
+
description=(
|
|
89
|
+
"Render a stored templateId or inline DSL to a PDF file. "
|
|
90
|
+
"Provide exactly one of template_id, dsl; data_json is a "
|
|
91
|
+
"JSON object for {{vars}}. Returns the file path."),
|
|
92
|
+
),
|
|
93
|
+
]
|
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
"""MkDocs plugin (requires ``pip install makespdf[mkdocs]``).
|
|
2
|
+
|
|
3
|
+
Shipped as an extra in this package (not a separate PyPI project): the
|
|
4
|
+
module imports ``mkdocs`` only inside the hook/plugin entry points, so a
|
|
5
|
+
docs build without the extra never touches it and there is no import cycle
|
|
6
|
+
(see ``makespdf.integrations`` docstring for the rule).
|
|
7
|
+
|
|
8
|
+
Wiring (``mkdocs.yml`` — the ``mkdocs.plugins`` entry point registered in
|
|
9
|
+
``pyproject.toml`` makes the ``makespdf`` name resolve after install)::
|
|
10
|
+
|
|
11
|
+
plugins:
|
|
12
|
+
- search
|
|
13
|
+
- makespdf
|
|
14
|
+
extra:
|
|
15
|
+
makespdf: { pageSize: A4 } # optional; passed as /md `options`
|
|
16
|
+
|
|
17
|
+
``MakesPDFPlugin`` (module attribute, resolved lazily via ``__getattr__``
|
|
18
|
+
so importing this module still never imports ``mkdocs``) is what the entry
|
|
19
|
+
point loads. ``get_mkdocs_plugin(client, options)`` is the same behaviour
|
|
20
|
+
as a factory for callers that want to inject a client. ``on_post_build_hook``
|
|
21
|
+
is the underlying hook both use; MkDocs ``hooks:`` takes file paths, not
|
|
22
|
+
``module:func`` strings, so to use it as a hook (instead of the plugin) add
|
|
23
|
+
a one-line shim file, e.g. ``docs/hooks/makespdf_hook.py``::
|
|
24
|
+
|
|
25
|
+
from makespdf.integrations.mkdocs_plugin import on_post_build_hook
|
|
26
|
+
|
|
27
|
+
and list it under ``hooks:`` in ``mkdocs.yml``.
|
|
28
|
+
|
|
29
|
+
Per-page front-matter (YAML block between leading ``---`` lines):
|
|
30
|
+
|
|
31
|
+
- ``pdf: false`` — skip this page (no PDF written, billed for nothing).
|
|
32
|
+
- ``pdf-template: <slug>`` (or ``pdf_template:``) — render this page via
|
|
33
|
+
``POST /api/v1/render`` with ``templateId=<slug>`` instead of ``/md``.
|
|
34
|
+
The page's remaining front-matter plus ``markdown`` / ``content`` (the
|
|
35
|
+
body) and ``title`` become the template ``data``.
|
|
36
|
+
|
|
37
|
+
Combined mode joins every markdown-rendered page body into one extra PDF::
|
|
38
|
+
|
|
39
|
+
extra:
|
|
40
|
+
makespdf: { pageSize: A4, combined: true } # -> site/combined.pdf
|
|
41
|
+
# combined: all-docs.pdf # custom file name
|
|
42
|
+
# combined_name: all-docs.pdf # same thing, explicit key
|
|
43
|
+
|
|
44
|
+
Pages rendered via ``pdf-template`` are excluded from the combined PDF —
|
|
45
|
+
they go through a different pipeline (``/render``) and cannot be
|
|
46
|
+
concatenated as markdown. ``combined`` / ``combined_name`` / ``pdf_template``
|
|
47
|
+
keys are control keys: they are never forwarded as ``/md`` options.
|
|
48
|
+
|
|
49
|
+
Each built page's source Markdown is otherwise rendered to a sibling
|
|
50
|
+
``.pdf`` via ``POST /api/v1/md`` (one billed render per page, plus one
|
|
51
|
+
more when combined mode is on).
|
|
52
|
+
|
|
53
|
+
Attribution: links to makesPDF from plugin docs carry ``?ref=mkdocs-plugin``
|
|
54
|
+
so docs-driven signups attribute to this integration.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
#: Value appended to makesPDF links in plugin docs (``?ref=<value>``).
|
|
58
|
+
ATTRIBUTION_REF = "mkdocs-plugin"
|
|
59
|
+
|
|
60
|
+
#: Front-matter keys consumed by the plugin (never sent as options/data).
|
|
61
|
+
CONTROL_KEYS = frozenset({"pdf", "pdf-template", "pdf_template"})
|
|
62
|
+
|
|
63
|
+
#: Values of ``pdf:`` that mean "skip this page".
|
|
64
|
+
_SKIP_VALUES = frozenset({"false", "no", "off", "0", "disable", "disabled"})
|
|
65
|
+
|
|
66
|
+
#: Default file name for the combined PDF (at the site root).
|
|
67
|
+
DEFAULT_COMBINED_NAME = "combined.pdf"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _coerce_scalar(value):
|
|
71
|
+
"""Coerce a single-line ``key: value`` front-matter value."""
|
|
72
|
+
text = value.strip()
|
|
73
|
+
if len(text) >= 2 and text[0] == text[-1] and text[0] in ("'", '"'):
|
|
74
|
+
return text[1:-1]
|
|
75
|
+
lowered = text.lower()
|
|
76
|
+
if lowered in ("true", "yes", "on"):
|
|
77
|
+
return True
|
|
78
|
+
if lowered in ("false", "no", "off"):
|
|
79
|
+
return False
|
|
80
|
+
if lowered in ("null", "none", "~", ""):
|
|
81
|
+
return None
|
|
82
|
+
try:
|
|
83
|
+
return int(text)
|
|
84
|
+
except ValueError:
|
|
85
|
+
pass
|
|
86
|
+
try:
|
|
87
|
+
return float(text)
|
|
88
|
+
except ValueError:
|
|
89
|
+
pass
|
|
90
|
+
return text
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def parse_front_matter(text):
|
|
94
|
+
"""Split ``text`` into ``(front_matter, body)``.
|
|
95
|
+
|
|
96
|
+
Only a leading ``---`` block is recognised; without one the whole
|
|
97
|
+
text is the body and the mapping is empty. Values are a minimal
|
|
98
|
+
YAML subset (scalars only — nested maps/lists are ignored), which
|
|
99
|
+
keeps this module dependency-free. An unterminated block is not
|
|
100
|
+
front-matter at all: the text is returned untouched.
|
|
101
|
+
"""
|
|
102
|
+
lines = text.splitlines()
|
|
103
|
+
if not lines or lines[0].strip() != "---":
|
|
104
|
+
return {}, text
|
|
105
|
+
end = None
|
|
106
|
+
for i in range(1, len(lines)):
|
|
107
|
+
if lines[i].strip() in ("---", "..."):
|
|
108
|
+
end = i
|
|
109
|
+
break
|
|
110
|
+
if end is None:
|
|
111
|
+
return {}, text
|
|
112
|
+
front_matter = {}
|
|
113
|
+
for line in lines[1:end]:
|
|
114
|
+
if not line.strip() or line.startswith((" ", "\t")):
|
|
115
|
+
continue
|
|
116
|
+
if line.lstrip().startswith("- "):
|
|
117
|
+
continue
|
|
118
|
+
if ":" not in line:
|
|
119
|
+
continue
|
|
120
|
+
key, _, value = line.partition(":")
|
|
121
|
+
key = key.strip()
|
|
122
|
+
if not key or key.startswith("#"):
|
|
123
|
+
continue
|
|
124
|
+
if not value.strip():
|
|
125
|
+
# Bare `key:` with no scalar opens a nested block (map/list),
|
|
126
|
+
# which this subset parser does not model — ignore it.
|
|
127
|
+
continue
|
|
128
|
+
front_matter[key] = _coerce_scalar(value)
|
|
129
|
+
body = "\n".join(lines[end + 1:])
|
|
130
|
+
return front_matter, body
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def should_skip_page(front_matter):
|
|
134
|
+
"""True when the page opts out via ``pdf: false`` (bool or string)."""
|
|
135
|
+
value = front_matter.get("pdf", True)
|
|
136
|
+
if isinstance(value, bool):
|
|
137
|
+
return not value
|
|
138
|
+
if value is None:
|
|
139
|
+
return False
|
|
140
|
+
return str(value).strip().lower() in _SKIP_VALUES
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def get_template_slug(front_matter, default=None):
|
|
144
|
+
"""Stored-template slug for the page, or ``default`` when unset."""
|
|
145
|
+
slug = front_matter.get("pdf-template", front_matter.get("pdf_template"))
|
|
146
|
+
if isinstance(slug, str) and slug.strip():
|
|
147
|
+
return slug.strip()
|
|
148
|
+
return default
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def page_title(front_matter, body, fallback="Document"):
|
|
152
|
+
"""Best-effort title: front-matter ``title``, first H1, then fallback."""
|
|
153
|
+
title = front_matter.get("title")
|
|
154
|
+
if isinstance(title, str) and title.strip():
|
|
155
|
+
return title.strip()
|
|
156
|
+
for line in body.splitlines():
|
|
157
|
+
stripped = line.strip()
|
|
158
|
+
if stripped.startswith("# "):
|
|
159
|
+
heading = stripped[2:].strip()
|
|
160
|
+
if heading:
|
|
161
|
+
return heading
|
|
162
|
+
return fallback
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def render_page_to_pdf(markdown_text, output_path, client=None, options=None,
|
|
166
|
+
template_id=None, data=None):
|
|
167
|
+
"""Render one page to ``output_path`` (PDF bytes to disk).
|
|
168
|
+
|
|
169
|
+
Default path posts ``markdown_text`` to ``POST /api/v1/md``. With
|
|
170
|
+
``template_id`` the markdown is NOT sent — the page renders via
|
|
171
|
+
``POST /api/v1/render`` with ``data`` (the hook fills it from
|
|
172
|
+
front-matter plus ``markdown`` / ``content`` / ``title``).
|
|
173
|
+
"""
|
|
174
|
+
from ..client import MakesPDFClient
|
|
175
|
+
|
|
176
|
+
pdf_client = client or MakesPDFClient()
|
|
177
|
+
if template_id is not None:
|
|
178
|
+
pdf = pdf_client.render(template_id=template_id, data=data or {})
|
|
179
|
+
else:
|
|
180
|
+
pdf = pdf_client.render_md(markdown_text, options)
|
|
181
|
+
with open(output_path, "wb") as fh:
|
|
182
|
+
fh.write(pdf)
|
|
183
|
+
return output_path
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def iter_markdown_sources(docs_dir):
|
|
187
|
+
"""Sorted ``(source_path, pdf_rel_path)`` pairs under ``docs_dir``."""
|
|
188
|
+
import os
|
|
189
|
+
|
|
190
|
+
pairs = []
|
|
191
|
+
for root, dirs, files in os.walk(docs_dir):
|
|
192
|
+
dirs.sort()
|
|
193
|
+
for name in sorted(files):
|
|
194
|
+
if not name.endswith(".md"):
|
|
195
|
+
continue
|
|
196
|
+
src = os.path.join(root, name)
|
|
197
|
+
rel = os.path.relpath(src, docs_dir)[:-3] + ".pdf"
|
|
198
|
+
pairs.append((src, rel))
|
|
199
|
+
return pairs
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _normalise_combined(combined, combined_name):
|
|
203
|
+
"""Resolve the combined control keys to an output file name or None."""
|
|
204
|
+
if combined is True:
|
|
205
|
+
return combined_name or DEFAULT_COMBINED_NAME
|
|
206
|
+
if isinstance(combined, str) and combined.strip():
|
|
207
|
+
return combined.strip()
|
|
208
|
+
if combined is None and isinstance(combined_name, str) \
|
|
209
|
+
and combined_name.strip():
|
|
210
|
+
# `combined_name` alone enables combined mode (same thing, explicit
|
|
211
|
+
# key). An explicit `combined: false` still disables it.
|
|
212
|
+
return combined_name.strip()
|
|
213
|
+
return None
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def on_post_build_hook(config, client=None, options=None, combined=None):
|
|
217
|
+
"""MkDocs ``on_post_build`` hook: sibling PDF for every ``*.md`` source.
|
|
218
|
+
|
|
219
|
+
When ``options`` is omitted, ``config["extra"]["makespdf"]`` (the
|
|
220
|
+
``extra: makespdf: {...}`` block in ``mkdocs.yml``) is used, so the
|
|
221
|
+
render options live with the docs config. Keys are ``/api/v1/md``
|
|
222
|
+
option names (``pageSize``, ``fontFamily``, ...); the control keys
|
|
223
|
+
``combined`` / ``combined_name`` / ``pdf_template`` are consumed here
|
|
224
|
+
and never forwarded. Returns the list of PDF paths written.
|
|
225
|
+
"""
|
|
226
|
+
import os
|
|
227
|
+
|
|
228
|
+
extra_cfg = (config.get("extra") or {}).get("makespdf") or {}
|
|
229
|
+
if not isinstance(extra_cfg, dict):
|
|
230
|
+
extra_cfg = {}
|
|
231
|
+
merged = dict(extra_cfg)
|
|
232
|
+
if options is not None:
|
|
233
|
+
merged.update(options)
|
|
234
|
+
render_options = {k: v for k, v in merged.items()
|
|
235
|
+
if k not in ("combined", "combined_name", "combinedName",
|
|
236
|
+
"pdf_template", "pdf-template")}
|
|
237
|
+
if not render_options:
|
|
238
|
+
render_options = None
|
|
239
|
+
default_template = merged.get("pdf_template") or merged.get("pdf-template")
|
|
240
|
+
if combined is None:
|
|
241
|
+
combined = merged.get("combined")
|
|
242
|
+
combined_name = (merged.get("combined_name")
|
|
243
|
+
or merged.get("combinedName"))
|
|
244
|
+
combined_out = _normalise_combined(combined, combined_name)
|
|
245
|
+
|
|
246
|
+
docs_dir = config.get("docs_dir", "docs")
|
|
247
|
+
site_dir = config.get("site_dir", "site")
|
|
248
|
+
written = []
|
|
249
|
+
combined_bodies = []
|
|
250
|
+
for src, rel in iter_markdown_sources(docs_dir):
|
|
251
|
+
with open(src, encoding="utf-8") as fh:
|
|
252
|
+
raw = fh.read()
|
|
253
|
+
front_matter, body = parse_front_matter(raw)
|
|
254
|
+
if should_skip_page(front_matter):
|
|
255
|
+
continue
|
|
256
|
+
dest = os.path.join(site_dir, rel)
|
|
257
|
+
os.makedirs(os.path.dirname(dest), exist_ok=True)
|
|
258
|
+
slug = get_template_slug(front_matter, default_template)
|
|
259
|
+
if slug is not None:
|
|
260
|
+
data = {k: v for k, v in front_matter.items()
|
|
261
|
+
if k not in CONTROL_KEYS}
|
|
262
|
+
data.setdefault("markdown", body)
|
|
263
|
+
data.setdefault("content", body)
|
|
264
|
+
data.setdefault("title", page_title(
|
|
265
|
+
front_matter, body,
|
|
266
|
+
fallback=os.path.splitext(os.path.basename(src))[0]))
|
|
267
|
+
render_page_to_pdf(body, dest, client=client,
|
|
268
|
+
template_id=slug, data=data)
|
|
269
|
+
written.append(dest)
|
|
270
|
+
else:
|
|
271
|
+
render_page_to_pdf(body, dest, client=client,
|
|
272
|
+
options=render_options)
|
|
273
|
+
written.append(dest)
|
|
274
|
+
combined_bodies.append(body)
|
|
275
|
+
if combined_out is not None and combined_bodies:
|
|
276
|
+
dest = os.path.join(site_dir, combined_out)
|
|
277
|
+
os.makedirs(os.path.dirname(dest), exist_ok=True)
|
|
278
|
+
combined_md = "\n\n".join(b.strip() for b in combined_bodies) + "\n"
|
|
279
|
+
render_page_to_pdf(combined_md, dest,
|
|
280
|
+
client=client, options=render_options)
|
|
281
|
+
written.append(dest)
|
|
282
|
+
return written
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def get_mkdocs_plugin(client=None, options=None, combined=None):
|
|
286
|
+
"""Return a MkDocs ``BasePlugin`` subclass rendering sibling PDFs."""
|
|
287
|
+
try:
|
|
288
|
+
from mkdocs.plugins import BasePlugin
|
|
289
|
+
except ImportError as exc:
|
|
290
|
+
raise ImportError(
|
|
291
|
+
"makespdf mkdocs integration needs the mkdocs extra: "
|
|
292
|
+
"pip install makespdf[mkdocs]") from exc
|
|
293
|
+
|
|
294
|
+
_client = client
|
|
295
|
+
_options = options
|
|
296
|
+
_combined = combined
|
|
297
|
+
|
|
298
|
+
class MakesPDFPlugin(BasePlugin):
|
|
299
|
+
def on_post_build(self, config):
|
|
300
|
+
# Fall back to the mkdocs.yml `extra: makespdf:` block when the
|
|
301
|
+
# factory was built without explicit options.
|
|
302
|
+
opts = _options
|
|
303
|
+
if opts is None:
|
|
304
|
+
try:
|
|
305
|
+
opts = (config.get("extra") or {}).get("makespdf")
|
|
306
|
+
except AttributeError:
|
|
307
|
+
opts = None
|
|
308
|
+
on_post_build_hook(config, client=_client, options=opts,
|
|
309
|
+
combined=_combined)
|
|
310
|
+
|
|
311
|
+
return MakesPDFPlugin
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _load_plugin_class():
|
|
315
|
+
"""Import ``mkdocs`` late and build the entry-point plugin class."""
|
|
316
|
+
try:
|
|
317
|
+
from mkdocs.plugins import BasePlugin
|
|
318
|
+
except ImportError as exc:
|
|
319
|
+
raise ImportError(
|
|
320
|
+
"makespdf mkdocs integration needs the mkdocs extra: "
|
|
321
|
+
"pip install makespdf[mkdocs]") from exc
|
|
322
|
+
|
|
323
|
+
class MakesPDFPlugin(BasePlugin):
|
|
324
|
+
def on_post_build(self, config):
|
|
325
|
+
on_post_build_hook(config)
|
|
326
|
+
|
|
327
|
+
return MakesPDFPlugin
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def __getattr__(name):
|
|
331
|
+
# PEP 562 lazy attribute: the `mkdocs.plugins` entry point loads
|
|
332
|
+
# `makespdf.integrations.mkdocs_plugin:MakesPDFPlugin` via getattr, and
|
|
333
|
+
# this keeps that working without importing mkdocs at module import time
|
|
334
|
+
# (see the integrations docstring rule). A missing extra raises the same
|
|
335
|
+
# helpful ImportError as the factory functions.
|
|
336
|
+
if name == "MakesPDFPlugin":
|
|
337
|
+
return _load_plugin_class()
|
|
338
|
+
raise AttributeError("module %r has no attribute %r" % (__name__, name))
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: makespdf
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Thin Python client for the makesPDF hosted API (Markdown and DSL templates to PDF)
|
|
5
|
+
Project-URL: Homepage, https://makespdf.com
|
|
6
|
+
Project-URL: Documentation, https://makespdf.com/docs/api
|
|
7
|
+
Author: makesPDF
|
|
8
|
+
License: MIT
|
|
9
|
+
Keywords: markdown,pdf,pdf-a,pdf-ua,rendering
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Topic :: Printing
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Requires-Python: >=3.9
|
|
21
|
+
Provides-Extra: crewai
|
|
22
|
+
Requires-Dist: crewai>=0.80; extra == 'crewai'
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: build; extra == 'dev'
|
|
25
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
26
|
+
Requires-Dist: twine; extra == 'dev'
|
|
27
|
+
Provides-Extra: langchain
|
|
28
|
+
Requires-Dist: langchain-core>=0.3; extra == 'langchain'
|
|
29
|
+
Provides-Extra: llamaindex
|
|
30
|
+
Requires-Dist: llama-index-core>=0.11; extra == 'llamaindex'
|
|
31
|
+
Provides-Extra: mkdocs
|
|
32
|
+
Requires-Dist: mkdocs>=1.6; extra == 'mkdocs'
|
|
33
|
+
Provides-Extra: test
|
|
34
|
+
Requires-Dist: pytest>=8; extra == 'test'
|
|
35
|
+
Description-Content-Type: text/markdown
|
|
36
|
+
|
|
37
|
+
# makespdf (Python)
|
|
38
|
+
|
|
39
|
+
Thin Python client for the [makesPDF](https://makespdf.com) hosted API.
|
|
40
|
+
Plain install is a bare HTTP client (stdlib only, zero required
|
|
41
|
+
dependencies): every call is a hosted API call, so billing stays consistent
|
|
42
|
+
with the web app and CLI. Nothing renders offline.
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
pip install makespdf
|
|
46
|
+
# framework shims (all optional):
|
|
47
|
+
pip install makespdf[langchain] # LangChain tool
|
|
48
|
+
pip install makespdf[llamaindex] # LlamaIndex tool
|
|
49
|
+
pip install makespdf[crewai] # CrewAI tool
|
|
50
|
+
pip install makespdf[mkdocs] # MkDocs sibling-PDF hook
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
import os
|
|
55
|
+
from makespdf import MakesPDFClient
|
|
56
|
+
|
|
57
|
+
client = MakesPDFClient(api_key=os.environ["MAKESPDF_API_KEY"])
|
|
58
|
+
|
|
59
|
+
# Markdown -> PDF bytes
|
|
60
|
+
pdf = client.render_md("# Invoice\n\nHello **Ada**.", {"pageSize": "A4"})
|
|
61
|
+
open("invoice.pdf", "wb").write(pdf)
|
|
62
|
+
|
|
63
|
+
# Stored template -> PDF bytes (production / billed)
|
|
64
|
+
pdf = client.render(template_id="invoice-classic", data={"name": "Ada"})
|
|
65
|
+
|
|
66
|
+
# Inline DSL draft (free, watermarked)
|
|
67
|
+
pdf = client.preview('const template = doc(page(col(s("Hi {{name}}"))));',
|
|
68
|
+
{"name": "Ada"})
|
|
69
|
+
|
|
70
|
+
# Cheap pre-flight checks (no rendering)
|
|
71
|
+
print(client.validate_md("## No H1 here"))
|
|
72
|
+
print(client.validate_preview('const template = doc(page(col(s("hi"))));'))
|
|
73
|
+
|
|
74
|
+
# veraPDF compliance check for an existing PDF (auth optional)
|
|
75
|
+
print(client.verify(open("invoice.pdf", "rb").read()))
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Module-level convenience functions (`makespdf.render_md(...)`, etc.) use a
|
|
79
|
+
default client built from `MAKESPDF_API_KEY` / `MAKESPDF_BASE_URL`.
|
|
80
|
+
|
|
81
|
+
## Auth
|
|
82
|
+
|
|
83
|
+
Mint a key at `https://makespdf.com/settings/api-keys`, store it as
|
|
84
|
+
`MAKESPDF_API_KEY`. The client never needs LLM keys — it is REST-only.
|
|
85
|
+
|
|
86
|
+
## Retry policy
|
|
87
|
+
|
|
88
|
+
`429` and `5xx` are retried up to 3 times with exponential backoff,
|
|
89
|
+
honouring `Retry-After`. Other `4xx` raise immediately (`400` ->
|
|
90
|
+
`ValidationError`, `401` -> `AuthenticationError`, `402` ->
|
|
91
|
+
`PaymentRequiredError`, `404` -> `NotFoundError`).
|
|
92
|
+
|
|
93
|
+
## Framework shims
|
|
94
|
+
|
|
95
|
+
All lazy — importing `makespdf` never imports a framework. Each shim exposes
|
|
96
|
+
exactly two tools (`makespdf_render_md` over `POST /api/v1/md`,
|
|
97
|
+
`makespdf_render` over `POST /api/v1/render`):
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
from makespdf.integrations.langchain import get_langchain_tools
|
|
101
|
+
from makespdf.integrations.llamaindex import get_llamaindex_tools
|
|
102
|
+
from makespdf.integrations.crewai import get_crewai_tools
|
|
103
|
+
from makespdf.integrations.mkdocs_plugin import get_mkdocs_plugin
|
|
104
|
+
from makespdf.integrations.demo import MARKDOWN_DEMO, DSL_DEMO, DATA_DEMO, TEMPLATE_ID_DEMO # shared demo data
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Full 5-line examples per runtime (all render the same demo data):
|
|
108
|
+
[LangChain](https://makespdf.com/docs/integrations/langchain?ref=pypi),
|
|
109
|
+
[LlamaIndex](https://makespdf.com/docs/integrations/llamaindex?ref=pypi),
|
|
110
|
+
[CrewAI](https://makespdf.com/docs/integrations/crewai?ref=pypi),
|
|
111
|
+
[LangGraph](https://makespdf.com/docs/integrations/langgraph?ref=pypi) and
|
|
112
|
+
[Vercel AI SDK](https://makespdf.com/docs/integrations/vercel-ai-sdk?ref=pypi).
|
|
113
|
+
LangGraph reuses the LangChain tools; the Vercel AI SDK page is the catalog
|
|
114
|
+
reference for the JS `@makespdf/agent-tools` implementation in the CLI repo.
|
|
115
|
+
|
|
116
|
+
### MkDocs sibling PDFs
|
|
117
|
+
|
|
118
|
+
After `pip install makespdf[mkdocs]`, the `makespdf` plugin name resolves
|
|
119
|
+
via the registered `mkdocs.plugins` entry point. Each page's source Markdown
|
|
120
|
+
is rendered to a sibling `.pdf` (one billed `/md` render per page).
|
|
121
|
+
Full guide:
|
|
122
|
+
[makespdf.com/docs/integrations/mkdocs](https://makespdf.com/docs/integrations/mkdocs?ref=mkdocs-plugin).
|
|
123
|
+
|
|
124
|
+
```yaml
|
|
125
|
+
# mkdocs.yml
|
|
126
|
+
plugins:
|
|
127
|
+
- search
|
|
128
|
+
- makespdf
|
|
129
|
+
extra:
|
|
130
|
+
makespdf: { pageSize: A4 } # optional; passed as /md `options`
|
|
131
|
+
# makespdf: { pageSize: A4, combined: true } # also emit site/combined.pdf
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Per-page front-matter (same contract as
|
|
135
|
+
[`@makespdf/docusaurus-plugin`](../integrations/docusaurus-plugin/)):
|
|
136
|
+
|
|
137
|
+
```md
|
|
138
|
+
---
|
|
139
|
+
pdf: false # skip this page (no PDF, no bill)
|
|
140
|
+
---
|
|
141
|
+
|
|
142
|
+
---
|
|
143
|
+
|
|
144
|
+
pdf-template: invoice-classic # render via /render with this templateId
|
|
145
|
+
customer: Ada # remaining keys + markdown/content/title become template data
|
|
146
|
+
|
|
147
|
+
---
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
`combined`, `combined_name`, and `pdf_template`/`pdf-template` are control
|
|
151
|
+
keys: they are consumed by the plugin and never sent as `/md` options.
|
|
152
|
+
Template-routed pages are excluded from the combined PDF.
|
|
153
|
+
|
|
154
|
+
Prefer a hooks file instead? MkDocs `hooks:` takes file paths (not
|
|
155
|
+
`module:func` strings), so add a one-line shim, e.g.
|
|
156
|
+
`docs/hooks/makespdf_hook.py`:
|
|
157
|
+
|
|
158
|
+
```python
|
|
159
|
+
from makespdf.integrations.mkdocs_plugin import on_post_build_hook
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
and list it under `hooks:` in `mkdocs.yml`.
|
|
163
|
+
|
|
164
|
+
## Testing
|
|
165
|
+
|
|
166
|
+
```bash
|
|
167
|
+
pip install -e .[test]
|
|
168
|
+
pytest -m "not integration" # recorded-fixture suite, no network
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
Live smokes (burns at most one billed render):
|
|
172
|
+
|
|
173
|
+
```bash
|
|
174
|
+
MAKESPDF_API_KEY=... MAKESPDF_BASE_URL=https://staging.makespdf.com MAKESPDF_SMOKE=1 pytest -m integration
|
|
175
|
+
```
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
makespdf/__init__.py,sha256=qnWruSyFHCVnRAQG17mPQuQqMkd5oi0Vbgpf5heCXFs,945
|
|
2
|
+
makespdf/client.py,sha256=FAdo9gqCirbGrt7WCPD6J_MP1pZM3lGxDaQwiDjxB7c,10108
|
|
3
|
+
makespdf/errors.py,sha256=4hvAAFFZSUYcthoYkvWX2dLVKq0NKur9zRPT_VHA75Q,1420
|
|
4
|
+
makespdf/integrations/__init__.py,sha256=oLLvIr3A4TojD_PycQ-yKB8m5HvQx0LhvPh4Jg7-rcs,914
|
|
5
|
+
makespdf/integrations/crewai.py,sha256=3f8nb4tjlvHEKAIRft8CjcOf-m1r-5mau4Y9-Yc76aU,3068
|
|
6
|
+
makespdf/integrations/demo.py,sha256=k4hQYxxMt4BPRAWGZbK0hQ2zKhFV82w5cQnT63jVlx8,1327
|
|
7
|
+
makespdf/integrations/langchain.py,sha256=HoFoXPOzrMGvKVGkYR9uHBsWmRIlguCJmcIIdYFGk1M,3439
|
|
8
|
+
makespdf/integrations/llamaindex.py,sha256=3puHKK-eexbtaYzJEnmdkzoSEAk1ixF_TNgwbg6K-sg,3456
|
|
9
|
+
makespdf/integrations/mkdocs_plugin.py,sha256=c7l_p5JBhgPG0NpTfRo8rNxk-5hKTjSg7mjHBoGGj6I,13091
|
|
10
|
+
makespdf-0.1.1.dist-info/METADATA,sha256=KsL3vTfTfepXMn-Ad5rHOHYDG-HoabWsOwxafUH5Z9I,6182
|
|
11
|
+
makespdf-0.1.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
12
|
+
makespdf-0.1.1.dist-info/entry_points.txt,sha256=X3Ekd4lFDH3ktbz8MI5p-N9fbeLYzcnmnc7QwJmsReY,79
|
|
13
|
+
makespdf-0.1.1.dist-info/RECORD,,
|