Ir para o conteúdo

tempest_fastapi_sdk.pdf

Geração de PDF a partir de templates HTML.

« Documentos e arquivos


PdfRenderer

PdfRenderer(
    *,
    template_dir: str | Path | None = None,
    assets: AssetPolicy | None = None,
    strict_assets: bool = True,
    max_concurrent: int = DEFAULT_MAX_CONCURRENT_RENDERS,
)

Renders HTML into PDF bytes.

The Jinja environment looks in the project's template_dir first and falls back to the bundled templates, so a project overrides receipt.html by dropping a file of that name next to its own — the same shadowing rule :class:~tempest_fastapi_sdk.utils.email.EmailUtils uses.

Attributes:

Name Type Description
template_dir Path | None

Project templates, searched first.

assets AssetPolicy

What a template may load. The default denies every fetch. Only its rules are shared between renders: each render collects refusals in its own :meth:~tempest_fastapi_sdk.pdf.AssetPolicy.for_render copy, so this instance's refusals is never read or cleared.

strict_assets bool

Whether a refused asset fails the render.

Initialize the renderer.

Parameters:

Name Type Description Default
template_dir str | Path | None

Directory whose templates shadow the bundled ones. None uses only the bundled set.

None
assets AssetPolicy | None

What templates may load. None builds a policy that denies every fetch, which is enough for the bundled templates — their CSS is inlined and images arrive as data: URIs. Safe to share across concurrent renders: each one collects its refusals in a private copy and reports them on its own AssetRefused (or warning), never on this object.

None
strict_assets bool

When True (default), a refused or unreachable asset raises after the page renders. The renderer otherwise swallows it and returns a document with a hole where the logo was, which is the wrong answer for an invoice.

True
max_concurrent int

Renders allowed to run at once.

DEFAULT_MAX_CONCURRENT_RENDERS

Raises:

Type Description
ValueError

If max_concurrent is below 1, or template_dir is not a directory.

environment property

environment: Environment

The Jinja environment, built on first use.

Autoescaping is on for every template: a customer name carrying < would otherwise reshape the document, and the caller of a PDF endpoint is frequently not the person the data came from.

Returns:

Name Type Description
Environment Environment

The configured environment.

Raises:

Type Description
ImportError

When Jinja2 is missing — install the [pdf] extra.

render_html_string

render_html_string(template: str, context: Mapping[str, Any]) -> str

Render a template to HTML, without producing a PDF.

Useful to preview a layout in a browser, and to test a template without paying for layout.

Parameters:

Name Type Description Default
template str

Template file name.

required
context Mapping[str, Any]

Values for the template.

required

Returns:

Name Type Description
str str

The rendered HTML.

Raises:

Type Description
TemplateNotFound

When neither the project nor the SDK has a template by that name.

render_html async

render_html(
    html: str, *, base_url: str | None = None, metadata: Mapping[str, Any] | None = None
) -> bytes

Render an HTML string to PDF bytes.

Parameters:

Name Type Description Default
html str

The document source.

required
base_url str | None

Base for resolving relative URLs. The asset policy still decides what may be fetched, so this widens nothing on its own.

None
metadata Mapping[str, Any] | None

Extra write_pdf options (pdf_identifier, custom_metadata, …). Passing any of these generally makes the output stop being byte-identical between runs.

None

Returns:

Name Type Description
bytes bytes

The PDF.

Raises:

Type Description
AssetRefused

When strict_assets is set and the document referenced something the policy denies.

ImportError

When WeasyPrint is missing.

render_template async

render_template(
    template: str,
    context: Mapping[str, Any],
    *,
    metadata: Mapping[str, Any] | None = None,
) -> bytes

Render a template to PDF bytes.

Parameters:

Name Type Description Default
template str

Template file name.

required
context Mapping[str, Any]

Values for the template.

required
metadata Mapping[str, Any] | None

Extra write_pdf options.

None

Returns:

Name Type Description
bytes bytes

The PDF.

Raises:

Type Description
TemplateNotFound

When the template does not exist.

render_document async

render_document(
    document: PdfDocument, *, metadata: Mapping[str, Any] | None = None
) -> bytes

Render one of the bundled documents.

The template comes from the payload's own type, so there is no second argument to keep in sync with it.

Parameters:

Name Type Description Default
document PdfDocument

A validated bundled document.

required
metadata Mapping[str, Any] | None

Extra write_pdf options.

None

Returns:

Name Type Description
bytes bytes

The PDF.

Raises:

Type Description
ValidationException

When document is a :class:PdfDocument subclass that names no template — the base class itself, or a subclass that forgot to set one.

TemplateNotFound

TemplateNotFound(
    message: str | None = None,
    *,
    code: str | None = None,
    status_code: int | None = None,
    details: dict[str, Any] | None = None,
    headers: dict[str, str] | None = None,
    message_key: str | None = None,
    message_params: dict[str, Any] | None = None,
    field: str | None = None,
)

Bases: NotFoundException

Raised when neither the project nor the SDK has the template.

bundled_document_names

bundled_document_names() -> list[str]

List the bundled documents by name.

Returns:

Type Description
list[str]

list[str]: Names accepted by tempest pdf render and the

list[str]

router, sorted.

document_schema

document_schema(name: str) -> type[PdfDocument]

Resolve a bundled document name to its schema.

Parameters:

Name Type Description Default
name str

A name from :func:bundled_document_names.

required

Returns:

Type Description
type[PdfDocument]

type[PdfDocument]: The schema to validate a payload with.

Raises:

Type Description
TemplateNotFound

When no bundled document has that name. The message lists the ones that exist, so a typo is one read away from fixed.

BUNDLED_TEMPLATE_DIR module-attribute

BUNDLED_TEMPLATE_DIR: Path = Path(__file__).parent / 'templates'

Directory holding the templates shipped with the SDK.

DEFAULT_MAX_CONCURRENT_RENDERS module-attribute

DEFAULT_MAX_CONCURRENT_RENDERS: int = 4

Renders allowed to run at once.

Layout is CPU-bound and single-threaded per document, so more workers than cores turns latency into queueing without adding throughput. Four matches the container sizes services here actually run on; raise it with max_concurrent when the host is bigger.

AssetPolicy dataclass

AssetPolicy(
    allow_dirs: tuple[Path, ...] = (),
    allow_remote: bool = False,
    remote_timeout: float = DEFAULT_REMOTE_TIMEOUT,
    max_bytes: int = DEFAULT_MAX_ASSET_BYTES,
    refusals: list[str] = list(),
)

Which URLs a template may resolve while rendering.

The default denies every fetch. That is deliberate: the bundled templates need no fetching at all — their CSS is handed to the renderer directly and images arrive as data: URIs — so the permissive settings exist for templates that genuinely need a local asset directory, and turning them on is a decision somebody makes on purpose.

Attributes:

Name Type Description
allow_dirs tuple[Path, ...]

Directories whose files a template may load through file://. A path is accepted only when it resolves inside one of them, so neither ../ nor a symlink pointing outside gets through.

allow_remote bool

Whether http:// and https:// may be fetched at all. False (default) — leaving it on means anything that reaches the template controls a request made from inside your network.

remote_timeout float

Seconds a remote asset has to answer.

max_bytes int

Ceiling for a single asset.

refusals list[str]

Human-readable reasons collected by :meth:refuse. :class:~tempest_fastapi_sdk.pdf.PdfRenderer never writes here: every render fetches through its own :meth:for_render copy and reports what it refused on the AssetRefused it raises (or the warning it logs), so this list only fills when you call :func:build_url_fetcher with this policy yourself.

refuse

refuse(url: str, reason: str) -> None

Record a refusal and raise, so the fetch does not succeed.

Parameters:

Name Type Description Default
url str

The URL the template asked for.

required
reason str

Why the policy denied it.

required

Raises:

Type Description
AssetRefused

Always. The renderer catches it, notes the asset is missing, and continues; the collected reason is what turns that into a real error at the end.

for_render

for_render() -> AssetPolicy

Return a copy with the same rules and an empty refusal list.

A policy is configuration plus a collector, and only the configuration may be shared. One instance handed to several concurrent renders would let each read — and clear — the others' refusals, so one request's error could carry another request's URL, presigned token included. Each render fetches through its own copy instead.

The copy is shallow and skips __post_init__: allow_dirs keeps the paths resolved when this policy was built, so a symlink swapped since then still cannot widen it, and a directory removed since then does not make the render raise ValueError.

Returns:

Name Type Description
AssetPolicy AssetPolicy

A policy enforcing the same rules, whose

AssetPolicy

refusals belongs to the caller alone.

take_refusals

take_refusals() -> list[str]

Return the refusals collected so far and reset the list.

Returns:

Type Description
list[str]

list[str]: One entry per refused URL, in the order the

list[str]

template referenced them.

resolve_local_path

resolve_local_path(url: str) -> Path

Map a file:// URL to a path inside an allowed directory.

Parameters:

Name Type Description Default
url str

The file:// URL from the document.

required

Returns:

Name Type Description
Path Path

The resolved, allowed path.

Raises:

Type Description
AssetRefused

When no directory is allowed, or the resolved path escapes all of them.

AssetRefused

AssetRefused(
    message: str | None = None,
    *,
    code: str | None = None,
    status_code: int | None = None,
    details: dict[str, Any] | None = None,
    headers: dict[str, str] | None = None,
    message_key: str | None = None,
    message_params: dict[str, Any] | None = None,
    field: str | None = None,
)

Bases: ValidationException

Raised when a template tried to load something the policy denies.

Carries every refusal from one render rather than the first, so a template with three blocked references is fixed in one pass.

UrlFetcher

Bases: Protocol

Callable returned by :func:build_url_fetcher for WeasyPrint.

Attributes:

Name Type Description
_fail_on_errors bool

Read by WeasyPrint to decide whether a failed fetch aborts the render or is only logged.

UrlFetcherResponse

Bases: Protocol

Subset of weasyprint.urls.URLFetcherResponse returned by a fetcher.

WeasyPrint does not ship a py.typed marker, so callers receive this protocol instead of Any and keep typed access to the response bytes and media type.

content_type property

content_type: str

MIME media type of the fetched asset.

read

read() -> bytes

Read the fetched asset bytes.

close

close() -> None

Close the underlying stream.

build_url_fetcher

build_url_fetcher(policy: AssetPolicy, *, fail_on_errors: bool = True) -> UrlFetcher

Build the fetch callable the renderer consults for every URL.

The returned callable carries _fail_on_errors, which WeasyPrint reads off it to decide whether a failed fetch stops the render or is only logged. Without it, a refused asset would silently become a document with a hole in it.

Parameters:

Name Type Description Default
policy AssetPolicy

The policy to enforce. Every refusal is appended to policy.refusals, so give each render its own collector — :meth:AssetPolicy.for_render — rather than one instance shared across concurrent calls. :class:~tempest_fastapi_sdk.pdf.PdfRenderer does exactly that on every render.

required
fail_on_errors bool

Sets _fail_on_errors on the returned callable. True (default) stops at the first refusal instead of laying out a document that is already missing something.

True

Returns:

Name Type Description
UrlFetcher UrlFetcher

A (url) -> UrlFetcherResponse callable matching

UrlFetcher

WeasyPrint's url_fetcher contract.

DEFAULT_MAX_ASSET_BYTES module-attribute

DEFAULT_MAX_ASSET_BYTES: int = 5 * 1024 * 1024

Ceiling for a single fetched asset, in bytes.

A template that pulls a 400 MB image does not fail — it renders, slowly, holding the whole thing in memory per concurrent request. 5 MiB fits any logo, signature or chart a document needs and turns the pathological case into an error instead of an outage.

DEFAULT_REMOTE_TIMEOUT module-attribute

DEFAULT_REMOTE_TIMEOUT: float = 5.0

Seconds a remote asset has to answer.

The default renderer timeout is 10 seconds per asset, which a page with twenty images turns into a request that outlives any sane gateway.

PdfDocument

Bases: BaseSchema

Base for a bundled document.

A subclass names the template it renders through, which is how :meth:~tempest_fastapi_sdk.pdf.renderer.PdfRenderer.render_document resolves one from the payload alone.

Attributes:

Name Type Description
template ClassVar[str]

Bundled template file name.

branding Branding

Shared appearance.

title str | None

Overrides the document's default heading.

ReceiptDocument

Bases: PdfDocument

A recibo — proof that an amount was paid.

Carries the amount in words, which is the element that keeps a figure from being altered after signing.

Attributes:

Name Type Description
number str | None

Receipt number.

issue_date date

Date printed and used in the closing line.

issuer Party

Who received the money and signs.

payer Party

Who paid.

amount_cents int

Amount received.

reference str

What the payment was for.

place str | None

City printed before the date.

QuoteDocument

Bases: PdfDocument

A quote / commercial proposal with priced lines.

Attributes:

Name Type Description
number str | None

Quote number.

issue_date date

When it was issued.

valid_until date | None

Last day the prices hold.

