pressjet 0.1.0b2__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.
pressjet/__init__.py ADDED
@@ -0,0 +1,182 @@
1
+ """The official Python SDK for Pressjet, an open PDF rendering service.
2
+
3
+ Build a document with the builders and render it with a client::
4
+
5
+ import pressjet
6
+ from pressjet import document, page, text
7
+
8
+ with pressjet.Client() as client:
9
+ pdf = client.generate(document(page(text("Hello")), title="Hello"))
10
+ """
11
+
12
+ from ._builders import (
13
+ DEFAULT_PAGE_NUMBER_TEMPLATE,
14
+ BinaryData,
15
+ BlockChild,
16
+ PageChild,
17
+ TextChild,
18
+ barcode,
19
+ document,
20
+ image,
21
+ page,
22
+ page_number,
23
+ table,
24
+ text,
25
+ view,
26
+ )
27
+ from ._client import (
28
+ Anchor,
29
+ AsyncClient,
30
+ Binary,
31
+ Check,
32
+ CheckedPage,
33
+ Client,
34
+ Diagnostic,
35
+ DiagnosticCode,
36
+ Document,
37
+ Flow,
38
+ FontFace,
39
+ HtmlCheckOptions,
40
+ HtmlOptions,
41
+ PageImage,
42
+ Preview,
43
+ Raster,
44
+ Verification,
45
+ VerificationSignature,
46
+ )
47
+ from ._errors import (
48
+ APIError,
49
+ ErrorCode,
50
+ PressjetConnectionError,
51
+ PressjetError,
52
+ PressjetTimeoutError,
53
+ ResponseTooLargeError,
54
+ )
55
+ from ._transport import (
56
+ DEFAULT_BASE_URL,
57
+ DEFAULT_MAX_RESPONSE_BYTES,
58
+ DEFAULT_MAX_RETRIES,
59
+ DEFAULT_TIMEOUT,
60
+ )
61
+ from ._types import (
62
+ BarcodeFormat,
63
+ BarcodeNode,
64
+ BarcodeProperties,
65
+ BlockNode,
66
+ BorderStyle,
67
+ BuiltInFontFamily,
68
+ Color,
69
+ Conformance,
70
+ DocumentNode,
71
+ DocumentProperties,
72
+ FontFamily,
73
+ FontStyle,
74
+ FontWeightName,
75
+ ImageNode,
76
+ ImageProperties,
77
+ Length,
78
+ PageNode,
79
+ PageProperties,
80
+ PageSize,
81
+ PageSizeName,
82
+ QrErrorCorrection,
83
+ RasterOptions,
84
+ Role,
85
+ Spacing,
86
+ Style,
87
+ TableCell,
88
+ TableColumn,
89
+ TableNode,
90
+ TableProperties,
91
+ TextContent,
92
+ TextNode,
93
+ TextProperties,
94
+ VerificationFormat,
95
+ VerificationPosition,
96
+ VerificationSettings,
97
+ ViewNode,
98
+ ViewProperties,
99
+ )
100
+ from ._version import __version__
101
+
102
+ __all__ = [
103
+ "DEFAULT_BASE_URL",
104
+ "DEFAULT_MAX_RESPONSE_BYTES",
105
+ "DEFAULT_MAX_RETRIES",
106
+ "DEFAULT_PAGE_NUMBER_TEMPLATE",
107
+ "DEFAULT_TIMEOUT",
108
+ "APIError",
109
+ "Anchor",
110
+ "AsyncClient",
111
+ "BarcodeFormat",
112
+ "BarcodeNode",
113
+ "BarcodeProperties",
114
+ "Binary",
115
+ "BinaryData",
116
+ "BlockChild",
117
+ "BlockNode",
118
+ "BorderStyle",
119
+ "BuiltInFontFamily",
120
+ "Check",
121
+ "CheckedPage",
122
+ "Client",
123
+ "Color",
124
+ "Conformance",
125
+ "Diagnostic",
126
+ "DiagnosticCode",
127
+ "Document",
128
+ "DocumentNode",
129
+ "DocumentProperties",
130
+ "ErrorCode",
131
+ "Flow",
132
+ "FontFace",
133
+ "FontFamily",
134
+ "FontStyle",
135
+ "FontWeightName",
136
+ "HtmlCheckOptions",
137
+ "HtmlOptions",
138
+ "ImageNode",
139
+ "ImageProperties",
140
+ "Length",
141
+ "PageChild",
142
+ "PageImage",
143
+ "PageNode",
144
+ "PageProperties",
145
+ "PageSize",
146
+ "PageSizeName",
147
+ "PressjetConnectionError",
148
+ "PressjetError",
149
+ "PressjetTimeoutError",
150
+ "Preview",
151
+ "QrErrorCorrection",
152
+ "Raster",
153
+ "RasterOptions",
154
+ "ResponseTooLargeError",
155
+ "Role",
156
+ "Spacing",
157
+ "Style",
158
+ "TableCell",
159
+ "TableColumn",
160
+ "TableNode",
161
+ "TableProperties",
162
+ "TextChild",
163
+ "TextContent",
164
+ "TextNode",
165
+ "TextProperties",
166
+ "Verification",
167
+ "VerificationFormat",
168
+ "VerificationPosition",
169
+ "VerificationSettings",
170
+ "VerificationSignature",
171
+ "ViewNode",
172
+ "ViewProperties",
173
+ "__version__",
174
+ "barcode",
175
+ "document",
176
+ "image",
177
+ "page",
178
+ "page_number",
179
+ "table",
180
+ "text",
181
+ "view",
182
+ ]
pressjet/_builders.py ADDED
@@ -0,0 +1,409 @@
1
+ """Builders for the Pressjet document tree.
2
+
3
+ Positional arguments are children; properties are keyword-only. Children that are ``None`` or
4
+ ``False`` are dropped and nested lists or tuples are flattened, so conditional content reads
5
+ naturally::
6
+
7
+ text("Total: ", amount, is_paid and text("PAID", style={"color": "green"}))
8
+
9
+ Properties left unset are omitted from the node, never sent as ``null``.
10
+ """
11
+
12
+ import base64
13
+ import math
14
+ from collections.abc import Iterator, Sequence
15
+ from typing import TypeAlias, cast
16
+
17
+ from ._types import (
18
+ BarcodeFormat,
19
+ BarcodeNode,
20
+ BarcodeProperties,
21
+ BlockNode,
22
+ BlockProperties,
23
+ Conformance,
24
+ DocumentNode,
25
+ DocumentProperties,
26
+ ImageNode,
27
+ ImageProperties,
28
+ PageNode,
29
+ PageProperties,
30
+ PageSize,
31
+ QrErrorCorrection,
32
+ Role,
33
+ Style,
34
+ TableCell,
35
+ TableColumn,
36
+ TableNode,
37
+ TableProperties,
38
+ TextContent,
39
+ TextNode,
40
+ TextProperties,
41
+ VerificationSettings,
42
+ ViewNode,
43
+ ViewProperties,
44
+ )
45
+
46
+ BinaryData: TypeAlias = bytes | bytearray | memoryview
47
+ """Raw bytes; the SDK encodes them as standard padded base64."""
48
+
49
+ PageChild: TypeAlias = PageNode | bool | Sequence["PageChild"] | None
50
+ """A page, a skipped value (``None``/``False``), or a nested sequence of them."""
51
+
52
+ BlockChild: TypeAlias = BlockNode | bool | Sequence["BlockChild"] | None
53
+ """A view, text, image, barcode or table, a skipped value (``None``/``False``), or a nested
54
+ sequence of them."""
55
+
56
+ TextChild: TypeAlias = (
57
+ str | int | float | TextNode | ImageNode | bool | Sequence["TextChild"] | None
58
+ )
59
+ """A string, a number (made a string), a text span, an inline image, a skipped value, or a
60
+ nested sequence of them."""
61
+
62
+ DEFAULT_PAGE_NUMBER_TEMPLATE = "{pageNumber} / {totalPages}"
63
+
64
+ _BLOCK_TYPES = frozenset({"view", "text", "image", "barcode", "table"})
65
+ _TEXT_NODE_TYPES = frozenset({"text", "image"})
66
+
67
+
68
+ def document(
69
+ *pages: PageChild,
70
+ title: str | None = None,
71
+ author: str | None = None,
72
+ lang: str | None = None,
73
+ created: str | None = None,
74
+ conformance: Conformance | Sequence[Conformance] | None = None,
75
+ verification: VerificationSettings | None = None,
76
+ ) -> DocumentNode:
77
+ """The root node. Holds one or more pages; each page may flow onto several.
78
+
79
+ ``lang`` is a language tag such as ``"en"`` or ``"es-MX"`` (needed for PDF/UA-1),
80
+ ``created`` an ISO 8601 date-time (needed for PDF/A-2b), and ``conformance`` one standard or
81
+ a sequence of them, sent as a list. ``verification`` stamps every page with a code that
82
+ ``verify`` reads back, such as ``{"id": "OH-2026-0417"}``.
83
+ """
84
+ properties: DocumentProperties = {}
85
+ if title is not None:
86
+ properties["title"] = title
87
+ if author is not None:
88
+ properties["author"] = author
89
+ if lang is not None:
90
+ properties["lang"] = lang
91
+ if created is not None:
92
+ properties["created"] = created
93
+ if conformance is not None:
94
+ properties["conformance"] = (
95
+ conformance if isinstance(conformance, str) else list(conformance)
96
+ )
97
+ if verification is not None:
98
+ properties["verification"] = verification
99
+ children = [cast(PageNode, node) for node in _nodes(pages, frozenset({"page"}), "document")]
100
+ return {"type": "document", "properties": properties, "children": children}
101
+
102
+
103
+ def page(
104
+ *children: BlockChild,
105
+ size: PageSize | None = None,
106
+ style: Style | None = None,
107
+ ) -> PageNode:
108
+ """A page template. Content that does not fit continues on new pages of the same size.
109
+
110
+ ``size`` is ``"LETTER"`` (the default), ``"A4"``, ``"LEGAL"`` or ``"A5"``, optionally followed
111
+ by ``landscape`` or ``portrait``, or a width and a height such as ``"210mm 297mm"``.
112
+ """
113
+ properties: PageProperties = {}
114
+ if size is not None:
115
+ properties["size"] = size
116
+ if style is not None:
117
+ properties["style"] = style
118
+ return {"type": "page", "properties": properties, "children": _blocks(children, "page")}
119
+
120
+
121
+ def view(
122
+ *children: BlockChild,
123
+ style: Style | None = None,
124
+ fixed: bool | None = None,
125
+ hide_on_first_page: bool | None = None,
126
+ wrap: bool | None = None,
127
+ break_: bool | None = None,
128
+ keep_together: bool | None = None,
129
+ keep_with_next: bool | None = None,
130
+ role: Role | None = None,
131
+ level: int | None = None,
132
+ alt: str | None = None,
133
+ id: str | None = None,
134
+ ) -> ViewNode:
135
+ """A flexbox container, like a ``div``.
136
+
137
+ ``fixed`` repeats it on every page the parent spans (``hide_on_first_page=True`` leaves it off
138
+ the first of them, as for a running header from page 2 on), ``wrap=False`` keeps it on one
139
+ page and ``break_=True`` starts it on a new page (``break`` is a Python keyword).
140
+ ``keep_with_next=True`` allows no page break before the next node. ``role``, ``level`` (of a
141
+ heading, 1 to 6) and ``alt`` tag it for PDF/UA; ``id`` names it in the layout report's
142
+ anchors and as a named destination in the PDF.
143
+ """
144
+ properties: ViewProperties = {}
145
+ if keep_together is not None:
146
+ properties["keepTogether"] = keep_together
147
+ if level is not None:
148
+ properties["level"] = level
149
+ _set_block_properties(
150
+ properties, style, fixed, hide_on_first_page, wrap, break_, keep_with_next, role, alt, id
151
+ )
152
+ return {"type": "view", "properties": properties, "children": _blocks(children, "view")}
153
+
154
+
155
+ def text(
156
+ *children: TextChild,
157
+ style: Style | None = None,
158
+ fixed: bool | None = None,
159
+ hide_on_first_page: bool | None = None,
160
+ wrap: bool | None = None,
161
+ break_: bool | None = None,
162
+ keep_together: bool | None = None,
163
+ keep_with_next: bool | None = None,
164
+ role: Role | None = None,
165
+ level: int | None = None,
166
+ alt: str | None = None,
167
+ id: str | None = None,
168
+ href: str | None = None,
169
+ ) -> TextNode:
170
+ """A paragraph. Strings are its text; nested text nodes are spans with their own style.
171
+
172
+ ``keep_together=True`` keeps it on one page when it fits; the other properties are as for
173
+ ``view``.
174
+ """
175
+ properties: TextProperties = {}
176
+ if href is not None:
177
+ properties["href"] = href
178
+ if keep_together is not None:
179
+ properties["keepTogether"] = keep_together
180
+ if level is not None:
181
+ properties["level"] = level
182
+ _set_block_properties(
183
+ properties, style, fixed, hide_on_first_page, wrap, break_, keep_with_next, role, alt, id
184
+ )
185
+ return {"type": "text", "properties": properties, "children": list(_text_content(children))}
186
+
187
+
188
+ def image(
189
+ src: BinaryData | str,
190
+ *,
191
+ style: Style | None = None,
192
+ fixed: bool | None = None,
193
+ hide_on_first_page: bool | None = None,
194
+ wrap: bool | None = None,
195
+ break_: bool | None = None,
196
+ keep_with_next: bool | None = None,
197
+ role: Role | None = None,
198
+ alt: str | None = None,
199
+ id: str | None = None,
200
+ inline_baseline: bool | None = None,
201
+ ) -> ImageNode:
202
+ """A PNG or JPEG image, never split across pages.
203
+
204
+ ``src`` is the image's bytes (encoded as base64 here), or a string that is already base64
205
+ or a ``data:`` URL and is passed through unchanged. Images are never fetched from a network.
206
+ ``alt`` is its alternative text; the other properties are as for ``view``.
207
+ """
208
+ properties: ImageProperties = {"src": encode_binary(src)}
209
+ if inline_baseline is not None:
210
+ properties["inlineBaseline"] = inline_baseline
211
+ _set_block_properties(
212
+ properties, style, fixed, hide_on_first_page, wrap, break_, keep_with_next, role, alt, id
213
+ )
214
+ return {"type": "image", "properties": properties, "children": []}
215
+
216
+
217
+ def barcode(
218
+ format: BarcodeFormat,
219
+ value: str,
220
+ *,
221
+ error_correction: QrErrorCorrection | int | None = None,
222
+ columns: int | None = None,
223
+ style: Style | None = None,
224
+ fixed: bool | None = None,
225
+ hide_on_first_page: bool | None = None,
226
+ wrap: bool | None = None,
227
+ break_: bool | None = None,
228
+ keep_with_next: bool | None = None,
229
+ role: Role | None = None,
230
+ alt: str | None = None,
231
+ id: str | None = None,
232
+ ) -> BarcodeNode:
233
+ """A QR, PDF417, Data Matrix or Code 128 symbol drawn as vectors, never split across pages.
234
+
235
+ ``value`` is what it holds; ``{pageNumber}`` and ``{totalPages}`` are replaced on each page.
236
+ ``error_correction`` is ``"L"``, ``"M"``, ``"Q"`` or ``"H"`` for QR and 0 to 8 for PDF417;
237
+ ``columns`` (1 to 30) sets PDF417's data columns. Without a width or height it takes one point
238
+ per module, and ``style["color"]`` sets the dark modules. ``alt`` is its alternative text
239
+ (``"Barcode"`` when absent); the other properties are as for ``view``.
240
+ """
241
+ properties: BarcodeProperties = {"format": format, "value": value}
242
+ if error_correction is not None:
243
+ properties["errorCorrection"] = error_correction
244
+ if columns is not None:
245
+ properties["columns"] = columns
246
+ _set_block_properties(
247
+ properties, style, fixed, hide_on_first_page, wrap, break_, keep_with_next, role, alt, id
248
+ )
249
+ return {"type": "barcode", "properties": properties, "children": []}
250
+
251
+
252
+ def table(
253
+ columns: Sequence[str | TableColumn],
254
+ rows: Sequence[Sequence[TableCell]] | None = None,
255
+ *,
256
+ style: Style | None = None,
257
+ header_style: Style | None = None,
258
+ row_style: Style | None = None,
259
+ repeat_header: bool | None = None,
260
+ keep_with_next: bool | None = None,
261
+ break_: bool | None = None,
262
+ id: str | None = None,
263
+ ) -> TableNode:
264
+ """A table: a header row that repeats on every page it reaches and rows that never split.
265
+
266
+ ``columns`` are 1 to 50 header strings or ``TableColumn`` dicts (``header``, ``width``,
267
+ ``align``, ``style``). Each row lists one cell per column: a string, a number, ``None`` for an
268
+ empty cell, or a block node. ``header_style`` and ``row_style`` apply over the default row
269
+ styles, ``repeat_header=False`` prints the header only on the first page, and the other
270
+ properties are as for ``view``.
271
+ """
272
+ properties: TableProperties = {"columns": list(columns)}
273
+ if rows is not None:
274
+ properties["rows"] = [[_cell(cell) for cell in row] for row in rows]
275
+ if style is not None:
276
+ properties["style"] = style
277
+ if header_style is not None:
278
+ properties["headerStyle"] = header_style
279
+ if row_style is not None:
280
+ properties["rowStyle"] = row_style
281
+ if repeat_header is not None:
282
+ properties["repeatHeader"] = repeat_header
283
+ if keep_with_next is not None:
284
+ properties["keepWithNext"] = keep_with_next
285
+ if break_ is not None:
286
+ properties["break"] = break_
287
+ if id is not None:
288
+ properties["id"] = id
289
+ return {"type": "table", "properties": properties, "children": []}
290
+
291
+
292
+ def page_number(
293
+ template: str = DEFAULT_PAGE_NUMBER_TEMPLATE,
294
+ *,
295
+ style: Style | None = None,
296
+ fixed: bool = True,
297
+ hide_on_first_page: bool | None = None,
298
+ ) -> TextNode:
299
+ """A text node showing the page number; ``{pageNumber}`` and ``{totalPages}`` are filled in.
300
+
301
+ It is ``fixed`` by default so it repeats on every page; ``hide_on_first_page=True`` leaves it
302
+ off the first page.
303
+ """
304
+ properties: TextProperties = {"fixed": fixed, "pageNumberText": template}
305
+ if hide_on_first_page is not None:
306
+ properties["hideOnFirstPage"] = hide_on_first_page
307
+ if style is not None:
308
+ properties["style"] = style
309
+ return {"type": "text", "properties": properties, "children": []}
310
+
311
+
312
+ def encode_binary(data: BinaryData | str) -> str:
313
+ """Standard padded base64 for bytes; a string is returned unchanged."""
314
+ if isinstance(data, str):
315
+ return data
316
+ if isinstance(data, (bytes, bytearray, memoryview)):
317
+ return base64.b64encode(data).decode("ascii")
318
+ raise TypeError(f"expected bytes or a base64 string, got {type(data).__name__}")
319
+
320
+
321
+ def _set_block_properties(
322
+ properties: BlockProperties,
323
+ style: Style | None,
324
+ fixed: bool | None,
325
+ hide_on_first_page: bool | None,
326
+ wrap: bool | None,
327
+ break_: bool | None,
328
+ keep_with_next: bool | None,
329
+ role: Role | None,
330
+ alt: str | None,
331
+ id: str | None,
332
+ ) -> None:
333
+ if fixed is not None:
334
+ properties["fixed"] = fixed
335
+ if hide_on_first_page is not None:
336
+ properties["hideOnFirstPage"] = hide_on_first_page
337
+ if wrap is not None:
338
+ properties["wrap"] = wrap
339
+ if break_ is not None:
340
+ properties["break"] = break_
341
+ if keep_with_next is not None:
342
+ properties["keepWithNext"] = keep_with_next
343
+ if role is not None:
344
+ properties["role"] = role
345
+ if alt is not None:
346
+ properties["alt"] = alt
347
+ if id is not None:
348
+ properties["id"] = id
349
+ if style is not None:
350
+ properties["style"] = style
351
+
352
+
353
+ def _blocks(children: Sequence[BlockChild], parent: str) -> list[BlockNode]:
354
+ return [cast(BlockNode, node) for node in _nodes(children, _BLOCK_TYPES, parent)]
355
+
356
+
357
+ def _cell(cell: TableCell) -> TableCell:
358
+ if cell is None or (isinstance(cell, (str, int, float)) and not isinstance(cell, bool)):
359
+ return cell
360
+ return cast(BlockNode, _node(cell, _BLOCK_TYPES, "table cell"))
361
+
362
+
363
+ def _text_content(children: Sequence[TextChild]) -> Iterator[TextContent]:
364
+ for child in _flatten(children):
365
+ if isinstance(child, str):
366
+ yield child
367
+ elif isinstance(child, (int, float)):
368
+ yield _number_text(child)
369
+ else:
370
+ yield cast(TextContent, _node(child, _TEXT_NODE_TYPES, "text"))
371
+
372
+
373
+ def _nodes(children: Sequence[object], allowed: frozenset[str], parent: str) -> Iterator[object]:
374
+ for child in _flatten(children):
375
+ yield _node(child, allowed, parent)
376
+
377
+
378
+ def _node(child: object, allowed: frozenset[str], parent: str) -> object:
379
+ if isinstance(child, dict) and child.get("type") in allowed:
380
+ return child
381
+ kinds = ", ".join(sorted(allowed))
382
+ raise TypeError(f"a {parent} holds {kinds} nodes, got {_describe(child)}")
383
+
384
+
385
+ def _flatten(children: Sequence[object]) -> Iterator[object]:
386
+ for child in children:
387
+ if child is None or child is False:
388
+ continue
389
+ if child is True:
390
+ raise TypeError("True is not a valid child; use None or False to skip a child")
391
+ if isinstance(child, Sequence) and not isinstance(child, (str, bytes, bytearray)):
392
+ yield from _flatten(child)
393
+ else:
394
+ yield child
395
+
396
+
397
+ def _number_text(value: int | float) -> str:
398
+ integral = isinstance(value, float) and math.isfinite(value) and value.is_integer()
399
+ if integral and abs(value) < 1e21:
400
+ return str(int(value))
401
+ return str(value)
402
+
403
+
404
+ def _describe(value: object) -> str:
405
+ if isinstance(value, dict):
406
+ return f"a {value.get('type')!r} node" if "type" in value else "a dict without a type"
407
+ if isinstance(value, str):
408
+ return f"the string {value[:40]!r}"
409
+ return type(value).__name__