Skip to main content

Quick navigation

Top-Level Functions

Start here when you need quick file-level tasks: open, merge, and batch rendering.

Open a PDF document

Opens a PDF document and returns a Document instance. Signature: sopdf.open(path, password, *, stream)
str | Path | None
default:"None"
File-system path to the PDF. Mutually exclusive with stream.
str | None
default:"None"
Password for encrypted PDFs. Pass None if no password is required.
bytes | None
default:"None"
Open from raw bytes in memory instead of a file. Mutually exclusive with path.
Returns: Document — The opened document object.

Merge multiple PDF files

Merges multiple PDF files into a single output file, in the order provided. Signature: sopdf.merge(inputs, output)
list[str | Path]
Ordered list of PDF file paths to concatenate.
str | Path
Destination file path for the merged PDF.

Render multiple pages to image bytes

Renders a list of pages to encoded image bytes. Signature: sopdf.render_pages(pages, *, dpi, format, alpha, parallel)
list[Page]
List of page objects to render, typically from doc.pages.
int
default:"72"
Rendering resolution in dots per inch. Common values: 72 (screen preview), 150 (high quality), 300 (print quality).
str
default:"\"png\""
Output image format: "png" or "jpeg".
bool
default:"False"
Whether to include an alpha (transparency) channel. Only effective for PNG.
bool
default:"False"
Whether to use multiprocessing for rendering. Bypasses the GIL for significant speedup on multi-core machines.
Recommended parameter presets Returns: list[bytes] — A list of encoded image bytes, one entry per page, in the same order as pages.

Render multiple pages and write files

Renders pages and writes the results to a directory as page_0.png, page_1.png, etc. Signature: sopdf.render_pages_to_files(pages, output_dir, *, dpi, format, alpha, parallel)
list[Page]
List of page objects to render.
str | Path
Output directory path. Created automatically if it does not exist.
int
default:"72"
Rendering resolution in dots per inch.
str
default:"\"png\""
Output image format: "png" or "jpeg".
bool
default:"False"
Whether to include an alpha channel (PNG only).
bool
default:"False"
Whether to use multiprocessing for rendering.
Recommended parameter presets
Back to top

Document Object Operations

Focus on this section after you have a Document instance and need page management, splitting, merging, or saving. Document represents an open PDF document. It should never be constructed directly — always obtain one via sopdf.open().

Properties

Total page count

Member: doc.page_count or len(doc)
The total number of pages in the document (read-only).
len(doc) is equivalent to doc.page_count.

Metadata

Document metadata — readable and writable via a Metadata proxy object.

Document outline

Document outline (table of contents) as an Outline tree. Returns an object with len == 0 when the document has no bookmarks. Uses pypdfium2 — no pikepdf cost for read-only access.

Encryption status

Whether the document is password-protected (read-only). Returns True even when the correct password has been provided and the document opened successfully.

Page sequence

Lazy sequence of all pages (read-only). Supports iteration and slicing. Commonly used with render_pages().

Page Access

Access page by index

Signature: doc[index] / doc.load_page(index)
Retrieves a page by 0-based index. Negative indices are supported (doc[-1] returns the last page).

Iteration

Split

Split document by pages

Signature: doc.split(pages, output)
Extracts specified pages from the current document and returns a new Document object.
list[int]
List of 0-based page indices to extract. The output order matches the list order.
str | Path | None
default:"None"
If provided, the new document is also written to this path. Otherwise, it is returned in memory only.
Returns: Document — A new document containing the specified pages.

Split into single-page files

Signature: doc.split_each(output_dir)
Saves each page as a separate PDF file. Files are named page_0.pdf, page_1.pdf, etc.
str | Path
Output directory path. Created automatically if it does not exist.

Merge

Append pages from another document

Signature: doc.append(other)
Appends all pages of another document to the end of this document. After calling this method, the document is marked as modified and must be saved via save() or to_bytes() to persist the change.
Document
The document whose pages will be appended.

Save

Save to file

Signature: doc.save(path, *, compress, garbage, linearize)
Writes the document to disk.
str | Path
Destination file path.
bool
default:"True"
Whether to compress content streams. Can significantly reduce file size.
bool
default:"False"
Whether to generate object streams for additional structural compression.
bool
default:"False"
Whether to linearize the PDF for optimized sequential network access (Fast Web View).

Export as bytes

Signature: doc.to_bytes(*, compress)
Serializes the document to bytes without writing to disk. Useful for in-memory processing or serving a PDF over a network.
bool
default:"True"
Whether to compress content streams.
Returns: bytes — The complete PDF file contents as bytes.

