cd /news/developer-tools/show-hn-emboss-a-python-pdf-engine-t… · home topics developer-tools article
[ARTICLE · art-79785] src=github.com ↗ pub= topic=developer-tools verified=true sentiment=↑ positive

Show HN: Emboss – a Python PDF engine that keeps documents as structured data

Emboss, a new Python PDF engine, generates deterministic, byte-identical PDFs from structured data or Markdown without a browser, ensuring hash-verifiable and diffable output for CI workflows. The engine features native Knuth-Plass typesetting, PDF/UA accessibility by default, and embeds source data at the element level, with over 1,900 tests backing its closed-loop lifecycle from generation to verification.

read54 min views1 publishedJul 30, 2026
Show HN: Emboss – a Python PDF engine that keeps documents as structured data
Image: source

Turn structured or LLM-generated content into accessible, print-ready PDFs. Describe a document once, as a declarative spec or as Markdown, and Emboss handles typesetting, PDF/UA tagging, and the full PDF structure. Output is deterministic and byte-identical across runs, so every PDF is hash-verifiable and diffable in CI.

from emboss import Document

doc = Document(title="Q3 Report", style="finance")
doc.heading("Revenue Analysis", level=1)
doc.paragraph("Revenue increased 12% year over year.")
doc.table(headers=["Region", "Q3"], rows=[["North America", "$2.4M"]])
doc.save("report.pdf")

No coordinates. No manual page-break handling. No separate accessibility pass.

Emboss treats a PDF as structured, self-describing data with a deterministic, accessible, verifiable lifecycle, not as final ink. Six properties set it apart:

Native typesetting, no browser. Emboss is a real typesetting engine (Knuth-Plass line breaking, true font metrics), not HTML-to-PDF like WeasyPrint or Prince, and not headless Chrome. That is why output is deterministic and why there is no Chromium or Node attack surface. It runs anywhere, including locked-down servers. - Pure-Python core, one hard dependency. Onlyfonttools

is required; pydantic, pikepdf, cryptography, and the MCP SDK are optional extras. Easy to vendor, audit, and deploy in restricted environments. - Byte-identical output. No timestamps, no random ids; the file/ID

is derived from content. The same document produces the same bytes on every machine, so a filing can be hash-pinned and a change can be code-reviewed and diffed in CI. Almost no other PDF toolchain can say this. - Accessibility by default. The PDF/UA structure tree is derived from the same semantic model that drives layout, so tags cannot drift from content. This matters now that the EU Accessibility Act (June 2025) makes accessible PDFs mandatory for many businesses. Conformance is checked against the real veraPDF validator in CI, not mocked. - Data embedded at the element level, a table A table or chart can carry its own source CSV inside the PDF as a per-element attachment, so the figure a reader sees and the data an analyst needs are the same file and can never drift apart. Every other PDF flattens a table to ink; Emboss keeps the data live inside the document.isits spreadsheet. - Self-describing and node-keyed, one closed loop. Each document embeds its own spec, a per-character text index, and a stable id on every block. Generate, review, edit, sign, verify, and reproduce all key off that same structure, so the document stays coherent and machine-actionable through its whole lifecycle. Competitors give you one stage; Emboss gives you the loop, backed by 1,900+ tests.

The one-line version: an Emboss document is structured data you can also read.

What Makes Emboss DifferentFor Decision-MakersBuilt for EnterpriseHow Emboss ComparesWhy EmbossInstallationQuick StartEmbossSpec FormatDocument ElementsStyle PresetsBrandKitTypography EngineLayout SystemAccessibility and Conformance (PDF/UA)Self-Describing PDFsDocument Diff and RedlineReview Round-TripMCP ServerTemplatesExecutive DecksDomain FeaturesCross-References and NumberingSVG EmbeddingDiagramsMulti-Column LayoutMath NotationCode BlocksChartsPDF/A Archival OutputCMYK and Print ProductionDigital SignaturesIncremental AmendmentRedactionValidationAdaptersAPI ReferencePerformanceDevelopmentArchitectureRoadmapLicense

What it is. A Python engine that turns structured or LLM-generated content into accessible, print-ready PDFs, and treats the resulting PDF as structured data you can also read, not as final ink.

The problem it solves. Enterprises generate documents at scale (reports, invoices, filings, contracts) but lose the structure the moment they become PDFs: the data behind a table is gone, accessibility is a costly afterthought, edits mean regeneration, and "what changed / who signed / is this the real version" become manual audits. Emboss keeps the structure inside the document for its entire life.

Outcome How Emboss delivers it
Trust & audit
Byte-identical deterministic output (hash-pinnable filings), self-verifying provenance (reproduce ), append-only signatures that flag anything added but unsigned, and tables that refuse to render if the totals do not add up.
Lower cost
LLM edits are node-scoped: changing one paragraph in a 50-page report costs a paragraph's tokens, not the report's.
Data never drifts
Tables and charts embed their own source CSV; the figure an executive sees and the data an analyst verifies are the same file, the same version.
Compliance built in
PDF/UA accessibility, PDF/A archival, Factur-X/ZUGFeRD e-invoicing, and PAdES/eIDAS signatures, all in one engine (see the table below).
AI-native distribution
An MCP server makes every document callable from Claude: generate, query with certainty from the embedded structure, and edit, with explicit "not in this document" grounding so it never fabricates.
Standard What it is for Regulatory driver
PDF/UA-1
Accessibility (tagged, assistive-tech ready) EU Accessibility Act (June 2025), US Section 508, EN 301 549
PDF/A-2b, PDF/A-3b
Archival / long-term retention Records retention, filing ingest
Factur-X / ZUGFeRD (EN 16931)
Electronic invoicing (XML inside the PDF) France B2B mandate (Sept 2026), EU e-invoicing
PAdES B-B / B-T (ETSI EN 319 142)
Legally recognized e-signatures eIDAS (EU)
PDF/X-4 (ISO 15930-7)
Print / prepress output Commercial print
WTPDF 1.0 (Reuse)
Clean re-extraction for RAG / reuse AI and data pipelines

Every conformance claim is checkable: emboss verify out.pdf --conformance ua1

(also 2b

, 3b

) runs the real veraPDF validator, and the CI conformance job runs it on every push, not a mock.

Capability Emboss Typical PDF tools (ReportLab, WeasyPrint, Prince, headless Chrome)
Rendering Native typesetting engine, no browser HTML-to-PDF or a browser engine
Determinism Byte-identical, hash-verifiable Timestamps / random ids; not guaranteed
Accessibility PDF/UA tagged by default, veraPDF-checked Manual or absent
Data in the file Table carries its own CSV; spec + text index embedded Table flattened to ink; data gone
Edit after render Node-scoped patch, structure preserved Regenerate, or overlay hacks
Review round-trip Annotation resolves to node + character range No structure to resolve against
Signatures PKCS#7, DocMDP, PAdES, append-only coverage check Basic or none
AI integration First-class MCP server, grounded answers None
Dependencies Pure Python, fonttools only (rest optional)
Native libs / a browser runtime

Dependency security. The only hard dependency is fonttools

; pydantic

, pikepdf

, cryptography

, and mcp

are optional extras, and Emboss never imports two of their own transitive dependencies (pillow

, starlette

) directly. Because those two set no upper bound, Emboss pins a known-patched floor on them in its own [project.optional-dependencies]

(pillow>=12.3.0

, starlette>=1.3.1

), so pip install emboss-pdf[verify]

/ [mcp]

/ [dev]

/ [all]

resolves to a patched transitive chain rather than whatever floor those packages declare. pip-audit

against the full dependency set (base plus every extra) reports no known vulnerabilities.

Emboss is built around guarantees that matter once a PDF leaves a notebook and enters a filing, an audit trail, or a distribution pipeline -- not marketing claims, but specific, checkable code paths.

Deterministic, hash-verifiable output. The sameDocument

always renders to the same bytes: no timestamps, no random identifiers, the file/ID

derived from content. Two runs, two machines, one hash -- renders are byte-diffable in CI.PDF/UA tagged by default, with real conformance evidence. Every document ships a complete structure tree, andemboss verify out.pdf --conformance 2b

(alsoua1

,3b

) shells out to the actual veraPDF CLI and reports its verdict. This is not a simulated check: the CI conformance job installs the real veraPDF binary and runs the test suite against it on every push (.github/workflows/ci.yml

).Self-describing PDFs.doc.render(embed_spec=True)

embeds the document's own EmbossSpec JSON, its node-keyed layout map, and a reflowable Markdown twin as real/AF

file attachments.Document.from_pdf()

reconstructs an equivalent document from those attachments, and falls back to walking the PDF/UA structure tree -- recovering headings, paragraphs, tables, and lists in order -- if the attachments were stripped.Stable node ids and a queryable layout map. Every block gets a deterministic id and a page/bounding-box entry indoc.layout_map()

: the foundation for auditing, redlining, and programmatic review of what landed where on the page.Document diff and redline.diff_documents()

matches blocks between two documents by node id and classifies each as added, removed, or changed, with a word-level diff on text-bearing blocks;render_redline()

turns that into a real PDF with struck-through deletions, underlined insertions, margin change-bars on added content, and a summary page. Also available asemboss diff old.pdf new.pdf -o redline.pdf

from the command line.A reproducibility manifest.doc.render(manifest=True)

attaches a deterministicemboss-manifest.json

