Expand description
Extract chars, words, lines, rects, and tables from PDF documents with precise coordinates.
pdfplumber is a Rust library for extracting structured content from PDF files. It is a Rust port of Python’s pdfplumber, providing the same coordinate-accurate extraction of characters, words, lines, rectangles, curves, images, and tables.
§Quick Start
use pdfplumber::{Pdf, TextOptions};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let pdf = Pdf::open_path("document.pdf", None)?;
for page in pdf.pages() {
let page = page?;
let text = page.extract_text(&TextOptions::default());
println!("Page {}: {}", page.page_number(), text);
}
Ok(())
}§Architecture
The high-level boundary is simple: ordinary applications should depend only on this crate.
Pdf is the canonical high-level entry point. Its options, errors, and extracted data are
re-exported here. Parser-internal types are intentionally not re-exported. Advanced parser work
can depend on the separate pdfplumber-parse crate explicitly. The
public rustdoc contract
defines the stable facade and the documentation gates applied to it.
Stable facade changes also follow the
Rust deprecation policy.
The
workspace and extraction architecture guide
traces the parser, core algorithms, binding adapters, caches, extension boundaries, and
one complete text request without expanding the stable facade.
Proposals that change the stable facade follow the
Rust API-design review,
which records ownership, allocation, iterator, determinism, error, extension-trait, and
future-compatibility decisions before merge.
The library is split into three crates:
- pdfplumber-core: Backend-independent data types and algorithms
- pdfplumber-parse: PDF parsing (Layer 1) and content stream interpreter (Layer 2)
- pdfplumber (this crate): Public API facade that ties everything together
§Opening inputs
The canonical input family names the source explicitly:
Pdf::open_pathreads a filesystem path (defaultstdfeature).Pdf::open_bytesparses an in-memory byte slice and works in WebAssembly.Pdf::open_readerconsumes any synchronousstd::io::Readsource from its current position through end-of-file; it does not requireSeek.
All three return an owned Pdf. The document does not borrow the path,
byte slice, or reader after the constructor returns. Path and reader failures
have PdfErrorKind::Io; invalid PDF data has PdfErrorKind::Parse.
Password-protected inputs use the matching open_*_with_password methods.
Best-effort repair is currently byte-only via Pdf::open_bytes_with_repair.
§Selecting and iterating pages
Pdf::pages returns a borrowed Pages collection view. Creating the
view does not clone the document or interpret page content. Select one page
directly with pdf.pages().get(0)?, or process owned Page values on
demand with for page in pdf.pages() and propagate each result with ?.
The iterator is double-ended and exact-sized, so selection from either end
does not require eagerly extracting every page.
§Stable data models
models is the curated data-model boundary for ordinary extraction.
Its contract
documents units, coordinate origins, ordering, optional fields, and the
compatibility scope for the 0.4.x line. Root re-exports remain available
for source compatibility. With the optional serde feature, the curated
models follow the separate
Serde JSON compatibility policy.
§Errors and diagnostics
PdfError is opaque and classified by PdfErrorKind. Its default
display and debug output is actionable but excludes source messages and
document content. PdfError::context exposes available zero-based page
and PDF indirect-object context, while std::error::Error::source keeps
the underlying cause available for opt-in protected diagnostics. See the
Rust error guide.
The opaque PdfError has no public variants. Matching the removed
string-payload enum shape does not compile:
use pdfplumber::PdfError;
fn match_removed_variant(error: &PdfError) -> bool {
match error {
PdfError::ParseError(_) => true,
_ => false,
}
}Classify it through PdfError::kind and include a wildcard because
PdfErrorKind is non-exhaustive:
use pdfplumber::{PdfError, PdfErrorKind};
fn is_parse_error(error: &PdfError) -> bool {
match error.kind() {
PdfErrorKind::Parse => true,
_ => false,
}
}§Concurrency
Pdf, Pages, PagesIter, Page, and CroppedPage implement
Send and Sync. Share a document as Arc<Pdf> for concurrent immutable
extraction. The document-wide object and image-byte resource budgets are
shared across all attempts. The optional [Pdf::pages_parallel] API keeps
results in page-index order; Python has a separate Global Interpreter Lock
boundary. See the full
Rust concurrency contract.
§Feature Flags
| Feature | Default | Description |
|---|---|---|
std | Yes | Enables file-path APIs (Pdf::open_path). Disable for WASM. |
serde | No | Adds Serialize/Deserialize; curated-model JSON follows a versioned compatibility policy. |
parallel | No | Enables Pdf::pages_parallel() via rayon. Not WASM-compatible. |
Features are additive and their supported combinations are defined by the Rust feature policy.
§Extracting Text
let pdf = Pdf::open_path("document.pdf", None).unwrap();
let page = pdf.pages().get(0).unwrap();
// Simple text extraction
let text = page.extract_text(&TextOptions::default());
// Layout-preserving text extraction
let text = page.extract_text(&TextOptions { layout: true, ..Default::default() });§Extracting Tables
let pdf = Pdf::open_path("document.pdf", None).unwrap();
let page = pdf.pages().get(0).unwrap();
let tables = page.find_tables(&TableSettings::default());
for table in &tables {
for row in &table.rows {
let cells: Vec<&str> = row.iter()
.map(|c| c.text.as_deref().unwrap_or(""))
.collect();
println!("{:?}", cells);
}
}§WASM Support
This crate compiles for wasm32-unknown-unknown. For WASM builds, disable
the default std feature and use the bytes-based API:
[dependencies]
pdfplumber = { version = "0.3", default-features = false }Then use Pdf::open_bytes with a byte slice:
let pdf = Pdf::open_bytes(pdf_bytes, None)?;
let page = pdf.pages().get(0)?;
let text = page.extract_text(&TextOptions::default());The parallel feature is not available for WASM targets (rayon requires OS threads).
Modules§
- models
- Curated, stable data models for ordinary extraction workflows.
Structs§
- Annotation
- A PDF annotation extracted from a page.
- BBox
- Bounding box in displayed page-space points with a top-left origin.
- Bookmark
- A single entry in the PDF document outline (bookmark / table of contents).
- Cell
- A detected table cell.
- Char
- A single character extracted from a PDF page.
- Cropped
Page - A spatially filtered view of a PDF page.
- Ctm
- Current Transformation Matrix (CTM) — affine transform.
- Curve
- A curve extracted from a painted path (cubic Bezier segment).
- Dash
Pattern - Dash pattern for stroking operations.
- Dedupe
Options - Options for duplicate character detection and removal.
- Document
Metadata - Document-level metadata extracted from the PDF /Info dictionary.
- Draw
Style - Style options for drawing overlays on the SVG page.
- Edge
- A line segment edge for table detection.
- Encoding
Resolver - Resolved encoding for a font, following PDF encoding resolution order.
- Explicit
Lines - User-provided line coordinates for Explicit strategy.
- Exported
Image - An exported image with deterministic filename, data, and metadata.
- ExtG
State - Extended Graphics State parameters (from
gsoperator). - Extract
Options - Options controlling extraction behavior and resource limits.
- Extract
Result - Result wrapper that pairs a value with collected warnings.
- Extract
Warning - A non-fatal warning encountered during extraction.
- Font
Encoding - An encoding table that may be a standard encoding modified by a Differences array.
- Form
Field - A PDF form field extracted from the document’s AcroForm dictionary.
- Graphics
State - Graphics state relevant to path painting.
- Html
Options - Options for HTML rendering.
- Html
Renderer - Renders PDF page content as semantic HTML.
- Hyperlink
- A resolved hyperlink extracted from a PDF page.
- Image
- An image extracted from a PDF page via the Do operator.
- Image
Content - Extracted image content (raw bytes) from a PDF image XObject.
- Image
Export Options - Options for exporting images with deterministic naming.
- Image
Metadata - Metadata about an image XObject from the PDF resource dictionary.
- Intersection
- An intersection point between horizontal and vertical edges.
- Line
- A line segment extracted from a painted path.
- Metadata
Entry - One entry in the raw document information dictionary.
- Metadata
Reference - The object identifier for an unresolved metadata reference.
- Page
- A single page from a PDF document.
- Page
Region Options - Configuration for page region detection.
- Page
Regions - Detected regions for a single page.
- Pages
- A borrowed collection view over the pages in a
Pdf. - Pages
Iter - Iterator over pages of a PDF document, yielding each page on demand.
- Painted
Path - A painted path — the result of a painting operator applied to a constructed path.
- Path
- A complete path consisting of segments.
- Path
Builder - Builder for constructing paths from PDF path operators.
- A PDF document opened for extraction.
- PdfError
- Fatal error returned by the public Rust facade.
- PdfError
Context - Safe location and operation context attached to a
PdfError. - PdfObject
Id - A PDF indirect object identifier attached to an error when known.
- PdfResource
Limit - Machine-readable details for a configured resource-limit failure.
- Point
- A 2D point.
- RawDocument
Metadata - The complete source-ordered document information dictionary.
- Rect
- A rectangle extracted from a painted path.
- Repair
Options - Options for controlling which PDF repairs to attempt.
- Repair
Result - Result of a PDF repair operation.
- Search
Match - A single text search match with its bounding box and position information.
- Search
Options - Options controlling text search behavior.
- Signature
Info - Digital signature metadata extracted from a PDF signature field.
- Struct
Element - A node in the PDF structure tree.
- SvgDebug
Options - Options for the debug_tablefinder SVG output.
- SvgOptions
- Options for SVG generation.
- SvgRenderer
- Renders PDF page content as SVG markup for visual debugging.
- Table
- A detected table.
- Table
Finder - Orchestrator for the table detection pipeline.
- Table
Finder Debug - Intermediate results from the table detection pipeline.
- Table
Quality - Quality metrics for a detected table.
- Table
Settings - Configuration for table detection.
- Text
Block - A text block: a group of lines forming a coherent paragraph or section.
- Text
Line - A text line: a sequence of words on the same y-level.
- Text
Options - Options for layout-aware text extraction.
- Validation
Issue - A validation issue found in a PDF document.
- Word
- A word extracted from a PDF page.
- Word
Extractor - Extracts words from a sequence of characters based on spatial proximity.
- Word
Options - Options for word extraction, matching pdfplumber defaults.
Enums§
- Annotation
Type - Common PDF annotation subtypes.
- Color
- Color value from a PDF color space.
- Column
Mode - Column detection mode for multi-column layout reading order.
- Edge
Source - Source of an edge, tracking which geometric primitive it came from.
- Extract
Warning Code - Machine-readable warning code for categorizing extraction issues.
- Field
Type - The type of a PDF form field.
- Fill
Rule - Fill rule for path painting.
- Image
Filter - PDF stream filter used to encode image data.
- Image
Format - Format of extracted image data.
- Metadata
Value - A recursively decoded value from the PDF document information dictionary.
- Orientation
- Orientation of a geometric element.
- Page
Object - An enum wrapping references to different page object types.
- Page
Object Kind - A base page-object family in content-stream encounter order.
- Path
Segment - A segment of a PDF path.
- PdfError
Kind - Machine-readable category for a fatal PDF operation error.
- Severity
- Severity of a validation issue.
- Shape
Kind - The compatible object family emitted for a painted-path subpath.
- Standard
Encoding - A named standard PDF encoding.
- Strategy
- Strategy for table detection.
- Text
Direction - Text flow direction.
- Unicode
Norm - Unicode normalization form to apply to extracted text.
Constants§
- DEFAULT_
SPLIT_ PUNCTUATION - The punctuation characters pdfplumber splits on when asked to split at
punctuation, i.e. Python’s
string.punctuation.
Functions§
- blocks_
to_ text - Convert text blocks into a string.
- cells_
to_ tables - Group adjacent cells into distinct tables.
- cluster_
lines_ into_ blocks - Cluster text line segments into text blocks based on x-overlap and vertical proximity.
- cluster_
words_ into_ lines - Cluster words into text lines based on y-proximity.
- derive_
edges - Derive all edges from collections of lines, rects, and curves.
- detect_
columns - Detect column boundaries from word x-coordinates.
- edge_
from_ curve - Derive an Edge from a Curve using chord approximation (start to end).
- edge_
from_ line - Derive an Edge from a Line.
- edges_
from_ curve - Derive one edge per straight run of a path.
- edges_
from_ rect - Derive 4 Edges from a Rect (top, bottom, left, right).
- edges_
to_ cells - Construct rectangular cells from intersection points and the edges that connect them.
- edges_
to_ intersections - Find all intersection points between horizontal and vertical edges.
- explicit_
lines_ to_ edges - Convert user-provided explicit line coordinates into edges.
- export_
image_ set - Export a set of images from a page with deterministic filenames.
- extract_
shapes - Extract Line, Rect, and Curve objects from a painted path.
- extract_
shapes_ with_ order - Extract shapes while retaining the emitted subpath-family order.
- extract_
text_ for_ cells - Extract text content for each cell by finding characters within the cell bbox.
- extract_
text_ for_ cells_ with_ options - Like
extract_text_for_cellsbut with explicitWordOptionsso the caller can supply a rotation-adjusted text direction. - image_
from_ ctm - Extract an Image from the CTM active during a Do operator invocation.
- intersections_
to_ cells - Construct rectangular cells from a grid of intersection points.
- is_cjk
- Returns
trueif the character is a CJK ideograph, syllable, or kana. - is_
cjk_ text - Returns
trueif the first character of the text is CJK. - join_
edge_ group - Merge overlapping or adjacent collinear edge segments.
- snap_
edges - Snap nearby parallel edges to aligned positions.
- sort_
blocks_ column_ order - Sort text blocks in column-aware reading order.
- sort_
blocks_ reading_ order - Sort text blocks in natural reading order.
- split_
lines_ at_ columns - Split text lines at large horizontal gaps to detect column boundaries.
- words_
to_ edges_ h - Find imaginary horizontal lines connecting the tops of at least
word_thresholdwords. - words_
to_ edges_ stream - Generate synthetic edges from text alignment patterns for the Stream strategy.
- words_
to_ edges_ v - Find imaginary vertical lines connecting the left, right, or center of at
least
word_thresholdwords. - words_
to_ text - Simple (non-layout) text extraction from words.
Type Aliases§
- Filtered
Page - A page view produced by
Page::filterorCroppedPage::filter. - Line
Orientation - Type alias preserving backward compatibility.