Lifecycle

Close document

Signature: doc.close()
Closes the document and releases all file handles and memory resources. Using a with statement is recommended over calling this directly.

Context Manager

Back to top

Page Object Operations

Use this section for single-page workflows such as rendering, text extraction, and text search. Page represents a single page within a document. Obtained via doc[i] or doc.load_page(i) — never constructed directly.

Properties

Page index

Member: page.number
The 0-based index of this page (read-only).

Page dimensions

Member: page.rect
The page dimensions as a Rect in PDF points (1 pt = 1/72 inch) (read-only). Use rect.width and rect.height to get the page size.

Page rotation

Member: page.rotation
The page rotation in degrees. Must be one of 0, 90, 180, 270 (read/write).

Rendering

Render to image bytes

Signature: page.render(*, dpi, format, alpha)
Renders the page to encoded image bytes.
int
default:"72"
Rendering resolution in dots per inch. Use 72 for screen preview, 300 for print quality.
str
default:"\"png\""
Output image format: "png" or "jpeg".
bool
default:"False"
Whether to include an alpha (transparency) channel. Only effective for PNG; JPEG does not support transparency.
Recommended parameter presets Returns: bytes — Encoded image bytes (PNG or JPEG).

Render and save image

Signature: page.render_to_file(path, *, dpi, format, alpha)
Renders the page and writes the image to a file. Parameters are identical to render().
str | Path
Output file path (including extension).
int
default:"72"
Rendering resolution in dots per inch.
str
default:"\"png\""
Output image format: "png" or "jpeg".
bool
default:"False"
Whether to include an alpha channel (PNG only).

Text Extraction

Extract plain text

Signature: page.get_text(*, rect)
Extracts plain text from the page.
Rect | None
default:"None"
Restrict extraction to this rectangular region. Extracts the full page when None.
Returns: str — The extracted plain text.

Extract text blocks

Signature: page.get_text_blocks(*, rect, format)
Extracts structured text blocks with bounding boxes.
Rect | None
default:"None"
Restrict extraction to this rectangular region. Extracts the full page when None.
str
default:"\"list\""
Return format. "list" returns a list of TextBlock objects; "dict" returns a list of plain dictionaries with "text" and "rect" keys.
Returns: format="list"list[TextBlock]; format="dict"list[dict], each of the form {"text": "...", "rect": {"x0": ..., "y0": ..., "x1": ..., "y1": ...}}

Search text positions

Signature: page.search(query, *, match_case)
Searches the page for a text string and returns the bounding rectangles of all matches.
str
The text string to search for.
bool
default:"False"
Whether the search is case-sensitive. Case-insensitive by default.
Returns: list[Rect] — Bounding rectangles for each match. Returns an empty list if no matches are found.

Search text with context blocks

Signature: page.search_text_blocks(query, *, match_case)
Searches for text and returns each match along with the surrounding text block for context.
str
The text string to search for.
bool
default:"False"
Whether the search is case-sensitive.
Returns: list[dict], each element contains:
Back to top

Data Types

Refer to this section when you need to understand response structures (for example Rect, TextBlock, and Metadata) for downstream processing.

Rect

Represents a rectangular region. Coordinates are in PDF points (pt, where 1 pt = 1/72 inch). The coordinate system has its origin at the top-left corner of the page, with x increasing rightward and y increasing downward.
Constructor Parameters Core properties (common) All geometric operations return new Rect instances — the original is immutable.

TextBlock

Represents a single block of text on a page, together with its bounding box.

Metadata

Read/write proxy for the PDF Document Info dictionary. Obtained via doc.metadata — never constructed directly. Read path (zero pikepdf cost): each property calls pypdfium2.get_metadata_dict() after auto-syncing. Write path (lazy pikepdf init): each setter calls _ensure_pike(), writes to pike_doc.docinfo, and marks the document dirty. The next read auto-syncs. Core fields (common) PDF date string format: D:YYYYMMDDHHmmSSOHH'mm' (prefix D: and timezone optional).

OutlineItem

An immutable bookmark node in the document outline.

Outline

Read-only bookmark tree manager. Obtained via doc.outline — never constructed directly. The tree is built once on first access using pypdfium2’s TOC data — no pikepdf initialisation needed.
Back to top

Exceptions

Read this section first when integrating PDF processing into production services and designing robust error handling. All exceptions inherit from PDFError, which inherits from the built-in RuntimeError.
Recommended catch order: catch specific exceptions first (PasswordError / FileDataError / PageError), then PDFError as a final fallback.
Back to top