Metadata-Version: 2.5
Name: pressjet
Version: 0.1.0b2
Summary: Official Python SDK for Pressjet, an open PDF rendering service.
Project-URL: Homepage, https://github.com/tonysantana1492/pressjet
Project-URL: Source, https://github.com/tonysantana1492/pressjet/tree/main/sdks/python
Project-URL: Documentation, https://github.com/tonysantana1492/pressjet/blob/main/docs/sdk-design.md
Author: Tony Santana
License-Expression: Apache-2.0 AND LicenseRef-FSL-1.1-ALv2
License-File: LICENSE
Keywords: pdf,pdf-generation,pressjet,rendering
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Printing
Classifier: Typing :: Typed
Requires-Python: >=3.11
Provides-Extra: dev
Requires-Dist: build>=1.6.1; extra == 'dev'
Requires-Dist: mypy>=2.4.1; extra == 'dev'
Requires-Dist: pytest>=9.2; extra == 'dev'
Requires-Dist: ruff>=0.17.6; extra == 'dev'
Description-Content-Type: text/markdown
License-File: renderer/DEJAVU-LICENSE.txt
License-File: renderer/LIBERATION-COPYRIGHT.txt
License-File: renderer/LICENSE.md
License-File: renderer/NOTICE
License-File: renderer/OFL.txt
License-File: renderer/THIRD-PARTY-LICENSES.txt

# Pressjet for Python

