Skip to main content

PyImprint

PyImprint is a Python library for creating and stamping PDF documents with customizable stamps, watermarks, and overlays. Build stamps from text, shapes, images, and QR codes with a fluent builder API, render them to SVG or PNG, or merge them onto existing PDFs.

CI Publish PyPI Python License

Installation

pip install pyimprint

Optional extras pull in the dependencies for PDF stamping, raster rendering and QR codes:

pip install 'pyimprint[pdf]'      # pypdf + reportlab, for PDF stamping and vector PDF export
pip install 'pyimprint[raster]'  # Pillow, for PNG raster export
pip install 'pyimprint[qr]'      # segno, the default QR encoder for StampBuilder.qr()
pip install 'pyimprint[all]'     # all extras

stamp_pdf, render_to_png and render_to_stamp_pdf are always importable; calling one without its extra raises ImportError with the matching install hint. To check up front:

import pyimprint

pyimprint.extras_available()  # e.g. {"pdf": True, "raster": False, "qr": True}

Or with uv:

uv add pyimprint
uv add 'pyimprint[all]'

PyImprint requires Python 3.12 or newer.

Quickstart

Build a stamp, render it to SVG, then stamp it onto an existing PDF:

from pyimprint import StampBuilder, render_to_svg, stamp_pdf

builder = StampBuilder()
stamp = (
    builder.text("DRAFT", x=100, y=50, size=48, fill="#ff0000")
    .border(stroke="#000000", stroke_width=2, padding=10)
    .sizing_mode("fit_stamp")
    .build()
)

# fit_stamp moved the content to (padding, padding) and sized the Group to fit
# the text, the border and its stroke: render exactly that canvas.
# (Core library, no extras needed.)
svg = render_to_svg(stamp, width=stamp.width, height=stamp.height)
with open("stamp.svg", "w") as f:
    f.write(svg)

# Stamp onto an existing PDF (requires the [pdf] extra): the stamp's top-left
# corner goes 96 px (1 inch) right of and below the first page's top-left.
with open("input.pdf", "rb") as f:
    pdf_bytes = f.read()
stamped = stamp_pdf(pdf_bytes, stamp, pages=0, position=(96, 96))
with open("output.pdf", "wb") as f:
    f.write(stamped)

API Reference

StampBuilder

StampBuilder is a fluent builder that composes stamp elements into a Group. Each method appends an element and returns self for chaining. Call build() to get the final Group.

.text(value, *, font="Helvetica", size=12, fill="#000000", stroke=None, stroke_width=1.0, x=0, y=0, bold=False, italic=False, rotate=0, opacity=1.0, ttf_bytes=None, placeholder_key=None, placeholder_max_chars=None)

Append a Text element. (x, y) is the left end of the text baseline. ttf_bytes embeds a TrueType font for PDF rendering (and is used for measuring). placeholder_key/placeholder_max_chars mark the text as a placeholder for fill_placeholders().

.rect(*, x, y, w, h, fill=None, stroke=None, stroke_width=1.0, rx=0, rotate=0, opacity=1.0)

Append a Rect. x, y, w, h are required. rx sets the corner radius.

.line(*, x, y, x2, y2, stroke="#000000", stroke_width=1.0, rotate=0, opacity=1.0)

Append a Line from (x, y) to (x2, y2).

.ellipse(*, x, y, w, h, fill=None, stroke=None, stroke_width=1.0, rotate=0, opacity=1.0)

Append an Ellipse within the bounding box (x, y, w, h).

.image(data, *, format="png", x=0, y=0, w=None, h=None, rotate=0, opacity=1.0)

Append an Image from raw bytes. format is "png", "jpeg", "gif", "webp" or "svg". When w/h are omitted the image's intrinsic pixel size is used (1 image pixel = 1 px), read from the PNG/JPEG/GIF/WebP header without any dependency (pyimprint.image_size); giving only one keeps the aspect ratio. SVG data needs both w and h (ImageSizeError otherwise).

.path(d, *, x=0, y=0, w=0, h=0, fill=None, stroke=None, stroke_width=1.0, rotate=0, opacity=1.0)

Append a Path from an SVG path string d.

.qr(data, *, x=0, y=0, w=100, h=100, version=1, error_correction="M", encoder=None)

Append a QR code Widget that renders data. error_correction is one of "L", "M", "Q", "H".

.add(element)

Append any already-constructed Element (a Text, a Group, a custom widget, ...). build() copies it, so later changes to element do not affect built stamps.