: the spec's sha256, the Emboss version, every embedded font's sha256, and any non-default render options.emboss.reproduce()

(andemboss reproduce report.pdf

) closes the loop: recover the document, re-render it, and structurally verify the two PDFs agree.Redaction by construction.Document.redact(rules)

matches whole blocks by node id, regex, predicate, or type and removes or replaces thembeforelayout, so redacted text never reaches a content stream -- not a black box painted over extractable text.DocMDP certification signatures.sign_pdf(..., certify=True, docmdp_permission=...)

produces an ISO 32000-1 certification signature declaring what changes (if any) are permitted after signing.PAdES (eIDAS) baseline signatures.sign_pdf_pades(...)

/amend_sign_pades(...)

produce ETSI EN 319 142 PAdES-BASELINE signatures (B-B, and B-T with an RFC 3161 timestamp): the EU-recognized profile for legal signature validity, on top of the existing append-only signing.Factur-X / ZUGFeRD e-invoicing.Document.attach_facturx(invoice)

embeds an EN 16931 Cross Industry Invoice XML on PDF/A-3, validated for arithmetic consistency before rendering (France B2B mandate, Sept 2026).PDF/X-4 print output and WTPDF 1.0.Document(pdfx=True, ...)

emits an ISO 15930-7 print/prepress file with a CMYK output intent;Document(wtpdf=True)

declares Well-Tagged PDF 1.0 Reuse conformance, andverify_wtpdf()

self-checks the tagging.BrandKit. A single versioned brand object (palette, fonts, logo) applies across every document built from it, so a rebrand touches one object instead of every document.CMYK and PDF/A archival output for print production and long-term retention pipelines.Long-form apparatus: numbered appendices, an alphabetized back-of-book index with resolved page numbers, a glossary with auto-linked first occurrences, and a visible table of contents with real page numbers and dot leaders.removes embedded files, provenance-revealing metadata, and internal structure-tree node ids from a rendered PDF before it goes to an external party.emboss strip

Emboss is not a general-purpose drawing library or an HTML-to-PDF converter. It is built for the pipeline where structured or model-generated content becomes a trustworthy document, and the comparison is most honest at the level of tool categories rather than head-to-head with a specific product.

Every claim in the Emboss column below is verifiable against this repository and its test suite. The right column describes what general-purpose PDF tooling (imperative drawing libraries and HTML/CSS engines) typically does; it is a category statement, not a claim about any one product, and specifics for a given tool should be verified against that tool.

Where Emboss is differentiated

Dimension Emboss Typical general-purpose PDF tools
Input a model can be constrained to JSON schema, provider-native structured outputs, Markdown Imperative code or HTML/CSS; no schema contract
Validation and repair of imperfect input Built in (truncation repair, per-block recovery) Not provided
Deterministic byte-identical output Yes, test-verified Generally not guaranteed
PDF/UA accessibility tagging On by default Opt-in or unavailable
Conformance evidence Real veraPDF check in CI and emboss verify
Varies; rarely built in
Self-describing, recoverable document embed_spec + from_pdf
No
Stable node ids and layout map Yes No
Document diff to a redlined PDF Yes No
Redaction that never enters the content stream Yes Typically overlay-based

Where established tools are ahead

This side matters just as much. Stated plainly:

Dimension Emboss Typical general-purpose PDF tools
Complex-script shaping (Arabic, Indic) Not supported Several engines support it
Arbitrary HTML and CSS input Not supported HTML/CSS engines accept it
Image formats PNG and JPEG Often broader
Production maturity New, released 2026 Many have 10 to 20 years in production

For turning structured or LLM-generated content into accessible, verifiable, auditable PDFs, Emboss covers ground the general category does not. For arbitrary HTML rendering, complex-script typesetting, or a long track record in production, an established tool is the safer choice.

Existing Python PDF libraries are page-description tools: you place ink at coordinates, and the resulting file has no idea that a given string was a heading. Accessibility tags, if available at all, are painted on after the fact and tend to disagree with the visible page.

Emboss inverts that. The semantic document is the source of truth, and both the visual output and the structure tree are derived from it. They cannot drift apart, because they come from the same description.

Deterministic output. The same document produces byte-identical PDFs across runs and machines. No timestamps, no random identifiers; the file /ID

is derived from content. This makes output hash-verifiable for filings and diffable in CI.

assert doc.render() == doc.render()   # always true

Structural correctness. Cross-reference offsets are recorded as bytes are written, so the xref table cannot disagree with the file.

Content never overflows. Everything is measured before anything is placed, so text running off the page is not a failure mode.

Tagged by default. Every document ships with a complete PDF/UA structure tree.

pip install emboss-pdf

Requires Python 3.10+ and fonttools

. Optional extras:

pip install emboss-pdf[all]       # pydantic + pikepdf + cryptography
pip install emboss-pdf[llm]       # pydantic schemas for LLM structured output
pip install emboss-pdf[verify]    # pikepdf for PDF structural verification
pip install emboss-pdf[signing]   # cryptography for digital signatures
pip install emboss-pdf[dev]       # full dev environment (pytest, mypy, ruff)

An OFL-licensed font set ships with the package (Source Serif 4, Source Sans 3, Source Code Pro; ~2.7MB, Latin, Greek, and Cyrillic coverage), plus Emboss Math, a modified subset of STIX Two Math carrying the mathematical alphanumeric glyphs used by \mathbb

/\mathcal

/\mathfrak

. Registering the set gives embedded fonts with full kerning and ligatures, no system font files required:

from emboss import Document
from emboss.bundled_fonts import register_bundled_fonts

doc = Document(title="Report")
register_bundled_fonts(doc.fonts)

The three text families are also available under the aliases "emboss serif"

, "emboss sans"

, and "emboss mono"

. Two lower-level helpers, bundled_font_path(family, bold=, italic=)

and BUNDLED_FAMILIES

, are available for callers that want the file paths directly.

from emboss import Document

doc = Document(title="Quarterly Report", author="Finance Team", style="finance")
doc.heading("Executive Summary", level=1)
doc.paragraph("Revenue grew 12% year over year, driven by enterprise expansion.")
doc.table(
    headers=["Metric", "Q3 2025", "Q3 2024", "Change"],
    rows=[
        ["Revenue", "$24.1M", "$21.5M", "+12%"],
        ["EBITDA",  "$8.2M",  "$6.9M",  "+19%"],
    ],
)
doc.bullets(["North America: +15%", "EMEA: +8%", "APAC: +11%"])
doc.save("quarterly_report.pdf")
python
from emboss.spec import Document, Heading, Paragraph, Table

doc = Document(
    title="Quarterly Report",
    style="finance",
    content=[
        Heading(text="Executive Summary", level=1),
        Paragraph(content="Revenue grew 12% year over year."),
        Table(
            headers=["Metric", "Value"],
            rows=[["Revenue", "$24.1M"], ["EBITDA", "$8.2M"]],
        ),
    ],
)
pdf_bytes = doc.render()

Tier 1: Spec prompt (full quality, recommended) -- pass the EmbossSpec format with your prompt:

from emboss import spec_prompt, Document

system = spec_prompt(style="finance")  # compact EmbossSpec description for LLMs
response = client.messages.create(
    model="claude-sonnet-5",
    system=system,
    messages=[{"role": "user", "content": "Create a Q3 financial report"}],
)
doc = Document.from_json(response.text)
doc.save("report.pdf")

Tier 2: One-liner (zero friction):

from emboss import generate

generate("Create a quarterly financial report",
         style="finance", output="report.pdf",
         provider="anthropic")  # or "openai"

Tier 3: Markdown (works with any LLM output):

from emboss import Document

md = llm.generate("Write a quarterly report...")  # any LLM, any provider
doc = Document.from_markdown(md, style="finance")
doc.save("report.pdf")

All three tiers produce identical PDF quality -- the typography engine (Knuth-Plass, optical margins, kerning) runs the same regardless of input format.

A whole directory, one PDF. A documentation team adds a build step rather than calling an API:

emboss build ./docs -o handbook.pdf

Files are concatenated in alphabetical order (numeric prefixes like 01-intro.md

work naturally), or from an explicit .order

file listing names one per line; the first file's front matter supplies the title and style. Available in Python as build_from_directory("./docs")

.

Code that cannot drift from its source. A fenced code block can load its body from a file instead of being typed inline:

python file=examples/settle.py lines=10-20 lines=A-B

selects a 1-based inclusive range; marker=NAME

selects a # region NAME

/ # endregion

(or # BEGIN NAME

/ # END NAME

) block instead. The included text is dedented and flows through the normal syntax highlighter, so a documented example is always the real code, not a copy that quietly went stale. Available directly as include_source(path, lines=..., marker=...)

.

Robust parsing. LLM output is messy; the parser is built for it:

doc = Document.from_json(
    text,
    strict=False,      # default: repair instead of raising
    smart=True,        # content intelligence: typography, tables, auto-style
    on_warning=print,  # one message per repair performed
)

spec_prompt()

teaches the exact vocabulary the validator accepts, so valid output is the common case- Synonym type tags and field spellings are normalized to the canonical vocabulary on both parse paths

  • Truncated JSON (cut off mid-generation) is repaired before parsing
  • When validation fails, recovery is per block: invalid blocks are coerced to paragraphs or dropped, the rest of the document renders strict=True