issuer Party

Who is quoting.

customer Party

Who receives the quote.

items list[LineItem]

The priced lines. At least one.

discount_cents int

Discount applied to the subtotal.

notes str | None

Free text under the table.

payment_terms str | None

How payment is expected.

subtotal_cents property

subtotal_cents: int

Sum of every line, before the discount.

Returns:

Name Type Description
int int

The subtotal, in cents.

total_cents property

total_cents: int

Subtotal minus the discount.

Returns:

Name Type Description
int int

The total, in cents.

ReportDocument

Bases: PdfDocument

A paginated tabular report.

The header and footer repeat on every page and the page number reads página X de Y, which is what makes a printed listing usable — somebody has to be able to tell a page is missing.

Attributes:

Name Type Description
heading str

Report title.

subtitle str | None

Line under the title.

generated_at date | None

Date printed in the header.

columns list[ReportColumn]

Column definitions. At least one.

rows list[dict[str, object]]

Row mappings keyed by ReportColumn.key. A missing key prints empty rather than failing — a report is often assembled from partial data.

totals dict[str, int]

Totals per column key, in cents for money columns. Printed in a final row.

ContractDocument

Bases: PdfDocument

A contract or written declaration.

Attributes:

Name Type Description
heading str

Document title.

preamble str | None

Paragraph before the clauses, usually qualifying the parties.

parties list[Party]

Who is bound. Printed in the header.

clauses list[Clause]

Numbered clauses. At least one.

place str | None

City in the closing line.

signed_on date | None

Date in the closing line.

signatories list[Signatory]

Signature blocks.

VoucherDocument

Bases: PdfDocument

A short receipt or label — half a page or less.

Attributes:

Name Type Description
heading str

Large text at the top.

subtitle str | None

Line under it.

fields dict[str, str]

Label/value pairs, printed in order.

qr_content str | None

Text to encode as the QR code — a verification URL, a Pix BR Code. Encoded by :func:~tempest_fastapi_sdk.pdf.qr_data_uri with the defaults calibrated for this template's 26mm box, once, while the document validates: a payload too long for any QR version fails there, as a validation error, not at render.

qr_data_uri str | None

QR code already encoded, as a data: URI — for a caller that needs its own encoder or settings. Mutually exclusive with qr_content.

note str | None

Small print at the foot.

height str

CSS height of the printed area.

qr_image property

qr_image: str | None

Return the data: URI the template embeds, if any.

The encoding is cached together with the content it came from, and reused only while qr_content still matches. model_copy(update= {"qr_content": ...}) runs no validator, so a cache keyed on nothing would keep printing the template's old QR on every copy — the natural way to issue a batch of tickets from one document.

Returns:

Type Description
str | None

str | None: The encoded qr_content, or qr_data_uri.

Party

Bases: BaseSchema

A person or company printed on a document.

Attributes:

Name Type Description
name str

Legal or trade name.

document str | None

CPF or CNPJ. Rendered through :func:~tempest_fastapi_sdk.pdf.formatting.format_document, which formats 11 and 14 digits and leaves anything else untouched.

address str | None

Free-form address, one line or several.

email str | None

Contact email.

phone str | None

Contact phone.

extra dict[str, str]

Additional labelled lines, printed in order — {"Inscrição estadual": "123"}.

Branding

Bases: BaseSchema

Appearance shared by every bundled document.

Attributes:

Name Type Description
logo_data_uri str | None

Logo as a data: URI. A URI rather than a path because the default asset policy fetches nothing — see :class:~tempest_fastapi_sdk.pdf.assets.AssetPolicy.

accent_color str

Colour of rules, table headers and totals.

footer_text str | None

Line printed at the foot of every page, next to the page number.

page_size str

CSS @page size value.

margin str

CSS @page margin value.

LineItem

Bases: BaseSchema

One priced line of a quote.

Attributes:

Name Type Description
description str

What is being charged for.

quantity float

How many. Fractional quantities are allowed (hours, kilos).

unit_price_cents int

Price of one unit, in cents.

unit str | None

Unit label shown next to the quantity.

total_cents property

total_cents: int

Line total, in cents.

Rounded half-up to the cent, because a fractional quantity times a cent price does not land on an integer and the printed line must add up to the printed total.

Returns:

Name Type Description
int int

quantity * unit_price_cents, rounded to the cent.

Clause

Bases: BaseSchema

One numbered clause of a contract.

Attributes:

Name Type Description
title str | None

Heading. Omit it for a plain paragraph.

body str

Text. Blank lines separate paragraphs.

Signatory

Bases: BaseSchema

One signature block at the foot of a contract.

Attributes:

Name Type Description
name str

Who signs.

role str | None

Their part — CONTRATANTE, Testemunha.

document str | None

CPF or CNPJ, printed under the line.

ReportColumn

Bases: BaseSchema

One column of a tabular report.

Attributes:

Name Type Description
key str

Key read from each row.

header str

Column heading.

align str

left, right or center.

money bool

Render the value as currency. The row must then carry an integer number of cents.

BUNDLED_DOCUMENTS module-attribute

BUNDLED_DOCUMENTS: dict[str, type[PdfDocument]] = {
    "contract": ContractDocument,
    "quote": QuoteDocument,
    "receipt": ReceiptDocument,
    "report": ReportDocument,
    "voucher": VoucherDocument,
}

Bundled document name to its schema.

Drives tempest pdf list and the router's document endpoint, so a new bundled template is registered in exactly one place.

qr_data_uri

qr_data_uri(
    content: str,
    *,
    error: QrErrorLevel = QR_ERROR_CORRECTION,
    scale: int = QR_SCALE,
    border: int = QR_BORDER,
) -> str

Encode content as a PNG QR code in a data: URI.

The result matches the pattern of :attr:~tempest_fastapi_sdk.pdf.VoucherDocument.qr_data_uri, so it can be passed there directly; :attr:VoucherDocument.qr_content <tempest_fastapi_sdk.pdf.VoucherDocument.qr_content> calls this with the defaults.

Example:

>>> from tempest_fastapi_sdk.pdf import qr_data_uri
>>> qr_data_uri("https://example.com/v/42").startswith(
...     "data:image/png;base64,"
... )
True

Parameters:

Name Type Description Default
content str

The text to encode — a verification URL, a Pix BR Code. Encoded exactly as given, never "optimized" into a Micro QR.

required
error QrErrorLevel

Error-correction level. See :data:QR_ERROR_CORRECTION for why the default is "h".

QR_ERROR_CORRECTION
scale int

Pixels per module. See :data:QR_SCALE.

QR_SCALE
border int

Quiet zone in modules. See :data:QR_BORDER.

QR_BORDER

Returns:

Name Type Description
str str

data:image/png;base64,....

Raises:

Type Description
ImportError

When segno (the [pdf] extra) is missing.

ValueError

When content is empty, or too long for any QR version at error — segno raises DataOverflowError, a ValueError.

QrErrorLevel module-attribute

QrErrorLevel = Literal['l', 'm', 'q', 'h']

ISO/IEC 18004 error-correction level: 7, 15, 25 or 30 % recovery.

QR_ERROR_CORRECTION module-attribute

QR_ERROR_CORRECTION: Final[QrErrorLevel] = 'h'

Default error correction: H, which recovers 30 % of the symbol.

A voucher is printed, folded, carried in a pocket and scanned off a crease — damage is the normal case, not the edge case. The price is density: H needs the most modules for a given payload, and the voucher's box is a fixed 26mm square, so the modules get smaller. With segno 1.6.6 and the default margin (deterministic, so exact):

========================= ===== ======= ======== Payload Level Version Module ========================= ===== ======= ======== 66-character URL H 8 0.49 mm 66-character URL M 5 0.63 mm 197-character Pix BR Code H 15 0.32 mm 197-character Pix BR Code M 10 0.43 mm ========================= ===== ======= ========

Both payloads at H, rendered through the voucher by WeasyPrint and rasterized at 100 dpi, decode with zxing-cpp; tests/pdf/test_qr.py repeats that at 150 dpi. A caller printing on a low-resolution thermal printer can pass error="m" to trade recovery for bigger modules.

QR_SCALE module-attribute

QR_SCALE: Final[int] = 8

Default pixels per module in the PNG.

The template sizes the image to 26mm whatever its pixel count, so the scale sets resolution, not size, and decoding did not change with it: scales 1, 2, 4 and 8 decoded the same payloads at the same dpi. What eight buys is margin against a viewer or print pipeline that smooths the image — the template asks it not to (image-rendering: pixelated makes WeasyPrint write /Interpolate false; without it, true), and not every consumer honors the flag. It costs about 4 KiB per document: the voucher with a Pix BR Code measured 13 KiB at scale 8 against 9 KiB at scale 1.

