Skip to main content

Crate pdfplumber

Crate pdfplumber 

Source
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:

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

FeatureDefaultDescription
stdYesEnables file-path APIs (Pdf::open_path). Disable for WASM.
serdeNoAdds Serialize/Deserialize; curated-model JSON follows a versioned compatibility policy.
parallelNoEnables 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.
CroppedPage
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).
DashPattern
Dash pattern for stroking operations.
DedupeOptions
Options for duplicate character detection and removal.
DocumentMetadata
Document-level metadata extracted from the PDF /Info dictionary.
DrawStyle
Style options for drawing overlays on the SVG page.
Edge
A line segment edge for table detection.
EncodingResolver
Resolved encoding for a font, following PDF encoding resolution order.
ExplicitLines
User-provided line coordinates for Explicit strategy.
ExportedImage
An exported image with deterministic filename, data, and metadata.
ExtGState
Extended Graphics State parameters (from gs operator).
ExtractOptions
Options controlling extraction behavior and resource limits.
ExtractResult
Result wrapper that pairs a value with collected warnings.
ExtractWarning
A non-fatal warning encountered during extraction.
FontEncoding
An encoding table that may be a standard encoding modified by a Differences array.
FormField
A PDF form field extracted from the document’s AcroForm dictionary.
GraphicsState
Graphics state relevant to path painting.
HtmlOptions
Options for HTML rendering.
HtmlRenderer
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.
ImageContent
Extracted image content (raw bytes) from a PDF image XObject.
ImageExportOptions
Options for exporting images with deterministic naming.
ImageMetadata
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.
MetadataEntry
One entry in the raw document information dictionary.
MetadataReference
The object identifier for an unresolved metadata reference.
Page
A single page from a PDF document.
PageRegionOptions
Configuration for page region detection.
PageRegions
Detected regions for a single page.
Pages
A borrowed collection view over the pages in a Pdf.
PagesIter
Iterator over pages of a PDF document, yielding each page on demand.
PaintedPath
A painted path — the result of a painting operator applied to a constructed path.
Path
A complete path consisting of segments.
PathBuilder
Builder for constructing paths from PDF path operators.
Pdf
A PDF document opened for extraction.
PdfError
Fatal error returned by the public Rust facade.
PdfErrorContext
Safe location and operation context attached to a PdfError.
PdfObjectId
A PDF indirect object identifier attached to an error when known.
PdfResourceLimit
Machine-readable details for a configured resource-limit failure.
Point
A 2D point.
RawDocumentMetadata
The complete source-ordered document information dictionary.
Rect
A rectangle extracted from a painted path.
RepairOptions
Options for controlling which PDF repairs to attempt.
RepairResult
Result of a PDF repair operation.
SearchMatch
A single text search match with its bounding box and position information.
SearchOptions
Options controlling text search behavior.
SignatureInfo
Digital signature metadata extracted from a PDF signature field.
StructElement
A node in the PDF structure tree.
SvgDebugOptions
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.
TableFinder
Orchestrator for the table detection pipeline.
TableFinderDebug
Intermediate results from the table detection pipeline.
TableQuality
Quality metrics for a detected table.
TableSettings
Configuration for table detection.
TextBlock
A text block: a group of lines forming a coherent paragraph or section.
TextLine
A text line: a sequence of words on the same y-level.
TextOptions
Options for layout-aware text extraction.
ValidationIssue
A validation issue found in a PDF document.
Word
A word extracted from a PDF page.
WordExtractor
Extracts words from a sequence of characters based on spatial proximity.
WordOptions
Options for word extraction, matching pdfplumber defaults.

Enums§

AnnotationType
Common PDF annotation subtypes.
Color
Color value from a PDF color space.
ColumnMode
Column detection mode for multi-column layout reading order.
EdgeSource
Source of an edge, tracking which geometric primitive it came from.
ExtractWarningCode
Machine-readable warning code for categorizing extraction issues.
FieldType
The type of a PDF form field.
FillRule
Fill rule for path painting.
ImageFilter
PDF stream filter used to encode image data.
ImageFormat
Format of extracted image data.
MetadataValue
A recursively decoded value from the PDF document information dictionary.
Orientation
Orientation of a geometric element.
PageObject
An enum wrapping references to different page object types.
PageObjectKind
A base page-object family in content-stream encounter order.
PathSegment
A segment of a PDF path.
PdfErrorKind
Machine-readable category for a fatal PDF operation error.
Severity
Severity of a validation issue.
ShapeKind
The compatible object family emitted for a painted-path subpath.
StandardEncoding
A named standard PDF encoding.
Strategy
Strategy for table detection.
TextDirection
Text flow direction.
UnicodeNorm
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_cells but with explicit WordOptions so 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 true if the character is a CJK ideograph, syllable, or kana.
is_cjk_text
Returns true if 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_threshold words.
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_threshold words.
words_to_text
Simple (non-layout) text extraction from words.

Type Aliases§

FilteredPage
A page view produced by Page::filter or CroppedPage::filter.
LineOrientation
Type alias preserving backward compatibility.