raises on any malformed input instead of repairing

Specs can also request layout features directly: "toc": true

inserts an auto-generated table of contents, and "page": {"columns": 2, "column_gap": 18}

sets multi-column geometry.

Documents are defined using EmbossSpec, a declarative JSON-serializable specification. Every document element is a typed Python dataclass that can be constructed programmatically, deserialized from JSON, or generated by an LLM via structured output.

The spec is the single source of truth. From it, Emboss derives:

  • The visual PDF (typography, layout, pagination)
  • The accessibility structure tree (PDF/UA tags)
  • HTML, Markdown, and DOCX exports (via adapters)
{
  "title": "Annual Report",
  "style": "corporate",
  "content": [
    {"type": "heading", "text": "Overview", "level": 1},
    {"type": "paragraph", "content": "Company performance exceeded targets."},
    {"type": "table", "headers": ["Q1", "Q2"], "rows": [["$1M", "$1.2M"]]}
  ]
}
Element Description Key Parameters
Heading
Section heading (H1-H6) text , level (1-6)
Paragraph
Body text with inline formatting content (str, TextRun, or list)
BulletList
Unordered list with nesting items (strings or sublists)
NumberedList
Ordered list with nesting items , start
Table
Data table with header row headers , rows , caption
Image
Embedded image source (path or bytes), width , caption
CodeBlock
Syntax-highlighted code code , language , line_numbers
MathBlock
LaTeX-style math notation source , display
Chart
Data visualization chart_type , labels , values
Callout
Admonition box (note/warning/tip) content , variant , title
Footnote
Numbered footnote content
SvgBlock
Inline SVG vector graphic source , width , height
BibliographyBlock
Formatted citation list citations
HorizontalRule
Visual separator thickness , color
PageBreak
Force a page break (optionally to a named page_styles geometry)
page_style
BlockQuote
Quoted passage set off with an accent bar content , attribution
CoverPage
Full-page title composition, forces a page break title , subtitle , authors , date , kicker
Abstract
Indented abstract block with a keywords line text , keywords
Authors
Centered grid of author entries authors (name, affiliation, email)
PullQuote
Large-type offset quotation text , attribution
StatTiles
Row of bordered statistic tiles, colored deltas stats (label, value, delta)
TableOfContents
Visible listing with dot leaders and page numbers title , depth , source (headings/figures/tables)
Appendix
Lettered section (Appendix A, B, ...) with its own A.1 numbering
title , content
Index
Back-of-book index resolved from index_terms marks
title
Glossary
Alphabetized term/definition list with auto-linked first occurrences entries , title
Diagram Node/edge graph with automatic layout, via doc.diagram(...)
nodes , edges , direction , caption
from emboss import Paragraph, TextRun

Paragraph(content=[
    TextRun(text="Regular text, "),
    TextRun(text="bold text", bold=True),
    TextRun(text=", "),
    TextRun(text="italic text", italic=True),
    TextRun(text=", and "),
    TextRun(text="colored text", color="2563eb"),
])

Seven professionally designed stylesheets are built in. Each encodes type scale, leading, table rules, and spacing so output looks authored without choosing a single measurement.

Preset Body Font Heading Font Body Size Alignment Use Case
legal
Times Times 11.5pt Justified Contracts, briefs, pleadings
finance
Helvetica Helvetica 10pt Left Reports, filings, data sheets
academic
Times Helvetica 11.5pt Justified Papers, dissertations, theses
corporate
Helvetica Helvetica 10.5pt Left Memos, policies, manuals
minimal
Helvetica Helvetica 9.5pt Left Data exports, compact reports
journal
Times Times 10.5pt Justified Journals, periodicals
brief
Helvetica Helvetica 10.5pt Left Executive briefs, one-pagers
doc = Document(style="finance")

from emboss import Style, StyleSheet
custom = StyleSheet(
    name="custom",
    body=Style(font_family="Helvetica", font_size=11.0, align="justify"),
    h1=Style(font_size=18.0, bold=True),
)
doc = Document(style=custom)

A BrandKit

is an immutable, versioned brand object layered on top of any style preset at render time. Set it once on the document and colors, fonts, and footer text propagate everywhere, so a rebrand is a single-object change rather than a find-and-replace across every document.

from emboss import Document, BrandKit

brand = BrandKit(
    name="Acme",
    version="2.1",
    primary="1f4e79",
    accent="1f8a70",
    ink="1a1a1a",
    muted="6b7280",
    heading_font="Emboss Serif",
    body_font="Emboss Sans",
    footer_text="Acme Corp -- Confidential",
)

doc = Document(title="Board Deck", style="corporate", brand=brand)
  • Heading and table-header colors take the brand primary

; body and secondary text takeink

/muted

. Any brand color that fails 4.5:1 contrast against white is automatically darkened for text use, while the raw brand color is kept for fills and rules. brand.series_palette(n)

returns a deterministic N-color chart palette derived fromprimary

andaccent

(or the explicitpalette

tuple, padded with derived colors if it runs short) -- charts under a brand stay on-brand without hand-picked colors.brand.to_dict()

/BrandKit.from_dict()

round-trip a brand kit through JSON (logo bytes travel as base64), for storing a brand centrally and it per render.

Emboss uses the Knuth-Plass algorithm from Knuth and Plass (1981) for optimal paragraph line breaking. Unlike greedy algorithms that fill each line independently, Knuth-Plass treats the paragraph as a shortest-path problem and minimizes total demerits across all lines:

greedy   widths: [216, 172, 168, 162, 176]   variance 367
optimal  widths: [216, 224, 202, 198]        variance 110

The algorithm:

  • Models text as Box (word), Glue (elastic space), and Penalty (breakpoint) items
  • Considers all legal breakpoints simultaneously
  • Penalizes abrupt spacing changes and tight/loose lines
  • Flags hyphen breaks and caps hyphen ladders: a large demerit stops runs of more than 3 consecutive hyphenated lines
  • Splits any word wider than the measure into character-level pieces (long URLs, identifiers), so lines never overflow even in narrow columns
  • Falls back to greedy breaking only for pathological input

The full Knuth-Liang en-US pattern set is bundled, plus a no-break list for domain terms (Inc.

, LLC

, EBITDA

, plaintiff

) that should never be split.

Glyph advances and kerning come from the font file (via fonttools). Text is emitted with the PDF TJ

operator so kerning pairs are actually applied between glyphs. Kerning reads GPOS pair positioning in full: class-based (Format 2) pairs resolved lazily and memoized, Extension (LookupType 9) wrappers unwrapped, and Value2 adjustments summed.

Base-14 font metrics are built in, so valid PDFs are produced with no font files present. The built-in AFM widths cover more than ASCII: en/em dashes, curly quotes, and accented Latin letters resolve to correct advances (accents via NFD decomposition to the base letter). For embedded fonts out of the box, see Bundled Fonts.

Automatic curly quotes, em/en dashes, fractions, ellipses, and non-breaking spaces before units. Applied during text processing, not as a post-process.

Automatic fi, fl, ff, ffi, and ffl ligature substitution on embedded fonts, gated per glyph on the font's cmap. Base-14 fonts carry no ligature glyphs and are left untouched.

Register a CJK-capable font (Noto Sans JP/SC/KR, or any TTF/OTF with CJK glyph coverage) and Chinese, Japanese, and Korean text renders correctly -- real glyphs, correct widths, correct line wrapping:

from emboss import Document, TextRun

doc = Document(title="Report")
doc.fonts.register("cjk", "/path/to/NotoSansJP-Regular.ttf")
doc.paragraph(TextRun("日本語のテストです。", font_family="cjk"))

Base-14 fonts (Helvetica, Times) carry no CJK glyphs; without a registered font, CJK characters are substituted out with a recorded warning rather than silently corrupting the page. Once a font is registered, the line breaker treats CJK Unified Ideographs, Hiragana, Katakana, and Hangul Syllables as break-opportune between any two characters (unlike Latin text, CJK carries no spaces between words), so long CJK passages wrap instead of overflowing. Which characters actually render depends on the registered font's own glyph coverage, as with any font -- a font covering only Japanese will not carry Simplified Chinese glyphs; Noto Sans CJK covers Chinese, Japanese, and Korean in one family if a document mixes scripts.

Not supported, stated honestly: right-to-left scripts (Arabic, Hebrew) and complex-script shaping (Indic scripts requiring glyph reordering and ligature substitution via a shaping engine like HarfBuzz) are a separate, larger project and remain unimplemented; RTL/complex-script text is still substituted with a warning today.

from emboss import PageSpec

page = PageSpec.letter()                        # 8.5 x 11 in
page = PageSpec.a4()                            # 210 x 297 mm
page = PageSpec.legal()                         # 8.5 x 14 in

page = PageSpec(
    width=612, height=792,
    margin_top=72, margin_bottom=72,
    margin_left=90, margin_right=72,
)

page = PageSpec.a4(columns=2, column_gap=18)

page = PageSpec.a4(landscape=True)

Also built in: PageSpec.a5()

and the tight-margin PageSpec.compact()

(A5, tuned for phone and tablet PDF readers).

A document can switch page geometry mid-flow for one wide table or diagram, then switch back, via page_styles

and PageBreak.page_style

:

doc = Document(
    title="Annual Report",
    page_styles={"wide": PageSpec.a4(landscape=True)},
)
doc.paragraph("Portrait content here.")
doc.page_break(page_style="wide")   # subsequent pages use the wide geometry
doc.table(headers=[...], rows=[...])
doc.page_break()                    # no page_style: reverts to the document default

Widow and orphan control: prevents single lines stranded at page tops/bottoms** Keep-with-next**: headings stay with their following paragraph** Keep-together**: atomic blocks (callouts, small tables) never split across pages** Table splitting**: large tables break across pages with header row repetition** Column balancing**: multi-column layouts balance content across columns

Every document is tagged with a complete PDF/UA structure tree:

  • Headings become /H1

through/H6

  • Paragraphs become /P

  • Tables become /Table

with/TH

and/TD

cells; header cells carry/Scope

  • Lists become /L

with/LI

,/Lbl

, and/LBody

  • Images, SVG blocks, and charts get /Figure

with the alt text emitted as/Alt

(a description is auto-derived when none is given) - Hyperlinks are written as /Link

annotations and tagged as/Link

structure elements withOBJR

references, as PDF/UA requires - Running heads, page numbers, Bates stamps, and watermarks are marked /Artifact

  • Tagged documents declare the PDF/UA-1 identifier in their XMP metadata
from emboss.pdf.verify import verify_pdf

result = verify_pdf(doc.render())
print(result)  # VerificationReport(ok=True, has_struct_tree=True, ...)

verify_pdf

is a structural check on the bytes Emboss just wrote (well-formed xref, matching object offsets, a present structure tree). It is not a conformance check by itself.

For actual ISO conformance, emboss.pdf.verify.verify_conformance

(and the emboss verify --conformance

CLI flag) invoke the real veraPDF CLI as a subprocess and parse its JSON report -- this is not a simulation, and it is not optional in CI: the conformance

job in .github/workflows/ci.yml

installs the official veraPDF binary and runs the test suite against it on every push and pull request.

emboss verify report.pdf --conformance 2b     # PDF/A-2b
emboss verify report.pdf --conformance ua1    # PDF/UA-1
emboss verify report.pdf --conformance 3b     # PDF/A-3b (with attachments)
python
from emboss.pdf.verify import verify_conformance

report = verify_conformance(doc.render(), flavour="ua1")
print(report.compliant)    # bool
print(report.violations)   # list[RuleViolation]: clause, description, count

Requires the verapdf

executable on PATH

, or VERAPDF_PATH

pointing at it; otherwise verify_conformance

raises with an install hint rather than silently skipping the check.

A rendered PDF can carry enough of its own provenance to be reconstructed later, without a side channel or a database lookup.

doc = Document(title="Q3 Report", style="finance")
doc.heading("Revenue", level=1)
doc.paragraph("Revenue increased 12% year over year.")

pdf_bytes = doc.render(embed_spec=True)

embed_spec=True

attaches three real /AF

(associated file) attachments to the PDF:

Attachment Contents /AFRelationship
emboss-spec.json
The canonical EmbossSpec JSON for exact reconstruction Source
emboss-layout.json
The node id -> page/bounding-box layout map Supplement
emboss-textmap.json
The node id -> per-character text-position index Supplement
emboss-doc.md
A reflowable Markdown twin of the document Alternative
from emboss import Document

recovered = Document.from_pdf("report.pdf")

Document.from_pdf

tries the embedded emboss-spec.json

first, an exact reconstruction. If it is missing (or strict=True

is not set and no attachment was ever embedded), it falls back to a degraded reconstruction by walking the PDF/UA structure tree and pulling text out of the content streams by marked-content id: headings, paragraphs, tables, lists, block quotes, footnotes, and code blocks come back with correct text and order (and their original stable node ids), even when styling and exact spec fields are lost. Pass strict=True

to require the exact path and raise instead.

layout = doc.layout_map()

Every top-level block gets a stable id -- an explicit one if you set it, otherwise a deterministic token derived from the element's type, position, and content, so the same document assigns the same ids on any machine and across runs. doc.layout_map()

resolves every id to where it actually landed on the page, in PDF coordinates. Node ids and the layout map are the mechanism behind from_pdf

recovery, the diff/redline tooling below, and any downstream annotation or programmatic-review workflow that needs to key off "this specific block, wherever it ends up."

Before a PDF leaves the building, emboss strip

removes all of this:

emboss strip report.pdf -o external.pdf
python
from emboss import strip_pdf

clean_bytes = strip_pdf(pdf_bytes)

strip_pdf

operates on already-rendered bytes: it drops the /AF

attachments and the /Names /EmbeddedFiles

tree, clears /Producer

and /Creator

plus the XMP CreatorTool

/document-history fields, and removes the structure tree's /IDTree

and per-element /ID

node ids -- while keeping Title, Author, and date fields. Output stays deterministic.

A single table or chart can carry its own source data inside the PDF, so the numbers a reader sees are one double-click away from the spreadsheet behind them. Set attach_data=True

:

doc.table(
    headers=["Quarter", "Bookings"],
    rows=[["Q1", "1,240"], ["Q2", "1,510"], ["Q3", "1,880"]],
    caption="Bookings by quarter",
    attach_data=True,   # embeds the table as an /AF CSV attachment
)