QR_BORDER module-attribute

QR_BORDER: Final[int] = 2

Default quiet zone, in modules, drawn inside the PNG.

ISO/IEC 18004 asks for four. The voucher supplies the rest: the image sits inside 6mm of white padding with a 5mm gap to the text, and two modules are at most 2.08mm — version 1, the largest module the box can hold (26mm over 25 modules). Drawing all four inside the image shrinks every module to pay for white the page already has: the 66-character URL at version 8 spans 53 modules with two a side and 57 with four, so each module loses 7 %.

format_cents

format_cents(cents: int, *, symbol: bool = True) -> str

Format an integer number of cents as Brazilian currency.

Parameters:

Name Type Description Default
cents int

Amount in cents. Negative values keep the sign in front of the symbol (-R$ 1,00), which is how a credit reads on a Brazilian statement.

required
symbol bool

Whether to prefix R$.

True

Returns:

Name Type Description
str str

The formatted amount, e.g. "R$ 1.234,56".

format_date

format_date(value: date | datetime) -> str

Format a date as dd/mm/aaaa.

Parameters:

Name Type Description Default
value date | datetime

The date to format.

required

Returns:

Name Type Description
str str

The formatted date.

format_date_long

format_date_long(value: date | datetime) -> str

Format a date the way a signed document spells it.

Parameters:

Name Type Description Default
value date | datetime

The date to format.

required

Returns:

Name Type Description
str str

E.g. "13 de agosto de 2026".

format_document

format_document(value: str) -> str

Format a CPF or CNPJ for display, leaving anything else alone.

Parameters:

Name Type Description Default
value str

Digits, with or without punctuation.

required

Returns:

Name Type Description
str str

000.000.000-00 for 11 digits, 00.000.000/0000-00

str

for 14, and the input unchanged otherwise — a foreign passport

str

number in this field must not be mangled into a shape it is not.

format_quantity

format_quantity(value: float, *, decimals: int = 3) -> str

Format a quantity the way an invoice line reads in Brazil.

A whole quantity prints without a decimal part (2, not 2,000); a fractional one uses a comma and drops trailing zeros (2,5). Printing 2.5 on a Brazilian document reads as a thousands separator to the person holding it.

Parameters:

Name Type Description Default
value float

The quantity.

required
decimals int

Maximum decimal places kept.

3

Returns:

Name Type Description
str str

The formatted quantity.

valor_por_extenso

valor_por_extenso(cents: int) -> str

Spell an amount in cents as Brazilian currency, in words.

This is the line a recibo carries under the figure, and it exists because a figure alone can be altered after signing.

Parameters:

Name Type Description Default
cents int

Amount in cents. Must be non-negative — a receipt for a negative amount is a different document.

required

Returns:

Name Type Description
str str

E.g. ``"mil duzentos e trinta e quatro reais e cinquenta e

str

seis centavos"``.

Raises:

Type Description
ValueError

If cents is negative, or above :data:MAX_EXTENSO_CENTS where the scale table runs out and the most significant group would be dropped in silence.

MAX_EXTENSO_CENTS module-attribute

MAX_EXTENSO_CENTS: int = 10 ** 15 - 1

Largest value :func:valor_por_extenso spells, in cents.

The scale table stops at trilhões; a value above it would silently lose its most significant group, so it raises instead.

MONTHS_PT_BR module-attribute

MONTHS_PT_BR: tuple[str, ...] = (
    "janeiro",
    "fevereiro",
    "março",
    "abril",
    "maio",
    "junho",
    "julho",
    "agosto",
    "setembro",
    "outubro",
    "novembro",
    "dezembro",
)

Month names used by :func:format_date_long, lowercase as in BR usage.

make_pdf_router

make_pdf_router(
    renderer: PdfRenderer,
    *,
    prefix: str = "/pdf",
    tags: list[str] | None = None,
    dependencies: Sequence[Any] | None = None,
    inline: bool = False,
    docs_locale: str | None = None,
) -> APIRouter

Build the router that renders the bundled documents.

Parameters:

Name Type Description Default
renderer PdfRenderer

The configured renderer. Its asset policy and template directory apply to every route here.

required
prefix str

URL prefix. Defaults to "/pdf".

'/pdf'
tags list[str] | None

OpenAPI tags. Defaults to ["pdf"].

None
dependencies Sequence[Any] | None