.group(*, x=0, y=0, rotate=0, opacity=1.0, transform=(1, 0, 0, 1, 0, 0)) -> GroupBuilder

Append a nested Group and return a GroupBuilder with the same element methods (text, rect, ..., add, group) that fills it. Children use the group's local coordinates: the group origin is placed at (x, y) and rotated by rotate degrees about it. The group is appended when group() is called, so it keeps its place in the drawing order; the with block is just for readability:

builder = StampBuilder().text("Header", x=10, y=20)
with builder.group(x=40, y=80, rotate=15) as g:
    g.rect(x=0, y=-30, w=160, h=40, stroke="#c00000", stroke_width=2)
    g.text("APPROVED", x=8, y=0, size=24, bold=True, fill="#c00000")
stamp = builder.border().sizing_mode("fit_stamp").build()

.border(*, stroke="#000000", stroke_width=1.0, rx=0, padding=10, fill=None)

Configure an auto-sized border Rect prepended behind the content at build() time. The border wraps the bounds of all content (text uses its real glyph box: baseline − ascent to baseline + descent) plus padding.

.sizing_mode(mode, *, width=None, height=None, padding=10)

Configure canvas sizing. Modes:

Mode Behavior
"fixed" No sizing adjustment (default); the Group keeps width/height 0.
"fit_stamp" Move the content so its bounds start at (padding, padding) (via the Group's transform) and size the Group to the content plus padding on every side, grown if needed so a border and its stroke fit. width/height are ignored.
"fit_content" The canvas is width × height (origin (0, 0)). Each Text, including texts in nested groups, is shrunk independently until its glyph box ends within width − padding / height − padding, taking its x/y into account. Text is never enlarged and never shrunk below 4pt. The Group gets width/height (an omitted one is derived from the content's far edge plus padding).

Text is measured with PyImprint's built-in font metrics (standard-14 fonts including bold/italic, or the ttf_bytes font), so borders and sizing modes need no extras.

.build() -> Group

Return a Group containing deep copies of all appended elements in order (QR encoder objects are shared). The steps run as: content → fit_content → fit_stamp → border, so the border always matches the final content. The builder is reusable: every build() returns an independent tree.

Element Types

All elements share base fields: x, y, width, height, rotate, opacity, fill, stroke, stroke_width.

Type Description Key fields
Group Container for child elements contents: list[Element], transform
Text Text string value, font_family, font_size, bold, italic, ttf_bytes, placeholder_key, placeholder_max_chars
Image Raster or SVG image data: bytes, format: str
Rect Rectangle rx: float (corner radius)
Line Line segment x2, y2
Ellipse Ellipse bounding box via width and height
Path SVG path d: str (SVG path data)
Widget Abstract base for deferred element graphs (e.g. QR codes) draw() -> Group
FontSpec Font specification value object family, size, bold, italic, ttf_bytes

Render Backends

from pyimprint import render_to_svg, render_to_png, render_to_stamp_pdf
Function Output Requires
render_to_svg(stamp, width, height, clip_bounds=None, *, embed_fonts=False) -> str SVG string Core (no extras)
render_to_png(stamp, width, height, dpi=96, clip_bounds=None) -> bytes PNG bytes [raster] (Pillow)
render_to_stamp_pdf(stamp, width_pt=612, height_pt=792, clip_bounds=None) -> bytes One-page PDF bytes [pdf] (reportlab)

All three backends draw the same picture (a pixel-parity test suite enforces it):

  • Units. Stamps are designed in CSS px (96 per inch, top-left origin, y down). width/height of render_to_svg/render_to_png are the canvas in px. render_to_png outputs round(width * dpi / 96) pixels per side and writes dpi to the PNG. render_to_stamp_pdf takes the page size in points and scales the stamp by 0.75, so 96 px print as 1 inch; use pyimprint.render.vector_pdf.px_to_pt(width_px) to size the page to a px canvas.
  • Transforms. Group transform, x/y and rotate apply to their children; every element's rotate (degrees, counter-clockwise) turns it about its own (x, y). Text.y is the baseline; "\n" starts a new line 1.2 × font_size below.
  • Paint. fill/stroke accept hex, rgb()/rgba(), CSS names, none and transparent. A child whose fill/stroke is None inherits it from its group; "none" means no paint. Unset text fill is black, unset shape fill/stroke paints nothing. opacity multiplies with the color's alpha and with every ancestor group's opacity. Strokes are centred; stroke_width=0 means no stroke.
  • Fonts. PDF embeds ttf_bytes, otherwise uses the matching standard-14 font (bold/italic variants included); unknown families fall back to Helvetica with a pyimprint.RenderWarning. PNG uses ttf_bytes or Pillow's scalable default font with synthesised bold/italic. render_to_svg(..., embed_fonts=True) embeds ttf_bytes as @font-face data URLs.
  • Paths render in every backend (full SVG path syntax including arcs). SVG images are supported by the SVG backend only (skipped with a RenderWarning in PNG/PDF).

stamp_pdf()

stamp_pdf(
    input_pdf: bytes | bytearray | memoryview | BinaryIO,
    stamp: Element,
    *,
    pages: int | Sequence[int] | Literal["all"] = 0,
    position: tuple[float, float] | None = (0, 0),
    rotation: float = 0.0,
    scale: float = 1.0,
    anchor: Literal["top-left", "top-right", "bottom-left", "bottom-right", "center"] = "top-left",
    placeholder_values: dict[str, str] | None = None,
    password: str | bytes | None = None,
    keep_encryption: bool = True,
    stamp_page_width: float | None = None,
    stamp_page_height: float | None = None,
    clip_bounds: tuple[float, float, float, float] | None = None,
    over: bool = True,
    incremental: bool = False,
) -> bytes

Overlay stamp onto pages of input_pdf and return the stamped PDF as a new bytes object. The input is never modified; streams are read from their current position (no seek, so pipes work). Requires the [pdf] extra (pypdf + reportlab).

Parameter Default Description
input_pdf required The PDF as bytes/bytearray/memoryview or a binary stream
stamp required The stamp element, usually a Group from StampBuilder.build()
pages 0 0-based index, sequence of indices, or "all". Negative indices count from the end; out-of-range raises PageRangeError (a ValueError naming the page count)
position (0, 0) (dx, dy) in px (96/in) from the page corner chosen by anchor, pointing into the page
anchor "top-left" Which corner of the stamp box sits at position, measured from the same corner of the page ("center": offset from the page centre, x right, y down)
rotation 0.0 Degrees, counter-clockwise as displayed, about the anchor point
scale 1.0 Uniform scale factor (> 0) about the anchor point
placeholder_values None placeholder_key → value, filled before rendering
password None User or owner password of an encrypted PDF (an empty user password is tried automatically)
keep_encryption True Re-encrypt with the input's original encryption (algorithm, permissions, user and owner passwords); False writes it unencrypted
stamp_page_width, stamp_page_height None Stamp box size in points (both or neither), anchored at the stamp's model origin; content outside is clipped
clip_bounds None (x, y, width, height) in px; the stamp is clipped to it
over True True stamps on top of page content; False stamps under
incremental False Append an incremental update instead of rewriting, keeping the original bytes (and signatures over them) intact. Not for encrypted inputs

Placement. Everything is relative to the page's visible box as displayed: the CropBox (clipped to the MediaBox, whatever its origin), with the page's /Rotate applied. So anchor="top-left", position=(96, 48) puts the stamp 1 in from the left and ½ in from the top of what a viewer shows, on portrait, landscape and rotated pages alike. The stamp box that gets placed is, in order of precedence:

  1. stamp_page_width × stamp_page_height (points) from the model origin;
  2. (0, 0, width, height) of a Group with a positive width and height (the canvas produced by sizing_mode("fit_stamp")/"fit_content", or the web designer);
  3. the stamp's content bounds (stamp.get_bounds()), grown by half the widest stroke.

Document data (metadata, outlines, form fields, page labels) is preserved. A filled signature field triggers a UserWarning, because a rewrite invalidates the signature; use incremental=True to append instead. Limitations: AES-encrypted PDFs need pypdf's crypto provider (pip install cryptography); /UserUnit is ignored. page= is accepted as a deprecated alias of pages=.

fill_placeholders()

fill_placeholders(stamp: Element, values: dict[str, str]) -> Element

Return a copy of stamp with placeholder Text elements filled. Any Text whose placeholder_key matches a key in values gets its value replaced. The input tree is never mutated.

from pyimprint import Text, Group, fill_placeholders

stamp = Group(
    contents=[
        Text("CONFIDENTIAL", placeholder_key="status", x=100, y=50, font_size=48, fill="#ff0000"),
    ]
)
filled = fill_placeholders(stamp, {"status": "TOP SECRET"})
# filled.contents[0].value == "TOP SECRET"

When placeholder_max_chars is set on a Text, the replacement value is truncated to that many user-perceived characters: accents, emoji ZWJ sequences, skin-tone modifiers, variation selectors and flags are never split. Widgets such as QrCode are left untouched (they stay widgets), and groups may be nested to any depth.

Serialization

from pyimprint import save_stamp, load_stamp, to_dict, from_dict
from pyimprint import save_pystamp, load_pystamp
Function Signature Description
to_dict (stamp: Element) -> dict Serialize to a JSON-safe dict with format_version and base64-encoded image data
from_dict (data: dict) -> Element Deserialize a dict back to an Element tree
save_stamp (stamp: Element, path: Path) -> None Write a stamp to a JSON file (indent=2, UTF-8)
load_stamp (path: Path) -> Element Load a stamp from a JSON file
save_pystamp (path, stamp, name=None, designer_metadata=None) -> None Write a stamp to a binary .pystamp container
load_pystamp (path) -> (Element, str | None, dict) Load a stamp from a .pystamp container

Stamp files use the .pyimprint.json extension. The format is versioned (currently 1.0) with an upcaster chain for future migrations.

.pystamp binary container

.pystamp is a self-contained binary format that bundles the stamp definition, image assets, and optional designer metadata into a single file. It is designed for sharing stamps with embedded images (no external file references) and is forwards-compatible via a versioned header with room for future extensions.

from pyimprint import StampBuilder, save_pystamp, load_pystamp

stamp = StampBuilder().text("DRAFT", x=10, y=20, size=24, fill="#ff0000").build()

# Export: write a .pystamp file with an optional name
save_pystamp("draft.pystamp", stamp, name="Draft Stamp")

# Import: read it back — returns (stamp, name, designer_metadata)
loaded_stamp, name, designer_meta = load_pystamp("draft.pystamp")
print(name)  # "Draft Stamp"

Binary format

All multi-byte fields are little-endian. The file is a fixed magic + versioned header followed by a ZIP body:

Offset Size Field Description
0 4 magic b"PIMP"
4 2 version uint16, currently 1
6 4 header-length uint32, byte count of the header fields after this one (lets readers skip to the ZIP body without parsing the rest)
10 2 flags uint16, 0 for v1
12 2 name-length uint16, byte count of the UTF-8 name that follows
14 name-length name UTF-8 stamp name (omitted when name=None)
14 + name-length ... body ZIP archive

The header-length field at offset 6 lets future versions extend the header without breaking old readers: a reader can skip header-length bytes from offset 10 to reach the ZIP body regardless of which version-specific fields were added in between.

The ZIP body contains:

Entry Description
stamp.json The stamp definition (same JSON format as save_stamp)
designer.json Optional designer metadata ({} when none was provided)
images/0.png, images/1.jpeg, ... Image assets referenced by Image elements

load_pystamp raises InvalidStampError on a bad magic bytes or truncated header, and UnsupportedFormatError on an unsupported version. Both are subclasses of StampSerializationError.

Web Designer

PyImprint ships a browser-based stamp designer that runs entirely on Pyodide (Python 3.13 compiled to WebAssembly). No server is needed. The designer loads the PyImprint wheel and its dependencies in the browser, so you get the full Python API client-side.

Live at: https://discoveryfox.github.io/pyimprint/

Features:

  • Design stamps visually with form controls for text, fonts, colors, borders, rotation, and positioning
  • Real-time SVG preview that updates as you type
  • Import and share stamps via .pyimprint.json files and URL hash links
  • PDF stamping with click-to-place positioning on the uploaded PDF
  • Image upload (JPEG, PNG, SVG) as stamp elements
  • Rearrangeable layers for multi-element stamps
  • Placeholder controls for template-driven stamp filling
  • Export to JSON, PNG, SVG, and PDF

To run the designer locally, first build and vendor the wheels it installs (the web/wheels/ directory is generated, not committed), then serve web/:

./web/build.sh
python -m http.server 8080 -d web

Then open http://localhost:8080/ in your browser.

CLI

The pyimprint command (also python -m pyimprint) stamps a .pystamp container or stamp JSON file onto PDFs. The format is detected by content, so designer exports work regardless of their extension.

pyimprint stamp --stamp stamp.pystamp --input input.pdf --out output.pdf \
    --pages all --anchor bottom-right --position 48,48 --set name="Ada Lovelace"

# Pipes: '-' reads the PDF from stdin / writes it to stdout
cat input.pdf | pyimprint stamp --stamp stamp.json --input - --out - > output.pdf
Option Default Description
--stamp required .pystamp or stamp JSON file
--input required Input PDF, or - for stdin
--out required Output PDF, or - for stdout
--pages 1 all or 1-based pages/ranges such as 1,3-5
--page Deprecated: one 0-based page index
--position 0,0 x,y offset in px (96/in) from the --anchor corner
--anchor top-left top-left, top-right, bottom-left, bottom-right or center
--scale 1.0 Uniform scale factor (> 0) about the anchor
--rotation 0 Degrees, counter-clockwise, about the anchor
--over / --under --over Stamp over or under the page content
--set KEY=VALUE Fill a placeholder (repeatable)
--password $PYIMPRINT_PASSWORD Password of an encrypted input (prefer the environment variable: command lines are visible to other users)
--no-keep-encryption Write an encrypted input's output unencrypted
--stamp-page-width, --stamp-page-height Stamp box size in points (both or neither)
--incremental Append an incremental update instead of rewriting
-v, --verbose Print tracebacks for errors
--version Print the version

Exit codes: 0 success, 1 usage error, 2 input error (missing or invalid file, wrong password, page out of range), 3 missing optional dependency or internal error.

The CLI requires the [pdf] extra. Install it with pip install 'pyimprint[pdf]'.

Development

This project uses uv for dependency management and packaging. Clone the repository and install the dev dependencies:

git clone https://github.com/DiscoveryFox/pyimprint.git
cd pyimprint
uv sync

Common tasks

Task Command
Run tests uv run pytest
Lint uv run ruff check
Format check uv run ruff format --check
Type check uv run mypy src/pyimprint
Build uv build

Testing

Run the unit test suite:

uv run pytest

The web designer has Playwright-based tests that exercise the live Pyodide UI. Run them with:

uv run --with playwright python -m pytest tests/test_web_designer.py

Tests that need no optional extras carry the core marker; CI also runs them against a no-extras install (a separate environment keeps your dev .venv intact):

UV_PROJECT_ENVIRONMENT=.venv-core uv run --no-dev --with pytest pytest -o addopts='' -m core $(grep -l 'pytest.mark.core' tests/*.py)

Publishing

Releases to PyPI are published automatically by the publish.yml GitHub Actions workflow whenever a tag matching v*.*.* (e.g. v0.2.0) is pushed. The workflow first runs the full CI suite and checks that the tag matches the version in pyproject.toml (the single source of truth; pyimprint.__version__ reads it from the installed package metadata), so bump the version before tagging.

To cut a release:

git tag v0.2.0
git push origin v0.2.0

Publishing prefers OIDC trusted publishing: on PyPI, open the pyimprint project, Publishing, Add a new publisher, with owner DiscoveryFox, repository PyImprint, workflow publish.yml, and environment pypi. Until that is set up, the workflow falls back to the PYPI_API_TOKEN repository secret; delete the secret once trusted publishing works.

License

MIT

Metadata

Release files for pyimprint 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pyimprint 0.3.0
File Size Uploaded Provenance Actions
pyimprint-0.3.0.tar.gz 102.2 kB Without provenance Details for pyimprint-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pyimprint 0.3.0
File Interpreter ABI Platform Actions
pyimprint-0.3.0-py3-none-any.whl Python 3 none any Details for pyimprint-0.3.0-py3-none-any.whl

Total release size: 210.8 kB

Release files / pyimprint-0.3.0.tar.gz

Download URL pyimprint-0.3.0.tar.gz
Size 102.2 kB
Tags Source
SHA-256 checksum
How to use checksums
2c5d51e8f3129a6ec588b5c8baa08601d7707cb4dcb7d774da6d72c978408e1d
BLAKE2b-256 checksum
How to use checksums
3a859dce5ba243becc742e47ad151cfeed3192e28958a03d72ff3f5b6c27b400
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.5 {"installer":{"name":"uv","version":"0.12.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / pyimprint-0.3.0-py3-none-any.whl

Download URL pyimprint-0.3.0-py3-none-any.whl
Size 108.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e8a3f5e4de8564ef2d61bde5d4d2d5bffda7a189a685fb1bcbc71a1200cadb3a
BLAKE2b-256 checksum
How to use checksums
d4c845ad69a84810d47584144e8379f09bf1bc2fc764fbf6b66c4227705a69a2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.5 {"installer":{"name":"uv","version":"0.12.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for pyimprint 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page