**Beta 2** · [Install this SDK from the versioned GitHub release](https://github.com/tonysantana1492/pressjet/blob/v0.1.0-beta.2/docs/beta.md#choose-an-sdk).

The official Python SDK for [Pressjet](https://github.com/tonysantana1492/pressjet), an open PDF
rendering service. Build a document tree with plain functions and render it to PDF, preview it as
images, draw flows, merge, rasterize and sign PDFs.

- Python 3.11+, fully typed (`py.typed`), no dependencies beyond the standard library.
- A synchronous `Client` and an `asyncio` `AsyncClient` with the same methods.
- Retries, timeouts and typed errors as described in the
  [SDK design](https://github.com/tonysantana1492/pressjet/blob/main/docs/sdk-design.md).

## Install

```sh
python -m pip install https://github.com/tonysantana1492/pressjet/releases/download/v0.1.0-beta.2/pressjet-0.1.0b2-py3-none-any.whl
```

## Quick start

```python
import pressjet
from pressjet import document, page, text

invoice = document(
    page(
        text("Invoice INV-001", style={"fontSize": 20, "fontWeight": "bold"}),
        text("Billed to ", text("Acme Corp.", style={"fontWeight": "bold"})),
        size="A4",
        style={"padding": 40, "fontFamily": "Helvetica"},
    ),
    title="Invoice INV-001",
)

with pressjet.Client(api_key="pj_sk_...", base_url="http://localhost:8080") as client:
    pdf = client.generate(invoice)

with open("invoice.pdf", "wb") as file:
    file.write(pdf)
```

`examples/invoice.py` is a complete example.

The [signature example](examples/signatures.py) builds a section you can append to a contract.
Choose `line` (default), `box` or `square` ([PDF sample](examples/signature-styles.pdf)).
To mix appearances, pass individual
`signature_field(name, appearance)` values to `signature_section`. With the matching CLI on
your path, this command generates a two-signer sheet with the optional diagonal draft stamp.

```sh
python examples/signatures.py --style box --watermark diagonal "Ana López" "Jordan Lee" | pressjet render - -o signatures.pdf
```

## Builders

```python
from pressjet import document, page, view, text, image, barcode, table, page_number
```

| Builder | Children | Keyword properties |
| --- | --- | --- |
| `document(*pages, title=None, author=None, lang=None, created=None, conformance=None, verification=None)` | pages | `lang`: a language tag such as `"es-MX"`; `created`: ISO 8601; `conformance`: `"pdf-a-2b"`, `"pdf-ua-1"` or a sequence of them; `verification`: a `VerificationSettings` dict |
| `page(*children, size=None, style=None)` | views, text, images, barcodes | `size`: `"LETTER"`, `"A4"`, `"LEGAL"`, `"A5"`, optionally with `landscape` or `portrait` (`"A4 landscape"`), or a width and height (`"210mm 297mm"`) |
| `view(*children, style=None, fixed=None, hide_on_first_page=None, wrap=None, break_=None, keep_together=None, keep_with_next=None, role=None, level=None, alt=None, id=None)` | views, text, images, barcodes | |
| `text(*children, style=None, fixed=None, hide_on_first_page=None, wrap=None, break_=None, keep_together=None, keep_with_next=None, role=None, level=None, alt=None, id=None)` | strings, numbers, text, images | |
| `image(src, style=None, fixed=None, hide_on_first_page=None, wrap=None, break_=None, keep_with_next=None, role=None, alt=None, id=None)` | none | `src`: bytes, base64 or a `data:` URL |
| `barcode(format, value, error_correction=None, columns=None, style=None, fixed=None, hide_on_first_page=None, wrap=None, break_=None, keep_with_next=None, role=None, alt=None, id=None)` | none | `format`: `"qr"`, `"pdf417"`, `"datamatrix"` or `"code128"` |
| `table(columns, rows=None, style=None, header_style=None, row_style=None, repeat_header=None, keep_with_next=None, break_=None, id=None)` | none | `columns`: header strings or `{"header", "width", "align", "style"}`; each row holds one cell per column: a string, a number, `None` or a node |
| `page_number(template="{pageNumber} / {totalPages}", style=None, fixed=True, hide_on_first_page=None)` | none | |

- Positional arguments are children; properties are keyword-only.
- `fixed=True` repeats a node on every page (headers, footers), `wrap=False` keeps it on one page
  and `break_=True` starts it on a new page. The trailing underscore avoids the `break` keyword;
  the node holds the schema's `"break"` key.
- `keep_together=True` keeps a view or paragraph on one page when it fits, and
  `keep_with_next=True` allows no page break between a node and the next one (a heading and its
  first paragraph).
- `role` (a `Role` such as `"heading"`, `"table"` or `"artifact"`), `level` (a heading's level,
  1 to 6) and `alt` (alternative text) tag the node for PDF/UA-1. `id` (unique, up to 64 of
  `A-Z a-z 0-9 _ . : -`) lists the node in the layout report's `anchors` and makes it a named
  destination in the PDF.
- `document(lang=..., created=..., conformance=...)` write a PDF/A-2b or PDF/UA-1 file:
  PDF/A-2b needs `created`, since the engine reads no clock, and PDF/UA-1 needs `title` and
  `lang`.
- `barcode` draws a symbol as vectors, never split across pages; it goes where a view or an
  image block goes, not inside text. `value` holds 1 to 4000 characters, with `{pageNumber}` and
  `{totalPages}` replaced on each page. `error_correction` is `"L"`, `"M"`, `"Q"` or `"H"` for QR
  and 0 to 8 for PDF417, and `columns` (1 to 30) sets PDF417's data columns. Without a width or
  height a code takes one point per module; `style={"color": ...}` sets the dark modules.
- `document(verification=...)` stamps every page's margin with a code that names the document, a
  digest of its source, the page number and total and, when the server holds a verification key,
  an Ed25519 signature. `id` is required (up to 64 of `A-Z a-z 0-9 _ . : / -`); `url` (an
  `https://` address a phone camera opens), `format` (`"qr"`, `"pdf417"` or `"datamatrix"`),
  `position` (`"bottom-right"` by default, or `"left-edge"` and so on), `size` (18 to 144
  points), `inset` and `caption` are optional. The code is sized to fit the margin, so it never
  covers content:

  ```python
  lease = document(page(...), verification={"id": "OH-2026-0417", "url": "https://example.com/v"})
  ```

- `None` and `False` children are dropped and nested lists or tuples are flattened, so
  conditional content and comprehensions read naturally:

  ```python
  view(
      [text(line.name) for line in lines],
      is_paid and text("PAID", style={"color": "#16a34a"}),
  )
  ```

- Numbers inside text become strings (`2.0` becomes `"2"`).
- Properties left unset are omitted, never sent as `null`.
- Image bytes are encoded as standard padded base64; a string `src` is passed through unchanged.
- Nodes are plain `dict`s (typed as `TypedDict`s such as `DocumentNode`) that `json.dumps`
  serializes to [`spec/document.schema.json`](https://github.com/tonysantana1492/pressjet/blob/main/spec/document.schema.json).
- `Style` is a `TypedDict` with every style property of the schema, using its camelCase keys and
  `Literal` types for the allowed values, so editors and type checkers complete and check them.
  It includes `display` (`"flex"` or `"block"`), `boxSizing`, `marginVertical`,
  `marginHorizontal`, `fontStyle`, `textDecoration`, `orphans`, `widows`, `transform`,
  `transformOrigin`, the per-side borders (`borderTop`, or `borderLeftWidth`, `borderLeftColor`,
  `borderLeftStyle` and so on) and `borderStyle` with `"none"` and `"hidden"`.
- `fontFamily` and `size` are open strings: `FontFamily` suggests the built-in families
  (`BuiltInFontFamily`) but takes a CSS-style list such as `"Brand, Archivo, sans-serif"`, and
  `PageSize` suggests the named sizes (`PageSizeName`).

## Client

| Method | Returns |
| --- | --- |
| `generate(document, *, fonts=None)` | PDF `bytes` |
| `html(html, settings=None)` | PDF `bytes` |
| `preview(document, options=None, *, fonts=None)` | `Preview(pdf, total_pages, pages)` |
| `check(document, *, fonts=None)` | `Check(ok, page_count, pages, diagnostics, dropped, anchors)`, the layout report |
| `check_html(html, settings=None)` | `Check`, the layout report of HTML as `html` prints it |
| `verify(code, *, public_key=None, layout=None)` | `Verification`, what a scanned verification code says |
| `draw(flow, append_pdfs=None)` | PDF `bytes` |
| `merge(pdfs)` | PDF `bytes` |
| `rasterize(data, options=None)` | `Raster(total_pages, pages)` |
| `sign(pdf, *, name, reason, signing_time)` | PDF `bytes` |
| `info()` | the server's capabilities as a `dict`, with `verificationKey` (base64url, or `None`) |
| `health()` | `{"status": "ok", "version": ...}` |

`check` reports what is wrong with a document without rendering it, each problem with a JSON
Pointer and a fix ([the codes](https://github.com/tonysantana1492/pressjet/blob/main/docs/layout-report.md)).
A document that cannot be rendered is a report with `ok` false, not an exception, so it may be any
JSON value, such as one a model wrote:

```python
report = client.check(json.loads(model_output))
for problem in report.errors:
    print(problem.code, problem.pointer, problem.fix)
if any(problem.code == DiagnosticCode.MISSING_GLYPH for problem in report.diagnostics):
    ...
```

- `barcode_too_small` (with `module`, the module width in millimetres) and `barcode_covered` are
  warnings about barcodes and verification codes.
- `anchors` is a list of `Anchor(id, page, x, y, width, height)`, one per node with an `id`: the
  page it first appears on (from 1) and its box there, in points from the page's top left. It is
  empty when no node has an `id`.
- `fonts` is a sequence of `FontFace` dicts, at most 32: `src` (TrueType or OpenType bytes, which
  the SDK encodes as base64, or a base64 string) and optional `family`, `weight` (1 to 1000) and
  `style` (`"normal"`, `"italic"` or `"oblique"`). The document may then name the family in
  `fontFamily`:

  ```python
  brand = {"family": "Brand", "src": Path("Brand-Regular.ttf").read_bytes()}
  pdf = client.generate(invoice, fonts=[brand])
  ```

- `verify` takes the text a scanner read from a verification code, in either form, and returns
  `Verification(valid, reason, id, digest, page, total_pages, signature, document_matches)`.
  `signature` is `"valid"` or `"invalid"` when a key is known (`public_key`, else the server's
  own), `"unchecked"` when none is, and `"absent"` for an unsigned code. Pass `layout`, the source
  document you kept, to learn whether the code was printed from it. A code whose signature is
  `"absent"` or `"unchecked"` proves only what `document_matches` says. A publishable key may call
  it:

  ```python
  result = client.verify(scanned_text, layout=lease)
  if not result.valid:
      print(result.reason or "the code does not match")
  ```

- `pages` is a list of `PageImage(page_number, width, height, png)`, where `png` holds the decoded
  PNG bytes.
- `options` is a `RasterOptions` dict: `scale`, `maximumPages`, `maximumInputPixels`, `mimeType`,
  `maximumImageDimension`. To rasterize an image instead of a PDF, set `mimeType`.
- Binary inputs (`pdfs`, `append_pdfs`, `data`, `pdf`) accept `bytes`, `bytearray` or
  `memoryview`, which the SDK encodes as base64, or a string that is already base64 or a `data:`
  URL.
- `flow` is a flow as plain JSON data ([`spec/flow.schema.json`](https://github.com/tonysantana1492/pressjet/blob/main/spec/flow.schema.json)).
- `signing_time` must be a timezone-aware `datetime`; it is sent as RFC 3339 in UTC. A naive
  `datetime` raises `ValueError` rather than guessing its time zone. Use
  `datetime.now(timezone.utc)`.
- Every method also takes keyword-only `timeout` (seconds) and `headers` that apply to that call.

## Async

`AsyncClient` has the same options and methods, as coroutines:

```python
import asyncio
import pressjet


async def main() -> None:
    async with pressjet.AsyncClient() as client:
        pdf = await client.generate(invoice)


asyncio.run(main())
```

It runs the standard-library HTTP transport in a worker thread with `asyncio.to_thread`, so calls
never block the event loop and the package keeps zero dependencies. Cancelling a call stops
waiting at once; the worker thread finishes the HTTP exchange in the background, bounded by the
timeout.

## Errors

All errors derive from `pressjet.PressjetError`.

| Error | When |
| --- | --- |
| `APIError` | The server refused the request. Has `status`, `code`, `title`, `detail`, `request_id` and `retry_after` (seconds or `None`). |
| `PressjetConnectionError` | The server could not be reached or the connection failed. `__cause__` keeps the underlying error. |
| `PressjetTimeoutError` | The call, including retries, did not finish within the timeout. A subclass of `PressjetConnectionError`. |
| `ResponseTooLargeError` | The answer was larger than `max_response_bytes`. |

`APIError`'s message reads `"<title>: <detail> (<code>, request <request_id>)"`. `ErrorCode` is a
`str` enum of every code in [`spec/openapi.yaml`](https://github.com/tonysantana1492/pressjet/blob/main/spec/openapi.yaml); an answer that is not a
problem document gets the code `http_<status>`.

```python
from pressjet import APIError, ErrorCode

try:
    client.generate(invoice)
except APIError as error:
    if error.code == ErrorCode.INVALID_DOCUMENT:
        print("Fix the document:", error.detail)  # names a JSON Pointer such as /children/0
    else:
        raise
```

## Configuration

```python
pressjet.Client(
    api_key=None,  # else PRESSJET_API_KEY; sent as Authorization: Bearer <key>
    base_url=None,  # else PRESSJET_URL, else http://localhost:8080
    timeout=60.0,  # seconds for the whole call, including retries
    max_retries=2,  # after 429, 502, 503, 504 and connection failures
    max_response_bytes=128 * 2**20,  # larger answers raise ResponseTooLargeError
    headers=None,  # extra headers on every request
)
```

Options are keyword-only. Rendering is a pure function of the request, so every operation is
safe to retry. Retries wait for `Retry-After` when the server sends it, otherwise
`0.5 s × 2^attempt` with ±25% jitter, capped at 8 s, and never past the timeout: when the wait
would end after the deadline, the last error is raised at once. The timeout bounds each socket
operation and is checked between reads of the answer. Every request sends
`User-Agent: pressjet-python/<version>` and a fresh `X-Request-Id`, one per attempt (pass your own
in `headers` to trace a call). Requests go through `urllib.request`, so the standard proxy
environment variables apply.

`Client` holds no open connections; `close()` and the context manager exist so code can manage it
like other clients.

## Development

```sh
docker run --rm -v "$PWD/../..:/repo" -w /repo/sdks/python python:3.13-slim \
  sh -c "pip install -q -e '.[dev]' && pytest -q && mypy --strict src tests examples && ruff check ."
```

Integration tests run against a real server when `PRESSJET_TEST_URL` and `PRESSJET_TEST_API_KEY`
are set (`scripts/test-server.sh` starts one), and are skipped otherwise.

## License

Apache-2.0.

## HTML invoices

Use `client.html_multipart(html, images, settings=None)` to attach raw JPEG or PNG
bytes keyed by the image's `src`. See [binary HTML images](../../docs/html.md#binary-images).

`client.html("<p>Invoice 42</p>")` returns PDF bytes. `settings` is an `HtmlOptions` dict:
`stylesheets`, `images` (names mapped to bytes or base64), `omitImages`, `profile`
(`"standard"`, `"pdf-ua-1"` or `"pdf-a-2b"`), `conformance`, `created`, `lang` (when the HTML has
no `lang` attribute), `fontFamily`, `fonts` (`FontFace` dicts, as above), `engine`
(`"native"`, the default, or `"reference"` for the server's optional WeasyPrint service) and
`verification` (a `VerificationSettings` dict, as for `document`; the native engine only).

`client.check_html(html, settings)` sends the same HTML to `/v1/check` and returns the layout
report, the compiler's findings (`ignored_css`, `ignored_html`, `missing_resource`,
`font_substituted`, `invalid_request`) first. Its settings are an `HtmlCheckOptions` dict, the
same keys without `engine` and `verification`. [Deployment and limits](../../docs/self-hosting.md#print-existing-html)