Emboss writes the table (or the chart's series) out as a CSV and embeds it as a real /AF

associated-file attachment on that element -- not a separate side file. The visible page is unchanged; the data rides along inside the same PDF.

How a reader opens the attachment. Attachment support is a PDF-reader feature, not something the document controls, so the steps differ by reader:

Reader How to open the embedded data
Adobe Acrobat / Reader View -> Show/Hide -> Side panels -> Attachments, then double-click the CSV
Firefox (built-in viewer) Click the paperclip icon in the left toolbar, then the file
Preview (macOS), Chrome No attachment UI -- these readers do not surface /AF files; use Acrobat or Firefox, or extract programmatically (below)

Any embedded file can also be pulled out without a viewer, straight from the bytes:

import io, pikepdf

with pikepdf.open(io.BytesIO(pdf_bytes)) as pdf:
    csv = pdf.attachments["table-1-data.csv"].get_file().read_bytes()

Beyond recovering a document's content, manifest=True

records what it takes to reproduce its exact rendered bytes:

pdf_bytes = doc.render(manifest=True)   # attaches emboss-manifest.json

The manifest is a deterministic JSON summary: the spec's sha256, the running Emboss version, every embedded font's sha256, and any render options that differ from their defaults (pdfa

, color_mode

, tagged

, toc

, page_number_format

, page_numbers

, front_matter_pages

). doc.reproducibility_manifest(...)

builds the same dict without rendering.

emboss reproduce report.pdf
php
from emboss import reproduce

report = reproduce("report.pdf")   # recover -> re-render -> structurally compare
print(report.ok)                   # bool

reproduce()

recovers the document from the PDF (via the embedded spec, or the degraded structure-tree path), re-renders it, and reports whether the two PDFs agree structurally -- same page count and same visible text per page, not a byte-for-byte match (attaching a manifest to the reproduction would itself shift bytes across the attachment boundary). A way to catch drift between what a PDF claims to be and what actually generated it.

A verifiable record of what generated a document -- which model, from what prompt, and who reviewed it -- folded into the same manifest:

from emboss import Document, GeneratorInfo

generator = GeneratorInfo.from_prompt(
    "Write a quarterly financial report",
    model="claude-sonnet-5", provider="anthropic",
    reviewed_by="R. Patel", reviewed_at="2026-07-29",
)
doc = Document(title="Q3 Report")
doc.paragraph("Revenue increased 12% year over year.")
pdf_bytes = doc.render(manifest=True, generator=generator)

GeneratorInfo.from_prompt

hashes the prompt (prompt_sha256

) rather than storing it, so the manifest proves a specific, reproducible input produced this output without disclosing potentially sensitive prompt content. reviewed_by

/reviewed_at

are plain caller-supplied strings, recorded only when a review is a deliberate act, never populated from the wall clock. Read it back with read_generator_info(pdf_bytes)

, which returns None

(not an exception) when no generator record is present -- an honest absence, not a guess. Document.generator = GeneratorInfo(...)

sets it once for every subsequent render; generate(..., manifest=True)

(the one-liner LLM tier) auto-populates model, provider, and the prompt hash unless a generator=

override is given.

This closes a real gap: as AI-content disclosure obligations broaden, no other PDF tool can prove which model produced a document and whether a human reviewed it. It composes with everything else here -- the reproducibility manifest is already signable via sign_pdf

/sign_pdf_pades

, so provenance can be part of a verifiable chain of custody, not a self-reported claim.

doc.patch(node_id, **changes)

returns a new Document

with the one block carrying node_id

replaced (dataclasses.replace(block, **changes)

under the hood) -- everything else, and the original document, untouched. Useful when a caller (an LLM given one block's id and a small diff, or an editing UI) only needs to change a single block without regenerating the whole spec.

diff_documents

matches blocks between two documents by their stable node id (assigning ids first if either side lacks them), and classifies each as added, removed, changed, or unchanged. A matched pair counts as "changed" only when both sides already carry the same id for that block -- typically because the id was assigned once (an explicit id=

, a prior render) and the block was edited in place rather than replaced.

from emboss import diff_documents, render_redline

result = diff_documents(old_doc, new_doc)
print(len(result.added), len(result.removed), len(result.changed))

redline_bytes = render_redline(old_doc, new_doc, result)

render_redline

renders the new document through the normal measure/paginate/render pipeline with revision marks baked in, not overlaid: deleted words struck through in crimson, inserted words underlined in forest green, added blocks marked with a real measured change-bar in the left margin, and a prepended summary page listing what was removed. Changed headings and pull quotes keep their new text with a redlined note paragraph underneath, since they carry no per-run styling to inline a word diff into.

emboss diff old.pdf new.pdf -o redline.pdf

A reviewer highlights, strikes out, or comments on a rendered PDF in whatever they already use -- Acrobat, Preview, Chrome. Because an Emboss PDF carries a text-position index, each annotation resolves back to the exact node and character range it covers, not a guess at a rectangle. This is the piece other PDFs cannot do: they have no structure to resolve a comment against.

Render with embed_spec=True

so the text map (emboss-textmap.json

) is present, then read the markup back:

from emboss.annotations import extract_comments, merge_comments

doc.save("v1.pdf", embed_spec=True)   # reviewers mark this up in their reader

comments = extract_comments("v1-legal.pdf")
comments = merge_comments(
    extract_comments("v1-legal.pdf"), extract_comments("v1-finance.pdf")
)

Each comment carries the reviewer, page, type, their text, and a resolution keyed to a stable node id and character range:

{"id": "c-07", "type": "strikeout", "author": "R. Patel", "page": 4,
 "node_id": "sec-risk.p3", "anchor_text": "exposure exceeds $4.2M",
 "char_range": [120, 143], "comment": "Overstates it, use the netted figure",
 "resolution": "exact", "status": "open"}

The resolution

is never omitted, so a mis-resolved comment cannot pass silently:

State Meaning Behaviour
exact
One node and a character range Patchable, phrase-level
node
One node, no character range Patchable, whole-node
spanning
Crosses two or more nodes Reports every node id; never split silently
unanchored
No content beneath the annotation Surfaced with page and rect; never dropped

Comments are never auto-applied -- that would ship a document nobody approved. Turning a free-text comment into a concrete replacement is a separate step (often a model); Emboss applies it deterministically and proves the change:

from emboss.review import propose_patches, apply_replacements, redline

propose_patches(doc, comments, replacements={})          # what would change
new_doc = apply_replacements(doc, comments, {"c-07": "the netted $2.8M"})
redline_pdf = redline(doc, new_doc)                       # proves the change

For an exact

resolution over plain text, only the objected-to phrase is spliced; everything else stays byte-identical. review_html(comments)

renders a self-contained triage report with the unresolved count loud at the top.

emboss render spec.json -o v1.pdf --embed-spec       # embeds spec, layout, text map
emboss review v1-legal.pdf v1-finance.pdf -o comments.json
emboss review v1-legal.pdf --html review.html        # triage view, no server
emboss apply comments.json --spec spec.json                       # propose only
emboss apply comments.json --spec spec.json --edits edits.json \
    -o v2.pdf --redline redline.pdf                               # apply and prove

emboss review

exits non-zero when any comment is unresolved, so a pipeline can gate on it. Flattened annotations (Preview's flattened export) are burned into the page and cannot be recovered by anything; a stripped PDF (no text map) resolves at page-and-rect granularity only, never a wrong guess.

Make Emboss documents callable from an AI assistant that speaks the Model Context Protocol, such as Claude Desktop. Configure it once, and the assistant can generate PDFs and answer questions about them from their embedded structure, not from guessing at rendered pixels -- because an Emboss PDF made with embed_spec=True

carries its own EmbossSpec JSON, a per-character text index, and any CSV data attached to its tables.

pip install "emboss-pdf[mcp]"
{
  "mcpServers": {
    "emboss": { "command": "emboss-mcp" }
  }
}

The server (built on the standard FastMCP API, served over stdio) exposes tools for the novel capabilities: render_document

, get_document_spec

and get_document_text

(exact answers from the embedded JSON), list_embedded_data

/ extract_embedded_data

(pull a table's source CSV back out), extract_review_comments

(annotations resolved to nodes), revision_history

(traceability), plus verify_document

and get_spec_schema

. Every query tool takes a file path, so one server answers questions about every PDF you generate. See the MCP Server guide for the step-by-step Claude Desktop setup.

The tools are plain, tested functions (emboss.mcp_server.dispatch

), callable from your own code without an MCP client.

Pre-configured document factories for common formats:

from emboss.templates import memo, report, letter, invoice

doc = memo(title="Project Update", author="Engineering Team")
doc.heading("Status", level=2)
doc.paragraph("All milestones are on track.")
doc.save("memo.pdf")

doc = invoice(title="Invoice #2024-0147", author="Acme Corp")
doc.table(
    headers=["Item", "Qty", "Price"],
    rows=[["Widget", "100", "$5.00"], ["Gadget", "50", "$12.00"]],
)
doc.save("invoice.pdf")

Available templates: memo

, report

, letter

, invoice

, academic_paper

, legal_brief

, slide_deck

, data_sheet

.

SlideDeck

builds a presentation deck from designed slide layouts, complete color themes, and a fit-to-slide guarantee: no slide ever spills onto a continuation page.

from emboss.slides import SlideDeck

deck = SlideDeck("Q3 Board Review", presenter="Ana Ruiz", date="Oct 2026", theme="boardroom")
deck.title_slide(subtitle="Board update")
deck.section_divider("Results")
deck.stat_slide("Key metrics", [("ARR", "$12.4M", "+18%"), ("Churn", "2.1%", "-0.3%")])
deck.bullet_slide("Highlights", ["Enterprise ARR up 22%", "Net retention at 118%"])
deck.chart_slide("Growth", chart_element)
deck.quote_slide("The window for category leadership is now.", attribution="CEO")
deck.closing_slide("Thank you", contact="ana@acme.com")
deck.save("board_deck.pdf")

Layouts:title_slide

,section_divider

,content_slide

(single orlayout="two-column"

),bullet_slide

,stat_slide

,chart_slide

,quote_slide

,code_slide

,closing_slide

.Four built-in themes, each a complete, WCAG-contrast-checked color system:boardroom

(navy and gold),horizon

(dusk blue and coral),carbon

(near-black and electric blue),meadow

(forest and spring green). Aliasesdefault

,dark

,light

,minimal

resolve to one of the four.Fit-to-slide: every slide is measured after composition; if it would overflow, type and spacing scale down in steps (to a floor of 0.8x) until it fits one slide, or a clear error names which slide and by how much it overflowed rather than silently clipping content.- Charts dropped into a themed deck automatically pick up the theme's chart palette unless colors are set explicitly. deck.build()

returns the underlyingDocument

for further customization before.render()

/.save()

.

from emboss import Document, LegalFeatures, PageSpec

doc = Document(
    title="Memorandum of Understanding",
    style="legal",
    page=PageSpec.letter(margin_left=108),
    legal=LegalFeatures(
        watermark="CONFIDENTIAL",
        watermark_opacity=0.12,
        line_numbering=True,
        bates_prefix="ACME-",
        bates_start=1,
        bates_digits=6,
        bates_position="bottom-right",
    ),
)

Bates numbering: sequential identifiers for legal discovery** Line numbering**: continuous line numbers in the left margin (court filings)** Watermarks**: diagonal text overlay with configurable opacity

The line between a nice PDF and a controlled document (ISO 9001, IEC 62304, medical device, aerospace) is a control block: a document identifier, version, status, an approvals table, and a revision history.

from emboss import Document, Approval, RevisionEntry

doc = Document(title="Design History File", style="legal")
doc.document_control(
    doc_id="DHF-2026-014",
    version="3.0",
    status="Approved",
    effective_date="2026-08-01",
    classification="Controlled",
    owner="Quality Engineering",
    approvals=[
        Approval(name="R. Patel", role="Quality Manager", date="2026-07-28"),
        Approval(name="M. Osei", role="Regulatory Affairs", date="2026-07-29"),
    ],
    revisions=[
        RevisionEntry(version="2.0", date="2026-03-01", author="R. Patel",
                      summary="Added risk analysis section"),
        RevisionEntry(version="3.0", date="2026-07-28", author="R. Patel",
                      summary="Updated verification protocol"),
    ],
)

The block expands into real, fully tagged tables before layout -- a metadata grid, an Approvals table, and a Revision History table -- so pagination, header repetition on long revision histories, and PDF/UA /Table

tagging all come from the same machinery an ordinary doc.table(...)

uses, not a hand-drawn panel. It round-trips through the JSON spec and renders in the HTML and Markdown adapters.

Fillable text, checkbox, and dropdown fields for intake and KYC-style documents, laid out in the normal document flow rather than manually positioned:

doc.heading("Client Intake", level=1)
doc.text_field("full_name", label="Full name")
doc.checkbox_field("accredited_investor", label="I am an accredited investor")
doc.dropdown_field("entity_type", options=["Individual", "Corporation", "Trust"],
                   label="Entity type")

Each field produces a genuine AcroForm widget -- /FT /Tx

, /Btn

, or /Ch

with the correct /V

, /Ff

flags (required

, multiline

, the combo bit for a dropdown's /Opt

), and a real checkbox /Yes

//Off

appearance -- not a drawn rectangle. Every field is tagged as real PDF/UA structure (a Form

-mapped structure element with the same object-reference mechanism link annotations already use), so a document containing form fields stays PDF/UA-tagged with no regression. Fields coexist with signature fields in one /AcroForm

, and a duplicate field name across a document raises rather than producing an AcroForm two fields silently share.

A visual invoice PDF can carry a machine-readable EN 16931 Cross Industry Invoice XML inside it, for the France B2B mandate (September 2026) and EU electronic invoicing. Document.attach_facturx

embeds the XML as a factur-x.xml

/AF

attachment, forces PDF/A-3, and writes the ZUGFeRD/Factur-X XMP metadata.

from emboss import Document, Invoice, Party, InvoiceLine

invoice = Invoice(
    invoice_number="INV-2026-001",
    issue_date="20260115",
    currency="EUR",
    seller=Party(name="Acme GmbH", country_code="DE", vat_id="DE123456789"),
    buyer=Party(name="Beispiel SA", country_code="FR"),
    lines=[
        InvoiceLine(name="Consulting", quantity="10", unit_price="150.00",
                    net_amount="1500.00", tax_rate_percent="19"),
    ],
)

doc = Document(title="Invoice INV-2026-001", style="finance")
doc.attach_facturx(invoice)          # embeds factur-x.xml, forces PDF/A-3
doc.save("invoice.pdf")

Invoice.validate()

(called before any XML is produced) reconciles the line net amounts, the per-rate tax, and the grand total, so an invoice whose numbers do not add up raises rather than emitting a non-conformant document. The default profile is EN 16931 (COMFORT); MINIMUM, BASIC, and EXTENDED select the guideline URN. build_cii_xml(invoice)

returns the XML directly if you want to inspect or transmit it on its own.

from emboss import HeaderFooter

doc = Document(
    header=HeaderFooter(
        left="Acme Corp",
        center="Confidential",
        right="{page} of {pages}",
        separator=True,
    ),
    footer=HeaderFooter(
        center="Generated by Emboss",
    ),
)

Placeholders {page}

and {pages}

are resolved at render time.

Automatic figure, table, and equation numbering with label-based cross-references:

from emboss import Document, Table, Image
from emboss.crossref import CrossReferenceIndex

doc = Document(title="Research Paper", style="academic")
doc.table(
    headers=["Variable", "Value"],
    rows=[["x", "42"]],
    caption="Experimental results",
    label="results-table",
)
doc.paragraph("As shown in @results-table, the value of x is 42.")

The @label

syntax resolves to "Table 1", "Figure 2", etc., with automatic counter tracking via NumberingContext

. Captions are numbered automatically ("Figure 1: ...", "Table 1: ..."), and each @label

reference becomes a clickable in-document link (a GoTo action targeting the labeled element's page).

Section numbering is available by setting number_sections = True

on the document; headings are numbered hierarchically and @label

references to sections resolve to the section number.

Embed SVG vector graphics as native PDF paths, no rasterization:

doc.svg("""
<svg width="200" height="100">
  <rect x="10" y="10" width="80" height="80" fill="#2563eb"/>
  <circle cx="150" cy="50" r="40" fill="#dc2626"/>
</svg>
""", width=200, height=100)

A substantial subset of static SVG is supported, using only the standard library:

Shapes:rect

,circle

,ellipse

,line

,polygon

,polyline

.Full path data:path

supportsM/L/H/V/C/S/Q/T/A/Z

, including relative lowercase forms and implicit command repetition -- elliptical arcs (A

) are converted to cubic Bezier segments.Transforms:translate

,scale

,rotate

(with an optional pivot),skewX

,skewY

, andmatrix

, composed correctly through nested<g>

groups.Gradients:linearGradient

andradialGradient

, includinghref

stop inheritance, rendered as banded fills;gradient_shading

builds the equivalent true PDF type 2/3/Shading

dictionary for callers wiring page resources directly.Clipping:clipPath

compiles to a real PDF clip (W n

).Opacity: element and groupopacity

/fill-opacity

/stroke-opacity

emit realExtGState

(gs

) operators, not simulated transparency.Text:<text>

withtext-anchor

, using base-14 metrics mapped from the requestedfont-family

.: reference-based reuse with a bounded reference depth to guard against cycles.<use>

/<defs>

  • Excluded by design: filters, animation, masks, patterns, and CSS beyond the style

attribute.

Node/edge graphs (architecture diagrams, flowcharts, state machines) with automatic layout: no coordinates to compute by hand.

doc.diagram(
    nodes=[
        {"id": "api", "label": "API Gateway"},
        {"id": "auth", "label": "Auth Service"},
        {"id": "db", "label": "User Store", "shape": "store"},
        {"id": "ok", "label": "Response", "shape": "rounded"},
    ],
    edges=[
        {"src": "api", "dst": "auth", "label": "verify"},
        {"src": "auth", "dst": "db"},
        {"src": "db", "dst": "auth", "style": "dashed"},
        {"src": "auth", "dst": "ok"},
    ],
    caption="Login flow",
)

Layout is automatic: a longest-path layering assigns nodes to layers, barycenter sweeps order nodes within each layer to reduce edge crossings, and cycles are handled by reversing back edges for layout purposes while rendering them along their true direction.Node shapes:box

,rounded

,decision

(diamond),store

(database cylinder),start_end

(pill).Edges: solid orstyle="dashed"

, with optional labels; self-loops render as a small loop back into the node.- Renders as native vector graphics (an SvgBlock

under the hood), with a deterministic, auto-generated/Alt

description summarizing the node and edge count -- no diagram ships without accessible alt text. - Also available as a fenced Markdown block: a ```` diagram`

fence withid: Label [shape]

node lines,a -> b: label

(or-->

for dashed) edge lines, and an optionaldirection: right

line. - Lower-level API: emboss.diagrams.layout_diagram

,render_diagram_svg

,diagram_alt_text

, and theDiagramNode

/DiagramEdge

dataclasses.

Beyond the general flowchart, three purpose-built diagram types cover most technical-documentation needs. Each is described as a plain node/edge list, laid out automatically, and rendered as native vector graphics with auto-generated /Alt

text.

Cloud / deployment architecture -- doc.architecture_diagram(nodes, edges, groups=...)

. Nodes carry a service

glyph (compute

, database

, storage

, queue

, gateway

, cache

, cdn

, function

, loadbalancer

, user

, external

, generic

) and an optional group

; groups nest to draw zones such as a VPC wrapping public and private subnets. Edges are solid or dashed

with labels. Relabel the nodes and the same layout describes an AWS, Azure, or GCP topology.

doc.architecture_diagram(
    nodes=[
        {"id": "alb", "label": "ALB", "service": "loadbalancer", "group": "public"},
        {"id": "ec2", "label": "EC2 - App", "service": "compute", "group": "private"},
        {"id": "rds", "label": "RDS", "service": "database", "group": "private"},
    ],
    edges=[("alb", "ec2"), ("ec2", "rds", "SQL")],
    groups=[
        {"id": "public", "label": "Public Subnet", "node_ids": ["alb"]},
        {"id": "private", "label": "Private Subnet", "node_ids": ["ec2", "rds"]},
        {"id": "vpc", "label": "VPC", "node_ids": ["public", "private"]},
    ],
    caption="AWS three-tier architecture",
)

Sequence -- doc.sequence_diagram(participants, messages)

. Draws one lifeline per participant; messages carry a style

of sync

(solid, filled arrowhead), async

(open arrowhead), or return

(dashed), and activate=True

opens an activation bar on the receiver. Self-messages render as a loop.

doc.sequence_diagram(
    participants=[{"id": "u", "label": "Client"}, {"id": "api", "label": "API"}],
    messages=[
        {"from": "u", "to": "api", "label": "POST /settle", "style": "sync",
         "activate": True},
        {"from": "api", "to": "u", "label": "202 Accepted", "style": "return"},
    ],
)

Entity-relationship -- doc.er_diagram(entities, relationships)

. Each entity lists typed attributes with a key

of PK

/FK

; each relationship carries a label and from_card

/to_card

cardinality (1

, N

, ...).

doc.er_diagram(
    entities=[
        {"id": "account", "name": "Account", "attributes": [
            {"name": "id", "key": "PK", "type": "uuid"},
        ]},
        {"id": "payment", "name": "Payment", "attributes": [
            {"name": "account_id", "key": "FK", "type": "uuid"},
        ]},
    ],
    relationships=[
        {"from": "account", "to": "payment", "label": "makes",
         "from_card": "1", "to_card": "N"},
    ],
)

All three are exposed in the Pydantic schema and the LLM spec prompt, so a model can emit them directly as architecture_diagram

/ sequence_diagram

/ er_diagram

spec blocks.

A ```` mermaid`

fence in Markdown, or parse_mermaid(source)

directly, parses common Mermaid diagram source onto Emboss's own diagram builders above, so the large existing corpus of docs already written in Mermaid renders as native vector graphics, not an image.

mermaid flowchart LR A[Start] --> B{OK?} B -->|yes| C[(Store)] B -.->|no| A flowchart

/graph

(with TD

/TB

/BT

/LR

/RL

direction), sequenceDiagram

(->>

sync, -->>

return, -)

async, +

/-

activation), and erDiagram

(attribute blocks and ||--o{

-style cardinality) are supported. An unsupported kind (classDiagram

, stateDiagram

) raises MermaidError

naming it, rather than rendering something wrong. In Markdown, a diagram that fails to parse degrades to a code block showing the source, with a warning via on_warning

, unless strict=True

is passed to parse_markdown

.

from emboss import parse_mermaid

block = parse_mermaid(source)   # an SvgBlock, addable with doc.add(block)
python
from emboss import Document, PageSpec

doc = Document(
    title="Newsletter",
    page=PageSpec.a4(columns=2, column_gap=18),
)
doc.heading("Top Stories", level=1)
doc.paragraph("Content flows automatically across columns...")

Content flows between columns automatically. Column-spanning elements (headings, wide tables) are supported via the column_span

style property.

LaTeX-style math rendering with support for common commands:

doc.math(r"E = mc^2")
doc.math(r"\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2}")
doc.math(r"\begin{pmatrix} a & b \\ c & d \end{pmatrix}")
doc.math(r"f(x) = \begin{cases} x^2 & x \ge 0 \\ -x & x < 0 \end{cases}")

Supported: superscripts, subscripts, fractions (\frac

), square roots (\sqrt

), integrals, summations, Greek letters, \text{}

, \mathcal

, \mathbb

, \mathbf

, \mathrm

, \operatorname

, and more.

\begin{...}

with &

column separators and \\

row breaks:

  • Matrices: matrix

,pmatrix

,bmatrix

,vmatrix

,Bmatrix

  • Piecewise: cases

  • Aligned equations: aligned

,align

,align*

,split

  • Gathered equations: gathered

,gather

,gather*

\mathbb

, \mathcal

/\mathscr

, and \mathfrak

render actual double-struck, script, and fraktur glyphs (Unicode Mathematical Alphanumeric Symbols, with the letterlike-symbol exceptions like \mathbb{R}

and \mathcal{H}

mapped to their reserved codepoints) from the bundled Emboss Math font, not a font-substitution approximation:

doc.math(r"\mathbb{R}^n \to \mathcal{H}")

Presentation MathML is accepted alongside LaTeX. parse_math

(and MathBlock

/doc.math

) auto-detects a source starting with <math

and routes it through emboss.mathml.parse_mathml

into the same AST the LaTeX parser produces, so layout and rendering are shared:

doc.math('<math><mfrac><mi>a</mi><mi>b</mi></mfrac></math>')

Supported elements: mi

/mn

/mo

tokens, mrow

, mfrac

, msqrt

/mroot

, msup

/msub

/msubsup

, munder

/mover

/munderover

(mapped onto the display-limit machinery), mtable

/mtr

/mtd

, mfenced

, mtext

, mspace

, mstyle

, and semantics

(annotations ignored). HTML5/MathML named entities are expanded and namespaces stripped, using only the standard library; malformed input raises ValueError

rather than rendering garbage.

Layout comes from real metrics, not approximations: glyph dimensions use the base-14 AFM tables (Times italic for variables, Times roman for text, Symbol for operators), inter-atom spacing follows the TeX spacing classes (thin, medium, thick), and in display mode \sum

, \prod

, \int

, and \lim

place their limits above and below the operator.

Syntax-highlighted code with optional line numbers:

doc.code_block(
    code='def hello():\n    print("Hello, world!")',
    language="python",
    line_numbers=True,
)

Built-in highlighters for Python, JavaScript, TypeScript, SQL, JSON, HTML, CSS, Rust, Go, Java, C, and more.

Data visualization rendered as native PDF vector graphics:

doc.chart(
    chart_type="bar",
    labels=["Q1", "Q2", "Q3", "Q4"],
    values=[120, 150, 180, 210],
    caption="Quarterly Revenue ($M)",
)

Chart types: bar

, line

, pie

, scatter

.

A finance or exec-brief pipeline produces figures from a data export, not a hand-typed list -- table_from_csv

/chart_from_csv

read a CSV path, file object, CSV text, or a pandas DataFrame (duck-typed; pandas stays an optional, never-required dependency) directly into a table or chart:

doc.table_from_csv("bookings.csv", caption="Bookings by region", verify_totals=True)
doc.chart_from_csv("bookings.csv", chart_type="bar", attach_data=True)

Because both methods ultimately call the existing Document.table

/Document.chart

, every other keyword composes for free: verify_totals=True

refuses to render if a CSV-sourced Total row doesn't add up, exactly as it would for a hand-typed table; attach_data=True

embeds the exact CSV that fed the chart inside the PDF, so the visual and its source data travel as one file. Currency, thousands separators, and percent signs in CSV cells ("$1,234.50"

) are parsed automatically (the same arithmetic.parse_number

the totals check uses), so a raw finance export plots and totals correctly without pre-cleaning. chart_from_csv

treats the first column as labels and every other numeric column as a series by default, or accepts explicit value_columns=

/category_column=

by name or index.

Generate PDF/A-2b compliant output for long-term archival:

doc = Document(
    title="Annual Filing",
    pdfa=True,       # enables PDF/A-2b conformance
    tagged=True,     # required for PDF/A
)

Includes XMP metadata, sRGB ICC output intent, and all required PDF/A catalog entries.

Set color_mode="cmyk"

and every draw path (text, rules, tables, charts, shapes) emits CMYK operators (k

/K

) instead of RGB:

from emboss import Document, Paragraph, TextRun

doc = Document(
    title="Print Run",
    color_mode="cmyk",
    pdfa=True,   # output intent switches to a CMYK profile (N=4)
)
doc.paragraph([TextRun(text="Brand red", color="cmyk(0,100,95,0)")])
doc.paragraph([TextRun(text="Spot ink", color="spot(PANTONE 485 C,0,100,95,0)")])
doc.save("print_run.pdf")

cmyk(c,m,y,k)

color strings work anywhere a color is accepted; RGB colors are converted when the document is in CMYK modespot(name,c,m,y,k)

defines a named spot color, emitted as a PDF Separation color space with a CMYK fallback- PDF/A output in CMYK mode uses a CMYK OutputIntent instead of sRGB

  • Redaction and signature appearances follow the document's color mode

Sign PDFs with X.509 certificates. A visual signature field is placed at render time; the PKCS#7 signature is injected afterward:

from emboss import Document, SignatureField
from emboss.signing import sign_pdf

doc = Document(
    title="Approval",
    signatures=[
        SignatureField(
            page_index=0, x=360, y=60, signer_name="Jane Doe",
            reason="Approved", location="San Francisco",
        )
    ],
)
pdf_bytes = doc.render()

signed_bytes = sign_pdf(pdf_bytes, "signer-key.pem", "signer.pem")

Requires pip install emboss-pdf[signing]

.

sign_pdf(..., certify=True, docmdp_permission=2)

produces an ISO 32000-1 12.8.2.3 certification signature: the /DocMDP entry it asserts states what changes (if any) are permitted after signing (1

forbids any further changes, 2

-- the default -- permits form fill-in and further signing, 3

additionally permits annotations). A certifying signature must be the document's first signature field; build_docmdp_reference

, build_certifying_signature

, and build_perms_dict

(in emboss.signing

) build the underlying /Reference, signature field, and catalog /Perms entries for callers assembling the PDF at a lower level than Document.render

.

Keep the distinction sharp: content edits go through the spec ( render, a new file); attestations append. Signatures, approvals, and annotations are added by appending an incremental revision that never rewrites the bytes already in the file. The original bytes stay a byte-exact prefix of the result, which is exactly what lets a signature's

/ByteRange

attest to everything written before it.

from emboss import amend_sign, revision_history, format_history

signed = amend_sign(pdf_bytes, cert="legal.pem", key="legal.key",
                    reason="Approved: Legal", name="R. Patel")
signed = amend_sign(signed, cert="finance.pem", key="finance.key",
                    reason="Approved: Finance", name="M. Osei")

print(format_history(signed))
Rev  Kind        Bytes             Signer        Coverage
--------------------------------------------------------------
  0  base        0-6582                          covers by rev 1,2
  1  signature   6582-24003        R. Patel      signed
  2  signature   24003-41560       M. Osei       signed

The headline check is coverage: a revision appended after a signature that no signature's /ByteRange

covers is detected and reported. That is the audit question -- what was added that nobody signed -- and it falls out of the /Prev

chain for free.

emboss amend contract.pdf --sign --cert legal.pem --key legal.key --reason "Approved: Legal"
emboss history contract.pdf
emboss verify contract.pdf --revisions      # exits non-zero on uncovered appended content

amend_pdf

handles non-signature attestations (a placed annotation, an added attachment) the same append-only way. DocMDP is enforced: if the base certifies with /P=1

(no changes) or /P=2

(signatures only), an amendment that exceeds the permitted scope raises rather than producing an illegal file. Amended files are valid but no longer linearized, since the appended revision sits after the original %%EOF

-- inherent to incremental updates, and the price of never rewriting prior bytes.

Determinism, restated for signing.Each revision is byte-identical to what it was when created. Amendments append; they never rewrite. The document remains reproducible from its embedded spec at any revision. This is stronger than a blanket "byte-identical output" claim, because it survives signing.

Two redaction models are available, and they are not equally honest. Construction-time redaction (Document.redact

) is the one to use for anything that actually matters: it matches whole content blocks -- by stable node id, a regex or predicate over the block's plain text, or element type -- and removes or replaces them before layout or rendering, so the real text never reaches a content stream.

Because redaction runs before the document embeds anything, a removed block is absent from every embedded artifact too, not just the page: the emboss-spec.json

, the text index, the layout map, the Markdown twin, the reproducibility manifest, and any table's attached CSV. This is verified in tests/test_redaction_leak.py

, and it is the property that keeps "self-describing" from quietly defeating "redacted". One honest limitation: redaction is block-granular. A value you keep in an un-redacted block stays there, including in a kept table's embedded CSV, so to remove a value from a table you redact the table (or drop attach_data

), not just a paragraph elsewhere.

from emboss import Callout, RedactionRule

rules = [
    RedactionRule(name="ssn", pattern=r"\d{3}-\d{2}-\d{4}"),
    RedactionRule(name="internal-notes", element_type=Callout, mode="remove"),
]
redacted_doc = doc.redact(rules)
pdf_bytes = redacted_doc.render()

redacted_doc.redaction_log   # what was removed, by which rule, before removal -- an audit trail, never auto-attached to output

mode="placeholder"

(the default) replaces a matched block with same-length filler text so the layout doesn't visibly reflow, then covers the filler's own rendered footprint with an opaque box -- the box conceals filler, never the original content. mode="remove"

drops the block outright. Placeholder mode covers the common text-bearing block types (Heading

, Paragraph

, BlockQuote

, Callout

, Footnote

, PullQuote

, BulletList

, NumberedList

, Table

, CodeBlock

); match other element types with mode="remove"

.

The older RedactionMark

/Document.redactions

mechanism draws opaque rectangles directly onto an already-rendered page and is kept for callers masking content that never went through a Document

at all (it is also what the diff/redline change-bars use) -- the underlying text is still in the content stream underneath the box, so it is not a substitute for construction-time redaction of real secret text.

For payloads that need to travel with the PDF but stay opaque to anyone without a password, Document.attach_encrypted(name, data, password)

queues an AES-256-GCM-encrypted /AF

attachment (relationship="EncryptedPayload"

), decrypted later with emboss.decrypt_attachment

.

Constraints are checked before rendering. Repairable issues are fixed automatically; genuine errors are reported:

from emboss import ConstraintValidator

result = ConstraintValidator().validate(doc)
for issue in result.issues:
    print(issue)

Export to multiple formats from a single document spec:

from emboss.adapters.html_export import to_html
from emboss.adapters.markdown_export import to_markdown
from emboss.adapters.docx_export import to_office_dict

html_str = to_html(doc)
md_str = to_markdown(doc)
office_data = to_office_dict(doc)
python
from emboss.adapters.pydantic_schema import DocumentSpec, generate_json_schema

schema = generate_json_schema()

doc = DocumentSpec.model_validate_json(json_string).to_document()
pdf_bytes = doc.render()
Document(
    title="",              # Document title (appears in PDF metadata and title block)
    author="",             # Author name
    subject="",            # Subject line
    keywords="",           # Comma-separated keywords
    language="en-US",      # BCP 47 language tag
    style="corporate",     # Preset name or StyleSheet instance
    brand=None,            # BrandKit layered on top of `style`
    page=PageSpec(),       # Page dimensions and margins
    page_styles={},        # Name -> PageSpec, switched via PageBreak.page_style
    content=[],            # List of block elements
    header=None,           # HeaderFooter for page headers
    footer=None,           # HeaderFooter for page footers
    page_numbers=True,     # Show page numbers
    tagged=True,           # Generate PDF/UA structure tree
    legal=None,            # LegalFeatures (Bates, line numbers, watermark)
    pdfa=False,            # Generate PDF/A-2b (or -3b with embed_spec) output
    toc=False,             # Generate table of contents
    color_mode="rgb",      # "rgb" or "cmyk" (print production)
    signatures=None,       # Digital signature fields
)
doc.heading(text, level=1)
doc.paragraph(content)
doc.bullets(items)
doc.numbered(items)
doc.table(headers, rows)
doc.image(source, width=None, caption=None)
doc.chart(chart_type, labels, values)
doc.diagram(nodes, edges=(), direction="down", caption=None)
doc.code_block(code, language="text")
doc.math(source)
doc.footnote(content)
doc.callout(content, variant="note")
doc.svg(source)
doc.rule()
doc.page_break(page_style=None)
doc.cover(title); doc.abstract(text); doc.authors(authors); doc.pull_quote(text)
doc.stat_tiles(stats); doc.table_of_contents(); doc.appendix(title, *blocks)
doc.index(); doc.glossary(entries)
doc.render(linearize=False, embed_spec=False) -> bytes
doc.save(path, linearize=False, embed_spec=False)
doc.layout_map() -> dict

Document.from_pdf(source, strict=False)   # recover a Document from a rendered PDF
  • Layout is pure Python with Knuth-Plass optimal line breaking
  • Font metrics are cached with LRU caching
  • A typical 10-page document renders in ~50-100ms
  • 200-page documents are supported with ~20-50MB peak memory
  • O(n) linear scaling with document size
git clone https://github.com/GGChamp85/Emboss.git
cd Emboss
python -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"
pytest                          # run all tests
pytest tests/test_emboss.py     # run core tests
pytest -q                       # quiet mode
ruff check src/ tests/          # linting
mypy src/emboss/                # type checking
python examples/financial_report.py
python examples/legal_pleading.py
python examples/showcase.py
php
Document (EmbossSpec)
    |
    v
ConstraintValidator --> validate + auto-fix
    |
    v
LayoutEngine --> measure (font metrics) --> paginate (Knuth-Plass)
    |
    v
Renderer --> ContentStream (PDF operators) + StructureTree (PDF/UA tags)
    |
    v
PDFAssembler --> byte-exact PDF with content-derived /ID
src/emboss/
  spec.py               # Document data model (EmbossSpec)
  writer.py             # Render pipeline: measure -> paginate -> render
  styles.py             # Cascading style system + presets
  constraints.py        # Validation + auto-fix
  layout/
    engine.py           # Layout engine: measurement + pagination
  typography/
    font_metrics.py     # Glyph metrics, kerning, subsetting
    line_breaking.py    # Knuth-Plass line breaker
    hyphenation.py      # Knuth-Liang hyphenation
    ligatures.py        # fi/fl/ffi/ffl substitution
    numbers.py          # Deterministic display number formatting
  pdf/
    assembler.py        # Low-level PDF object writer
    fonts.py            # Font resource building + subsetting
    objects.py          # PDF object types (Dict, Array, Stream)
    streams.py          # Content stream operators (text, shapes)
    tags.py             # PDF/UA structure tree builder
    verify.py           # Structural verification + real veraPDF conformance
    attachments.py      # /AF embedded-file attachments (PDF/A-3)
  adapters/
    html_export.py      # HTML export
    markdown_export.py  # Markdown export
    docx_export.py      # DOCX export
    pydantic_schema.py  # JSON Schema / Pydantic models for LLM
  math_render.py        # LaTeX math parser + renderer, math alphabets
  mathml.py             # Presentation MathML parser
  code_highlight.py     # Syntax highlighting
  charts.py             # Chart rendering
  chart_facts.py        # Chart fact extraction + caption verification
  images.py             # Image handling
  svg.py                # SVG parser + renderer (paths, gradients, clipping)
  diagrams.py           # Node/edge diagram layout + SVG rendering
  crossref.py           # Cross-reference resolution
  numbering.py          # Figure/table auto-numbering
  templates.py          # Document templates
  bibliography.py       # Citation formatting
  colors.py             # Color palettes + theming
  brandkit.py           # Versioned brand object
  bundled_fonts.py      # Bundled OFL font set + registration
  intelligence.py       # Content analysis + smart typography
  toc.py                # Table of contents generation
  pdfa.py               # PDF/A-2b/A-3b conformance
  signing.py            # Digital signatures
  redaction.py          # Content redaction
  slides.py             # SlideDeck + slide/presentation layout
  nodeid.py             # Stable node ids + layout map
  recovery.py           # Spec embedding, from_pdf recovery, strip_pdf
  manifest.py           # Reproducibility manifest + reproduce()
  diff.py               # Node-keyed document diff + redline rendering
  generate.py           # LLM prompt, structured generation, spec parsing
  markdown.py           # Markdown -> EmbossSpec parser
Phase Scope Status
1 Core engine, typography, layout, tagging Done
2 Unicode CIDFont, code highlighting, math, bibliography, charts Done
3 Images, SVG, TOC, multi-column, templates Done
4 PDF/A, redaction, digital signatures Done
5 Cross-references, custom headers/footers, numbered lists Done
6 Micro-typography, GPOS kerning, performance, CMYK Done
7 BrandKit, SlideDeck, diagrams, MathML, real veraPDF conformance, self-describing PDFs (embed_spec /from_pdf /strip ), document diff and redline, reproducibility manifest, construction-time redaction, DocMDP certification signatures, encrypted attachments, node-scoped patching
Done
8 Text-position index and annotation round-trip, incremental amendment with signature coverage, MCP server, Factur-X/ZUGFeRD, table arithmetic validation, PAdES/eIDAS baseline signatures, PDF/X-4, WTPDF 1.0, Mermaid parsing, include-from-source, emboss build , controlled-document block
Done

Apache-2.0. See LICENSE for the full text.

── more in #developer-tools 4 stories · sorted by recency
── more on @emboss 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
Live at https://your-agent.zahid.host
Get free account → Pricing
from €0/mo · no card required
LIVE [news/show-hn-emboss-a-pyt…] indexed:0 read:54min 2026-07-30 ·