FastAPI dependencies applied to every route — this is where auth and rate limiting go. The router adds none by itself.

None
inline bool

Serve with Content-Disposition: inline so the browser displays the document instead of downloading it.

False
docs_locale str | None

Language of the OpenAPI summary and description text — "en-US" or "pt-BR". None (default) reads API_DOCS_LOCALE through :class:~tempest_fastapi_sdk.settings.ServerSettings, whose default is "en-US".

None

Returns:

Name Type Description
APIRouter APIRouter

Ready to mount with app.include_router.

safe_filename

safe_filename(name: str | None, *, default: str) -> str

Reduce a caller-supplied name to something safe in a header.

A filename reaches Content-Disposition, where a quote ends the quoted string and a newline splits the response into two. Directory separators matter less here — nothing writes the file server-side — but a name carrying them is never what the caller meant either.

Parameters:

Name Type Description Default
name str | None

The requested name.

required
default str

Used when name is missing or reduces to nothing.

required

Returns:

Name Type Description
str str

A name safe to interpolate, always ending in .pdf.

DocumentRequestSchema

Bases: BaseSchema

Request body for rendering a bundled document.

Attributes:

Name Type Description
payload dict[str, Any]

The document's fields, validated against the schema the document path parameter selects. Kept as a mapping here so one endpoint serves every bundled document; the real validation happens against the concrete schema, and its errors name the real fields.

filename str | None

Name suggested to the browser.

DocumentListSchema

Bases: BaseSchema

One entry of the bundled-document listing.

Attributes:

Name Type Description
name str

Name to pass as the path parameter.

schema_name str

Python class validating its payload.

json_schema dict[str, Any]

The JSON Schema of that class, so a client can build a form without reading the SDK.

PDF_MEDIA_TYPE module-attribute

PDF_MEDIA_TYPE: str = 'application/pdf'

Media type of every response this router produces.

extract_pdf_pages

extract_pdf_pages(data: bytes) -> list[PageText]

Read every page's text layer, keeping page boundaries.

Parameters:

Name Type Description Default
data bytes

The PDF file contents.

required

Returns:

Type Description
list[PageText]

list[PageText]: One entry per page, in document order. A page with

list[PageText]

no text layer comes back with an empty string rather than being

list[PageText]

dropped, so entry n is always page n.

Raises:

Type Description
ImportError

When the [pdf-read] extra is not installed.

PdfReadError

When the bytes are not a readable PDF.

extract_pdf_text

extract_pdf_text(
    data: bytes,
    *,
    max_chars: int | None = None,
    page_marker: str = DEFAULT_PAGE_MARKER,
    truncation_notice: str = DEFAULT_TRUNCATION_NOTICE,
    partial_page_notice: str = DEFAULT_PARTIAL_PAGE_NOTICE,
) -> str

Read a PDF into one string, annotated with page markers.

Truncation prefers page boundaries: whole pages are kept while they fit, because a page that survives is a page the model can cite. When not even the first page fits, the cut happens mid-page and partial_page_notice says so — returning nothing but a notice would hand the model an empty prompt, which is the failure this module exists to prevent.

The result never exceeds max_chars. The notice is part of the budget, not an addition to it.

Parameters:

Name Type Description Default
data bytes

The PDF file contents.

required
max_chars int | None

Ceiling on the returned length. None returns everything. Size it against the model's context window, not against the file — a window that overflows is silently truncated by the daemon instead, with no notice at all.

None
page_marker str

Template for the per-page separator. Receives page (one-based).

DEFAULT_PAGE_MARKER
truncation_notice str

Template appended when the cut lands on a page boundary. Receives page (last page included, always >= 1) and total.

DEFAULT_TRUNCATION_NOTICE
partial_page_notice str

Template appended when the cut lands inside page 1. Receives page and total.

DEFAULT_PARTIAL_PAGE_NOTICE

Returns:

Name Type Description
str str

The document text, or an empty string when no page carries a

str

text layer — the signature of a scanned document.

Raises:

Type Description
ImportError

When the [pdf-read] extra is not installed.

PdfReadError

When the bytes are not a readable PDF.

Notes

A budget too small to carry the notice beside a real slice of text returns raw document text cut to max_chars — no notice, and no page marker either. The marker is dropped for the same reason the notice is: it costs 16 characters that this regime does not have. Rendering it while it merely fit made the result shrink as the budget grew — measured on a 239-character page, max_chars=16 returned 16 characters of document and max_chars=17 returned one, the marker having eaten the rest. Paying more for less is not a trade-off a caller asked for.

PageText module-attribute

PageText = tuple[int, str]

A one-based page number paired with the text found on that page.

DEFAULT_PAGE_MARKER module-attribute

DEFAULT_PAGE_MARKER: str = '=== PAGE {page} ==='

Separator written above each page's text.

Not decoration: it gives a model something to cite when asked where a value came from. Override it to match the language of the surrounding prompt — a marker in a different language than the instruction is one more thing for the model to reconcile.

DEFAULT_TRUNCATION_NOTICE module-attribute

DEFAULT_TRUNCATION_NOTICE: str = (
    "=== DOCUMENT TRUNCATED AFTER PAGE {page} OF {total} ==="
)

Line appended when the text is cut at a page boundary.

A silent cut is the dangerous one: the model answers about the half it was shown, with no sign that a half is missing.

DEFAULT_PARTIAL_PAGE_NOTICE module-attribute

DEFAULT_PARTIAL_PAGE_NOTICE: str = '=== PAGE {page} OF {total} TRUNCATED MID-PAGE ==='

Line appended when even the first page did not fit max_chars.

Distinct from :data:DEFAULT_TRUNCATION_NOTICE on purpose: a reader (human or model) that sees this knows the last sentence may stop in the middle, so a value read near the end is not to be trusted the way a whole page is. Asking for a budget smaller than one page used to return only the notice — no document text at all, and 46 characters for a max_chars=40.

read_pdf_pages async

read_pdf_pages(
    data: bytes, *, extractor: PdfExtractorEnum = TEXT, password: str | None = None
) -> PdfPagesResult

Read a PDF page by page, optionally recovering layout and tables.

Both backends are synchronous and CPU-bound, so the work runs in a worker thread. A large scanned document can occupy that thread for seconds — this is a call to bound with a timeout, not one to fan out.

Parameters:

Name Type Description Default
data bytes

The PDF file contents.

required
extractor PdfExtractorEnum

Which backend to use. Defaults to :attr:PdfExtractorEnum.TEXT.

TEXT
password str | None

Password for an encrypted document.

None

Returns:

Name Type Description
PdfPagesResult PdfPagesResult

The document's pages, in order.

Raises:

Type Description
ImportError

When the extra the chosen backend needs is missing.

PdfDecryptError

When the document is encrypted and the password does not open it.

PdfExtractError

When parsing fails for any other reason.

PdfExtractorEnum

Bases: BaseStrEnum

Which extraction backend reads the document.

Attributes:

Name Type Description
TEXT

pypdf. Fast, pure Python, no layout recovery, no tables. Needs [pdf-read].

LAYOUT

pdfplumber. Slower, keeps layout positioning — which is what makes a multi-column page readable — and fills :attr:PdfPage.tables. Needs [pdf-layout].

PdfPage

Bases: BaseSchema

One page's extracted contents.

Attributes:

Name Type Description
page_number int

One-based page index, matching the document.

text str

Plain text found on the page. Empty for a page with no text layer — a scan — rather than absent.

tables list[list[list[str]]]

Tables found on the page, only populated by :attr:PdfExtractorEnum.LAYOUT. Outer list: tables; middle: rows; inner: cells. A cell the extractor read as empty is "", never None, so a row is always a list of strings.

PdfPagesResult

Bases: BaseSchema

A whole document, read page by page.

Attributes:

Name Type Description
extractor PdfExtractorEnum

Which backend produced this result.

page_count int

Number of pages read.

pages list[PdfPage]

One entry per page, in document order.

PdfDecryptError

PdfDecryptError(
    message: str | None = None,
    *,
    code: str | None = None,
    status_code: int | None = None,
    details: dict[str, Any] | None = None,
    headers: dict[str, str] | None = None,
    message_key: str | None = None,
    message_params: dict[str, Any] | None = None,
    field: str | None = None,
)

Bases: ValidationException

The PDF is encrypted and the supplied password was wrong or absent.

PdfExtractError

PdfExtractError(
    message: str | None = None,
    *,
    code: str | None = None,
    status_code: int | None = None,
    details: dict[str, Any] | None = None,
    headers: dict[str, str] | None = None,
    message_key: str | None = None,
    message_params: dict[str, Any] | None = None,
    field: str | None = None,
)

Bases: AppException

Parsing the PDF failed for a reason that is not a wrong password.