API Reference
This section provides detailed documentation for the public classes and methods in Natural PDF.
Core Classes
Section titled “Core Classes”Bases: AggregateTextMixin, ClassificationResultAccessorMixin, PDFOCRMixin, ServiceHostMixin, SelectorHostMixin, ExportMixin, Visualizable
PDF( path_or_url_or_stream, *, font_attrs: Optional[List[str]] = None, keep_spaces: bool = True, text_tolerance: Optional[dict] = None, auto_text_tolerance: bool = True, text_layer: bool = True, context: Optional[PDFContext] = None,)Enhanced PDF wrapper built on top of pdfplumber.
This class provides a fluent interface for working with PDF documents, with improved selection, navigation, and extraction capabilities. It integrates OCR, layout analysis, and AI-powered data extraction features while maintaining compatibility with the underlying pdfplumber API.
The PDF class supports loading from files, URLs, or streams, and provides spatial navigation, element selection with CSS-like selectors, and advanced document processing workflows including multi-page content flows.
Attributes:
- pages (
PageCollection) – Lazy-loaded list of Page objects for document pages. - path – Resolved path to the PDF file or source identifier.
- source_path – Original path, URL, or stream identifier provided during initialization.
- highlighter (
HighlightingService) – Service for rendering highlighted visualizations of document content.
Example:
Basic usage:```pythonimport natural_pdf as npdf
pdf = npdf.PDF("document.pdf")page = pdf.pages[0]text_elements = page.find_all('text:contains("Summary")')Advanced usage with OCR:
pdf = npdf.PDF("scanned_document.pdf")pdf.apply_ocr(engine="rapidocr", resolution=144)tables = pdf.pages[0].find_all('table')Initialize the enhanced PDF object.
**Parameters:**
- **path_or_url_or_stream** – Path to the PDF file (str/Path), a URL (str), or a file-like object (stream). URLs must start with 'http://' or 'https://'.- **font_attrs** (`Optional[List[str]]`) – List of font attributes for grouping characters into words. Common attributes include ['fontname', 'size']. Defaults to None.- **keep_spaces** (`bool`) – If True, include spaces in word elements during text extraction. Defaults to True.- **text_tolerance** (`Optional[dict]`) – PDFplumber-style tolerance settings for text grouping. Dictionary with keys like 'x_tolerance', 'y_tolerance'. Defaults to None.- **auto_text_tolerance** (`bool`) – If True, automatically scale text tolerance based on font size and document characteristics. Defaults to True.- **text_layer** (`bool`) – If True, preserve existing text layer from the PDF. If False, removes all existing text elements during initialization, useful for OCR-only workflows. Defaults to True.
**Raises:**
- (`TypeError`) – If path_or_url_or_stream is not a valid type.- (`IOError`) – If the PDF file cannot be opened or read.- (`ValueError`) – If URL download fails.
**Example:**
```python```python# From file pathpdf = npdf.PDF("document.pdf")
# From URLpdf = npdf.PDF("https://example.com/document.pdf")
# From streamwith open("document.pdf", "rb") as f: pdf = npdf.PDF(f)
# With custom settingspdf = npdf.PDF("document.pdf", text_layer=False, # For OCR-only processing font_attrs=['fontname', 'size', 'flags'])<a id="natural_pdf.PDF.add_exclusion"></a>
#### `add_exclusion`
```pythonadd_exclusion( exclusion_func, label: Optional[str] = None, method: str = 'region',) -> PDFAdd an exclusion function to the PDF.
Exclusion functions define regions of each page that should be ignored during text extraction and analysis operations. This is useful for filtering out headers, footers, watermarks, or other administrative content that shouldn’t be included in the main document processing.
Parameters:
- exclusion_func – A function that takes a Page object and returns a Region to exclude from processing, or None if no exclusion should be applied to that page. The function is called once per page.
- label (
Optional[str]) – Optional descriptive label for this exclusion rule, useful for debugging and identification. - method (
str) – Exclusion method - ‘region’ (default) converts to region, ‘element’ matches individual elements by bbox.
Returns:
- (
PDF) – Self for method chaining.
Raises:
- (
AttributeError) – If PDF pages are not yet initialized.
Example:
```pythonpdf = npdf.PDF("document.pdf")
# Exclude headers (top 50 points of each page)pdf.add_exclusion( lambda page: page.region(0, 0, page.width, 50), label="header_exclusion")
# Exclude any text containing "CONFIDENTIAL"pdf.add_exclusion( lambda page: page.find('text:contains("CONFIDENTIAL")').above(include_source=True) if page.find('text:contains("CONFIDENTIAL")') else None, label="confidential_exclusion")
# Chain multiple exclusionspdf.add_exclusion(header_func).add_exclusion(footer_func)<a id="natural_pdf.PDF.add_region"></a>
#### `add_region`
```pythonadd_region( region_func: Callable[[Page], Optional[Region]], name: Optional[str] = None,) -> PDFAdd a region function to the PDF.
Parameters:
- region_func (
Callable[[Page], Optional[Region]]) – A function that takes a Page and returns a Region, or None - name (
Optional[str]) – Optional name for the region
Returns:
- (
PDF) – Self for method chaining
analyses (attribute)
Section titled “analyses (attribute)”analyses: Dict[str, Any]analyze_layout
Section titled “analyze_layout”analyze_layout(*args, **kwargs) -> ElementCollection[Region]Analyzes the layout of all pages in the PDF.
This is a convenience method that calls analyze_layout on the PDF’s page collection.
Parameters:
- *args – Positional arguments passed to pages.analyze_layout().
- **kwargs – Keyword arguments passed to pages.analyze_layout().
Returns:
- (
ElementCollection[Region]) – An ElementCollection of all detected Region objects.
apply_ocr
Section titled “apply_ocr”apply_ocr( engine: Optional[str] = None, *, options: Optional[Any] = None, languages: Optional[list[str]] = None, min_confidence: Optional[float] = None, device: Optional[str] = None, resolution: Optional[int] = None, detect_only: bool = False, apply_exclusions: bool = True, replace: OCRReplaceMode = 'ocr', use_cache: bool = True, model: Optional[str] = None, client: Optional[Any] = None, prompt: Optional[str] = None, instructions: Optional[str] = None, max_new_tokens: Optional[int] = None, layout: Optional[bool | str] = None, preserve_markup: bool = False, function: Optional[CustomOCRCallable] = None, source_label: str = 'custom-ocr', confidence: Optional[float] = None, pages: Optional[int | Iterable[int] | range | slice] = None, show_progress: bool = True,) -> SelfApply OCR to selected pages and return self.
This method has three validated modes:
- recognition (the default) recognizes text with a registered engine;
detect_only=Truerefreshes persistent text bounding boxes without deleting native or recognized text;function=recognizes text with a callable receiving each physical Region on the selected pages.
Parameters:
- engine (
Optional[str]) – Registered OCR engine name. When omitted, resolve the PDF context default. Supplyingmodelorclientselects VLM OCR when no engine is named. - options (
Optional[Any]) – Typed engine-specific options object or validated mapping. - languages (
Optional[list[str]]) – Ordered language codes such as["en", "fr"]. - min_confidence (
Optional[float]) – Minimum accepted confidence between 0 and 1. - device (
Optional[str]) – Requested compute device, such as"cpu"or"cuda". - resolution (
Optional[int]) – Render resolution in DPI. - detect_only (
bool) – Refresh detection-only spatial artifacts instead of recognizing text. Detection preserves existing text. - apply_exclusions (
bool) – Mask configured exclusions in pixels sent to OCR. - replace (
OCRReplaceMode) – Recognition/function replacement policy:"ocr","all", or"none". Detection has its own refresh policy. - use_cache (
bool) – Allow the persistent OCR result cache when its identity can be proven safe. - model (
Optional[str]) – VLM model name. - client (
Optional[Any]) – OpenAI-compatible VLM client. - prompt (
Optional[str]) – Complete VLM prompt overriding the generated prompt. - instructions (
Optional[str]) – Additional VLM instructions. - max_new_tokens (
Optional[int]) – VLM generation limit. - layout (
Optional[bool | str]) – VLM layout mode (bool or registered detector name). - preserve_markup (
bool) – Preserve raw VLM markup in text metadata. - function (
Optional[CustomOCRCallable]) – Custom callable receiving a physical Region and returning recognized text orNone. It cannot be combined with engine, VLM, cache, exclusion, or detection controls. - source_label (
str) – Provenance label stored asocr_engineon custom-function output. Its selector-visible source remains"ocr"like every other OCR artifact. - confidence (
Optional[float]) – Confidence assigned to custom-function OCR text. - pages (
Optional[int | Iterable[int] | range | slice]) – Page index, iterable of indexes, range, or slice to process. Omit to process every page in PDF order. - show_progress (
bool) – Display a per-page progress bar while executing.
Returns:
- (
Self) – The PDF for fluent chaining.
Raises:
- (
TypeError) – An argument has the wrong type orfunctionis not callable. - (
ValueError) – Mode-specific arguments conflict or a value is invalid.
ask( question: str, *, pages: Optional[Union[int, Iterable[int], range]] = None, min_confidence: float = 0.1, model: Optional[str] = None, client: Optional[Any] = None, using: str = 'text', engine: Optional[str] = None, **kwargs: Any,) -> StructuredDataResultAsk a single question about the document content.
Routes through page-level .ask() which delegates to
.extract() internally, returning :class:StructuredDataResult.
Parameters:
- question (
str) – Question string. - pages (
Optional[Union[int, Iterable[int], range]]) – Specific pages to query (default: all). - min_confidence (
float) – Minimum confidence for extractive QA. - model (
Optional[str]) – Model name for QA / VLM / LLM engine. - client (
Optional[Any]) – OpenAI-compatible client for LLM-backed QA. When provided,.ask()uses the LLM extraction path unlessengine='vlm'. - using (
str) –'text'or'vision'for the client-backed extraction path. - engine (
Optional[str]) –None(auto),'doc_qa', or'vlm'.
Returns:
- (
StructuredDataResult) – class:StructuredDataResultwith ananswerfield.
ask_batch
Section titled “ask_batch”ask_batch( questions: List[str], *, pages: Optional[Union[int, Iterable[int], range]] = None, min_confidence: float = 0.1, model: Optional[str] = None, client: Optional[Any] = None, using: str = 'text', engine: Optional[str] = None, **kwargs: Any,) -> List[StructuredDataResult]Ask multiple questions about the document content.
Resolves pages once and creates a single :class:PageCollection,
then routes each question through it, returning a list of
:class:StructuredDataResult objects.
ask_pages
Section titled “ask_pages”ask_pages( question: QuestionInput, *, pages: Optional[Union[Iterable[int], range, slice]] = None, min_confidence: float = 0.1, model: Optional[str] = None, client: Any = None, using: str = 'text', engine: Optional[str] = None, **kwargs,) -> List[StructuredDataResult]Ask a question across a set of pages and return per-page responses.
Returns a list of :class:StructuredDataResult, one per page.
category (attribute)
Section titled “category (attribute)”category: Optional[str]Top category label for the last classification run.
category_confidence (attribute)
Section titled “category_confidence (attribute)”category_confidence: Optional[float]Confidence score associated with category.
classification_results (attribute)
Section titled “classification_results (attribute)”classification_results: Optional[Dict[str, Any]]Full classification payload converted into a dictionary.
classify
Section titled “classify”classify( labels: List[str], *, model: Optional[str] = None, using: Optional[str] = None, min_confidence: float = 0.0, analysis_key: str = 'classification', multi_label: bool = False, **kwargs: Any,)Delegate classification to the classification service and return the result.
classify_pages
Section titled “classify_pages”classify_pages( labels: List[str], *, model: Optional[str] = None, pages: Optional[Union[Iterable[int], range, slice]] = None, analysis_key: str = 'classification', using: Optional[str] = None, min_confidence: float = 0.0, multi_label: bool = False, batch_size: int = 8, progress_bar: bool = True, **kwargs,) -> PDFClassifies specified pages of the PDF.
Parameters:
- labels (
List[str]) – List of category names - model (
Optional[str]) – Model identifier (‘text’, ‘vision’, or specific HF ID) - pages (
Optional[Union[Iterable[int], range, slice]]) – Page indices, slice, or None for all pages - analysis_key (
str) – Key to store results in page’s analyses dict - using (
Optional[str]) – Processing mode (‘text’ or ‘vision’) - **kwargs – Additional arguments forwarded to the classification engine
Returns:
- (
PDF) – Self for method chaining
clear_exclusions
Section titled “clear_exclusions”clear_exclusions() -> PDFClear all exclusion functions from the PDF.
Removes all previously added exclusion functions that were used to filter out unwanted content (like headers, footers, or administrative text) from text extraction and analysis operations.
Returns:
- (
PDF) – Self for method chaining.
Raises:
- (
AttributeError) – If PDF pages are not yet initialized.
Example:
```pythonpdf = npdf.PDF("document.pdf")pdf.add_exclusion(lambda page: page.find('text:contains("CONFIDENTIAL")').above())
# Later, remove all exclusionspdf.clear_exclusions()<a id="natural_pdf.PDF.clear_ocr_cache"></a>
#### `clear_ocr_cache` *(staticmethod)*
```pythonclear_ocr_cache() -> intClear the OCR result cache. Returns number of entries removed.
close()Close the underlying PDF file and clean up any temporary files.
describe
Section titled “describe”describe(**kwargs)Describe the PDF content using the describe service.
deskew
Section titled “deskew”deskew( pages: Optional[Union[Iterable[int], range, slice]] = None, *, resolution: int = 300, angle: Optional[float] = None, detection_resolution: int = 72, force_overwrite: bool = False, engine: Optional[str] = None, **deskew_kwargs,) -> PDFCreates a new, in-memory PDF object containing deskewed versions of the specified pages from the original PDF.
This method renders each selected page, detects and corrects skew, and then combines the resulting images into a new PDF using ‘img2pdf’. The new PDF object is returned directly.
Important: The returned PDF is image-based. Any existing text, OCR results, annotations, or other elements from the original pages will not be carried over.
Parameters:
- pages (
Optional[Union[Iterable[int], range, slice]]) – Page indices/slice to include (0-based). If None, processes all pages. - resolution (
int) – DPI resolution for rendering the output deskewed pages. - angle (
Optional[float]) – The specific angle (in degrees) to rotate by. If None, detects automatically. - detection_resolution (
int) – DPI resolution used for skew detection if angles are not already cached on the page objects. - force_overwrite (
bool) – If False (default), raises a ValueError if any target page already contains processed elements (text, OCR, regions) to prevent accidental data loss. Set to True to proceed anyway. - engine (
Optional[str]) – Engine name —"projection"(default),"hough", or"standard". - **deskew_kwargs – Additional keyword arguments forwarded to the deskew engine during automatic detection (e.g.,
num_peaksfor Hough).
Returns:
- (
PDF) – A new PDF object representing the deskewed document.
Raises:
- (
ImportError) – If ‘img2pdf’ library is not installed. - (
ValueError) – Ifforce_overwriteis False and target pages contain elements. - (
FileNotFoundError) – If the source PDF cannot be read (if file-based). - (
IOError) – If creating the in-memory PDF fails. - (
RuntimeError) – If rendering or deskewing individual pages fails.
detect_checkboxes
Section titled “detect_checkboxes”detect_checkboxes(*args, **kwargs)detect_layout (attribute)
Section titled “detect_layout (attribute)”detect_layout = analyze_layoutdetect_lines
Section titled “detect_lines”detect_lines(*args, **kwargs)export
Section titled “export”export( path: Union[str, Path], *, resolution: Optional[float] = None, width: Optional[int] = None, layout: Literal['stack', 'grid', 'single'] = 'stack', stack_direction: Literal['vertical', 'horizontal'] = 'vertical', gap: int = 5, columns: Optional[int] = None, crop: Union[bool, Literal['content']] = False, crop_bbox: Optional[Tuple[float, float, float, float]] = None, format: Optional[str] = None, **kwargs,) -> NoneExport a clean image to file.
This is a convenience method that renders and saves in one step.
Parameters:
- path (
Union[str, Path]) – Output file path - resolution (
Optional[float]) – DPI for rendering - width (
Optional[int]) – Target width in pixels - layout (
Literal['stack', 'grid', 'single']) – How to arrange multiple pages/regions - stack_direction (
Literal['vertical', 'horizontal']) – Direction for stack layout - gap (
int) – Pixels between stacked images - columns (
Optional[int]) – Number of columns for grid layout - crop (
Union[bool, Literal['content']]) – Cropping mode (False, True, int for padding, ‘wide’, or Region) - crop_bbox (
Optional[Tuple[float, float, float, float]]) – Explicit crop bounds - format (
Optional[str]) – Image format (inferred from path if not specified) - **kwargs – Additional parameters passed to rendering
export_analyses
Section titled “export_analyses”export_analyses( output_path: Union[str, Path], analysis_keys: Union[str, List[str]], format: str = 'json', include_content: bool = True, include_images: bool = False, image_dir: Optional[Union[str, Path]] = None, image_format: str = 'jpg', image_resolution: int = 72, overwrite: bool = True, **kwargs,) -> strExport analysis results to a file.
Parameters:
- output_path (
Union[str, Path]) – Path to save the export file - analysis_keys (
Union[str, List[str]]) – Key(s) in the analyses dictionary to export - format (
str) – Export format (‘json’, ‘csv’, ‘excel’) - include_content (
bool) – Whether to include extracted text - include_images (
bool) – Whether to export images of elements - image_dir (
Optional[Union[str, Path]]) – Directory to save images (created if doesn’t exist) - image_format (
str) – Format to save images (‘jpg’, ‘png’) - image_resolution (
int) – Resolution for exported images - overwrite (
bool) – Whether to overwrite existing files - **kwargs – Additional format-specific options
Returns:
- (
str) – Path to the exported file
export_ocr_correction_task
Section titled “export_ocr_correction_task”export_ocr_correction_task( output_zip_path: str, *, overwrite: bool = False, suggest=None, resolution: int = 300,)Exports OCR results from this PDF into a correction task package. Exports OCR results from this PDF into a correction task package.
Parameters:
- output_zip_path (
str) – The path to save the output zip file. - overwrite (
bool) – When True, replace any existing archive atoutput_zip_path. - suggest – Optional callable that can provide OCR suggestions per region.
- resolution (
int) – DPI used when rendering page images for the package.
export_training_data
Section titled “export_training_data”export_training_data(output_dir: str, **kwargs) -> dictExport cropped text images and labels for OCR model training.
Creates a HuggingFace ImageFolder-compatible directory with cropped text-element images and metadata (JSONL or CSV).
Parameters:
- output_dir (
str) – Destination directory. - **kwargs – Forwarded to :func:
~natural_pdf.exporters.training_data.export_training_data.
Returns:
- (
dict) – Summary dict withimages,skipped, andoutput_dirkeys.
extract
Section titled “extract”extract( schema: Union[Type[Any], Sequence[str]], client: Any = None, analysis_key: str = 'structured', prompt: Optional[str] = None, using: str = 'text', model: Optional[str] = None, engine: Optional[str] = None, overwrite: bool = True, **kwargs: Any,)Run structured extraction on the entire PDF.
Accepts the same arguments as :meth:Page.extract. Pass
citations=True to get per-field source citations that map
extracted values back to their source elements across pages.
Pass confidence=True for per-field confidence scores, and
instructions="..." for domain-specific LLM guidance.
using='vision' is only supported for single-page PDFs and
requires either client=... or engine='vlm'.
Returns:
- class:
StructuredDataResult
extract_pages
Section titled “extract_pages”extract_pages( schema: Union[Type[BaseModel], Sequence[str]], *, client: Any = None, pages: Optional[Union[Iterable[int], range, slice]] = None, analysis_key: str = 'structured', overwrite: bool = True, **kwargs,) -> PDFRun structured extraction across multiple pages.
extract_tables
Section titled “extract_tables”extract_tables( selector: Optional[str] = None, merge_across_pages: bool = False, method: Optional[str] = None, table_settings: Optional[dict] = None,) -> List[Any]Extract tables from the document or matching elements.
Parameters:
- selector (
Optional[str]) – Optional selector to filter tables (not yet implemented). - merge_across_pages (
bool) – Whether to merge tables that span across pages (not yet implemented). - method (
Optional[str]) – Extraction strategy to prefer. MirrorsPage.extract_tables. - table_settings (
Optional[dict]) – Per-method configuration forwarded toPage.extract_tables.
Returns:
- (
List[Any]) – List of extracted tables
extract_text
Section titled “extract_text”extract_text( *, separator: str | None = None, layout: bool | TextLayoutOptions = False, apply_exclusions: bool = True, newlines: bool | str = True, whitespace: WhitespaceMode = 'preserve', strip: bool = True, bidi: bool = True, content_filter: ContentFilter | None = None,) -> strExtract members independently, then join them at exact host boundaries.
separator=None uses the host’s natural separator. Empty member
handling is host policy. Transforms run on members only: separators are
never normalized, stripped, bidi-processed, or included in a regex match.
extract_text_result
Section titled “extract_text_result”extract_text_result( *, separator: str | None = None, layout: bool | TextLayoutOptions = False, apply_exclusions: bool = True,) -> ExtractedTextJoin raw member results with exact source offsets.
extracted
Section titled “extracted”extracted(analysis_key: Optional[str] = None) -> AnyRetrieve the stored result from a previous .extract() call.
find( selector: Optional[str] = None, *, text: Optional[Union[str, Sequence[str]]] = None, overlap: Optional[str] = None, apply_exclusions: bool = True, regex: bool = False, case: bool = True, text_tolerance: Optional[Dict[str, Any]] = None, auto_text_tolerance: Optional[Union[bool, Dict[str, Any]]] = None, reading_order: bool = True, near_threshold: Optional[float] = None, engine: Optional[str] = None,) -> Optional['Element']Resolve a selector/text query against the host using the selector service.
find_all
Section titled “find_all”find_all( selector: Optional[str] = None, *, text: Optional[Union[str, Sequence[str]]] = None, overlap: Optional[str] = None, apply_exclusions: bool = True, regex: bool = False, case: bool = True, text_tolerance: Optional[Dict[str, Any]] = None, auto_text_tolerance: Optional[Union[bool, Dict[str, Any]]] = None, reading_order: bool = True, near_threshold: Optional[float] = None, engine: Optional[str] = None,) -> 'ElementCollection'Return every element that matches the selector/text query.
from_images (classmethod)
Section titled “from_images (classmethod)”from_images( images: Union[Image.Image, List[Image.Image], str, List[str], Path, List[Path]], resolution: int = 300, apply_ocr: bool = True, ocr_engine: Optional[str] = None, **pdf_options,) -> PDFCreate a PDF from image(s).
Parameters:
- images (
Union[Image.Image, List[Image.Image], str, List[str], Path, List[Path]]) – Single image, list of images, or path(s)/URL(s) to image files - resolution (
int) – DPI for the PDF (default: 300, good for OCR and viewing) - apply_ocr (
bool) – Apply OCR to make searchable (default: True) - ocr_engine (
Optional[str]) – OCR engine to use (default: auto-detect) - **pdf_options – Options passed to PDF constructor
Returns:
- (
PDF) – PDF object containing the images as pages
Example:
```python# Simple scan to searchable PDFpdf = PDF.from_images("scan.jpg")
# From URLpdf = PDF.from_images("https://example.com/image.png")
# Multiple pages (mix of local and URLs)pdf = PDF.from_images(["page1.png", "https://example.com/page2.jpg"])
# Without OCRpdf = PDF.from_images(images, apply_ocr=False)
# With specific enginepdf = PDF.from_images(images, ocr_engine='rapidocr')<a id="natural_pdf.PDF.get_id"></a>
#### `get_id`
```pythonget_id() -> strGet unique identifier for this PDF.
get_rendering_service
Section titled “get_rendering_service”get_rendering_service()Public accessor for the rendering service (primarily for tests).
get_sections
Section titled “get_sections”get_sections( start_elements=None, end_elements=None, new_section_on_page_break=False, include_boundaries='both', orientation='vertical',) -> ElementCollectionExtract sections from the entire PDF based on start/end elements.
This method delegates to the PageCollection.get_sections() method, providing a convenient way to extract document sections across all pages.
Parameters:
- start_elements – Elements or selector string that mark the start of sections (optional)
- end_elements – Elements or selector string that mark the end of sections (optional)
- new_section_on_page_break – Whether to start a new section at page boundaries (default: False)
- include_boundaries – How to include boundary elements: ‘start’, ‘end’, ‘both’, or ‘none’ (default: ‘both’)
- orientation – ‘vertical’ (default) or ‘horizontal’ - determines section direction
Returns:
- (
ElementCollection) – ElementCollection of Region objects representing the extracted sections
Example:
Extract sections between headers:```pythonpdf = npdf.PDF("document.pdf")
# Get sections between headerssections = pdf.get_sections( start_elements='text[size>14]:bold', end_elements='text[size>14]:bold')
# Get sections that break at page boundariessections = pdf.get_sections( start_elements='text:contains("Chapter")', new_section_on_page_break=True)> **Note:**> You can provide only start_elements, only end_elements, or both.> - With only start_elements: sections go from each start to the next start (or end of document)> - With only end_elements: sections go from beginning of document to each end> - With both: sections go from each start to the corresponding end
<a id="natural_pdf.PDF.highlight"></a>
#### `highlight`
```pythonhighlight(*elements, **kwargs)Convenience method for highlighting elements in Jupyter/Colab.
This method creates a highlight context, adds the elements, and returns the resulting image. It’s designed for simple one-liner usage in notebooks.
Parameters:
- *elements – Elements or element collections to highlight
- **kwargs – Additional parameters passed to show()
Returns:
- PIL Image with highlights
Example:
# Simple one-liner highlightingpage.highlight(left, mid, right)
# With custom colorspage.highlight( (tables, 'blue'), (headers, 'red'), (footers, 'green'))highlighter (attribute)
Section titled “highlighter (attribute)”highlighter: HighlightingService = HighlightingService(self)highlights
Section titled “highlights”highlights(show: bool = False) -> HighlightContextCreate a highlight context for accumulating highlights.
This allows for clean syntax to show multiple highlight groups:
Example:
with pdf.highlights() as h: h.add(pdf.find_all('table'), label='tables', color='blue') h.add(pdf.find_all('text:bold'), label='bold text', color='red') h.show()Or With Automatic Display: with pdf.highlights(show=True) as h: h.add(pdf.find_all(‘table’), label=‘tables’) h.add(pdf.find_all(‘text:bold’), label=‘bold’) # Automatically shows when exiting the context
Parameters:
- show (
bool) – If True, automatically show highlights when exiting context
Returns:
- (
HighlightContext) – HighlightContext for accumulating highlights
inspect
Section titled “inspect”inspect(limit: int = 30, **kwargs)Inspect the PDF content using the describe service.
metadata (attribute)
Section titled “metadata (attribute)”metadata: Dict[str, Any]Access PDF metadata as a dictionary.
Returns document metadata such as title, author, creation date, and other properties embedded in the PDF file. The exact keys available depend on what metadata was included when the PDF was created.
Returns:
- (
Dict[str, Any]) – Dictionary containing PDF metadata. Common keys include ‘Title’, - (
Dict[str, Any]) – ‘Author’, ‘Subject’, ‘Creator’, ‘Producer’, ‘CreationDate’, and - (
Dict[str, Any]) – ‘ModDate’. May be empty if no metadata is available.
Example:
```pythonpdf = npdf.PDF("document.pdf")print(pdf.metadata.get('Title', 'No title'))print(f"Created: {pdf.metadata.get('CreationDate')}")<a id="natural_pdf.PDF.pages"></a>
#### `pages` *(attribute)*
```pythonpages: PageCollectionAccess pages as a PageCollection object.
Provides access to individual pages of the PDF document through a collection interface that supports indexing, slicing, and iteration. Pages are lazy-loaded to minimize memory usage.
Returns:
- (
PageCollection) – PageCollection object that provides list-like access to PDF pages.
Raises:
- (
AttributeError) – If PDF pages are not yet initialized.
Example:
```pythonpdf = npdf.PDF("document.pdf")
# Access individual pagesfirst_page = pdf.pages[0]last_page = pdf.pages[-1]
# Slice pagesfirst_three = pdf.pages[0:3]
# Iterate over pagesfor page in pdf.pages: print(f"Page {page.index} has {len(page.chars)} characters")<a id="natural_pdf.PDF.path"></a>
#### `path` *(attribute)*
```pythonpath = self.source_pathrender
Section titled “render”render( *, resolution: Optional[float] = None, width: Optional[int] = None, highlights: Optional[Union[List[Dict[str, Any]], bool]] = None, labels: bool = False, label_format: Optional[str] = None, render_ocr: bool = False, layout: Literal['stack', 'grid', 'single'] = 'stack', stack_direction: Literal['vertical', 'horizontal'] = 'vertical', gap: int = 5, columns: Optional[int] = None, crop: Union[bool, int, str, 'Region', Literal['wide']] = False, crop_bbox: Optional[Tuple[float, float, float, float]] = None, **kwargs,) -> Optional[PILImage]Generate a clean image, with optional explicit highlights.
This method produces publication-ready images without any debugging annotations or persistent highlights.
Parameters:
- resolution (
Optional[float]) – DPI for rendering (default from global settings) - width (
Optional[int]) – Target width in pixels (overrides resolution) - highlights (
Optional[Union[List[Dict[str, Any]], bool]]) – Optional explicit highlight groups/specs to render - labels (
bool) – Whether to render a legend for explicit highlights - label_format (
Optional[str]) – Format string for generated highlight labels - render_ocr (
bool) – Whether to render OCR text overlay on the image - layout (
Literal['stack', 'grid', 'single']) – How to arrange multiple pages/regions - stack_direction (
Literal['vertical', 'horizontal']) – Direction for stack layout - gap (
int) – Pixels between stacked images - columns (
Optional[int]) – Number of columns for grid layout - crop (
Union[bool, int, str, 'Region', Literal['wide']]) – Cropping mode (False, True, int for padding, ‘wide’, or Region) - crop_bbox (
Optional[Tuple[float, float, float, float]]) – Explicit crop bounds - **kwargs – Additional parameters passed to rendering
Returns:
- (
Optional[PILImage]) – PIL Image object or None if nothing to render
save_pdf
Section titled “save_pdf”save_pdf( output_path: Union[str, Path], ocr: bool = False, original: bool = False, apply_exclusions: bool = False, dpi: int = 300,)Saves the PDF object (all its pages) to a new file.
Choose one saving mode:
ocr=True: Creates a new, image-based PDF using OCR results from all pages. Text generated during the natural-pdf session becomes searchable, but original vector content is lost. Requires ‘ocr-export’ extras.original=True: Saves a copy of the original PDF file this object represents. Any OCR results or analyses from the natural-pdf session are NOT included. If the PDF was opened from an in-memory buffer, this mode may not be suitable. Requires ‘ocr-export’ extras.apply_exclusions=True: Saves the original PDF with exclusion zones whited out. Exclusion regions added via add_exclusion() are covered with white rectangles, preserving the rest of the original vector content. Cannot be combined with ocr=True.
Parameters:
- output_path (
Union[str, Path]) – Path to save the new PDF file. - ocr (
bool) – If True, save as a searchable, image-based PDF using OCR data. - original (
bool) – If True, save the original source PDF content. - apply_exclusions (
bool) – If True, save with exclusion zones whited out. - dpi (
int) – Resolution (dots per inch) used only when ocr=True.
Raises:
- (
ValueError) – If the PDF has no pages, or if the mode flags are invalid. - (
ImportError) – If required libraries are not installed for the chosen mode. - (
RuntimeError) – If an unexpected error occurs during saving.
save_searchable
Section titled “save_searchable”save_searchable(output_path: Union[str, Path], dpi: int = 300)DEPRECATED: Use save_pdf(…, ocr=True) instead. Saves the PDF with an OCR text layer, making content searchable.
Requires optional dependencies. Install with: pip install “natural-pdf[export]”
Parameters:
- output_path (
Union[str, Path]) – Path to save the searchable PDF - dpi (
int) – Resolution for rendering and OCR overlay.
search
Section titled “search”search(query: str, *, top_k: int = 5, model: Optional[str] = None) -> PageCollectionSemantic search across pages in this PDF.
Finds the pages most relevant to the query using sentence-transformers embeddings. Embeddings are cached so repeated searches are fast.
Parameters:
- query (
str) – Text to search for. - top_k (
int) – Number of pages to return. - model (
Optional[str]) – Embedding model name (default: all-MiniLM-L6-v2).
Returns:
- (
PageCollection) – PageCollection of the most relevant pages, ordered by relevance. - (
PageCollection) – Each page has a_search_scoreattribute with the similarity score.
selector_flow
Section titled “selector_flow”selector_flow() -> Anyselector_page
Section titled “selector_page”selector_page() -> Anyselector_region
Section titled “selector_region”selector_region() -> Anyservices (attribute)
Section titled “services (attribute)”services: ServiceNamespaceshow( *, resolution: Optional[float] = None, width: Optional[int] = None, color: Optional[Union[str, Tuple[int, int, int]]] = None, labels: bool = True, label_format: Optional[str] = None, highlights: Optional[Union[List[Dict[str, Any]], bool]] = None, legend_position: str = 'right', annotate: Optional[Union[str, List[str]]] = None, render_ocr: bool = False, layout: Optional[Literal['stack', 'grid', 'single']] = None, stack_direction: Literal['vertical', 'horizontal'] = 'vertical', gap: int = 5, columns: Optional[int] = 6, limit: Optional[int] = 30, crop: Union[bool, int, str, 'Region', Literal['wide']] = False, crop_bbox: Optional[Tuple[float, float, float, float]] = None, **kwargs,) -> Optional[PILImage]Generate a preview image with highlights.
This method is for interactive debugging and visualization. Elements are highlighted to show what’s selected or being worked with.
Parameters:
- resolution (
Optional[float]) – DPI for rendering (default from global settings) - width (
Optional[int]) – Target width in pixels (overrides resolution) - color (
Optional[Union[str, Tuple[int, int, int]]]) – Default highlight color - labels (
bool) – Whether to show labels for highlights - label_format (
Optional[str]) – Format string for labels (e.g., “Element {index}”) - highlights (
Optional[Union[List[Dict[str, Any]], bool]]) – Additional highlight groups to show, or False to disable all highlights - legend_position (
str) – Position of legend/colorbar (‘right’, ‘left’, ‘top’, ‘bottom’) - annotate (
Optional[Union[str, List[str]]]) – Attribute name(s) to display on highlights (string or list) - render_ocr (
bool) – Whether to render OCR text overlay on the image - layout (
Optional[Literal['stack', 'grid', 'single']]) – How to arrange multiple pages/regions (defaults to ‘grid’ for multi-page, ‘single’ for single page) - stack_direction (
Literal['vertical', 'horizontal']) – Direction for stack layout - gap (
int) – Pixels between stacked images - columns (
Optional[int]) – Number of columns for grid layout (defaults to 6) - limit (
Optional[int]) – Maximum number of pages to display (default 30, None for all) - crop (
Union[bool, int, str, 'Region', Literal['wide']]) – Cropping mode: - False: No cropping (default) - True: Tight crop to element bounds - int: Padding in PDF points around element (crop bounds are computed in PDF coordinate space, then scaled by resolution) - ‘wide’: Full page width, cropped vertically to element - Region: Crop to the bounds of another region - crop_bbox (
Optional[Tuple[float, float, float, float]]) – Explicit crop bounds - **kwargs – Additional parameters passed to rendering
Returns:
- (
Optional[PILImage]) – PIL Image object or None if nothing to render
source_path (attribute)
Section titled “source_path (attribute)”source_path = '<stream>'split( divider, *, include_boundaries: str = 'start', orientation: str = 'vertical', new_section_on_page_break: bool = False,) -> ElementCollectionDivide the PDF into sections based on the provided divider elements.
Parameters:
- divider – Elements or selector string that mark section boundaries
- include_boundaries (
str) – How to include boundary elements (default: ‘start’). - orientation (
str) – ‘vertical’ or ‘horizontal’ (default: ‘vertical’). - new_section_on_page_break (
bool) – Whether to split at page boundaries (default: False).
Returns:
- (
ElementCollection) – ElementCollection of Region objects representing the sections
Example:
# Split a PDF by chapter titleschapters = pdf.split("text[size>20]:contains('Chapter')")
# Export each chapter to a separate filefor i, chapter in enumerate(chapters): chapter_text = chapter.extract_text() with open(f"chapter_{i+1}.txt", "w") as f: f.write(chapter_text)
# Split by horizontal rules/linessections = pdf.split("line[orientation=horizontal]")
# Split only by page breaks (no divider elements)pages = pdf.split(None, new_section_on_page_break=True)to_llm
Section titled “to_llm”to_llm(**kwargs) -> strReturn an LLM-optimized text representation of this PDF.
to_markdown
Section titled “to_markdown”to_markdown( *, pages: Optional[List[int]] = None, separator: str = '\n\n---\n\n', **kwargs,) -> strConvert PDF pages to Markdown using a VLM.
Falls back to extract_text() per-page when no model is configured.
Parameters:
- pages (
Optional[List[int]]) – Optional list of 0-based page indices. Defaults to all pages. - separator (
str) – String inserted between page results. - **kwargs – Passed to each page’s
to_markdown().
Returns:
- (
str) – Combined Markdown string.
update_ocr
Section titled “update_ocr”update_ocr( transform: Callable[[Any], Optional[str]], *, apply_exclusions: bool = False, pages: Optional[Union[Iterable[int], range, slice]] = None, max_workers: Optional[int] = None, progress_callback: Optional[Callable[[], None]] = None,) -> PDFConvenience wrapper for updating only OCR-derived text elements.
update_text
Section titled “update_text”update_text( transform: Callable[[Any], Optional[str]], *, selector: str = 'text', apply_exclusions: bool = False, pages: Optional[Union[Iterable[int], range, slice]] = None, max_workers: Optional[int] = None, progress_callback: Optional[Callable[[], None]] = None,) -> PDFApplies corrections to text elements using a callback function.
Parameters:
- transform (
Callable[[Any], Optional[str]]) – Function that takes an element and returns corrected text or None - selector (
str) – Selector to apply corrections to (default: “text”) - apply_exclusions (
bool) – Whether to honour exclusion regions while selecting text. - pages (
Optional[Union[Iterable[int], range, slice]]) – Optional page indices/slice to limit the scope of correction - max_workers (
Optional[int]) – Maximum number of threads to use for parallel execution - progress_callback (
Optional[Callable[[], None]]) – Optional callback function for progress updates
Returns:
- (
PDF) – Self for method chaining
PDFCollection
Section titled “PDFCollection”Bases: PDFCollectionOCRMixin, ServiceHostMixin, SelectorHostMixin, ApplyMixin, ExportMixin
PDFCollection( source: Union[str, Iterable[Union[str, PDF]]], recursive: bool = True, **pdf_options: Any,)Initializes a collection of PDF documents from various sources.
Parameters:
- source (
Union[str, Iterable[Union[str, PDF]]]) – The source of PDF documents. Can be: - An iterable (e.g., list) of existing PDF objects. - An iterable (e.g., list) of file paths/URLs/globs (strings). - A single file path/URL/directory/glob string. - recursive (
bool) – If source involves directories or glob patterns, whether to search recursively (default: True). - **pdf_options (
Any) – Keyword arguments passed to the PDF constructor.
apply(self: Any, func: Callable[..., Any], *args: Any, **kwargs: Any) -> Anyapply_ocr
Section titled “apply_ocr”apply_ocr( engine: Optional[str] = None, *, options: Optional[Any] = None, languages: Optional[list[str]] = None, min_confidence: Optional[float] = None, device: Optional[str] = None, resolution: Optional[int] = None, detect_only: bool = False, apply_exclusions: bool = True, replace: OCRReplaceMode = 'ocr', use_cache: bool = True, model: Optional[str] = None, client: Optional[Any] = None, prompt: Optional[str] = None, instructions: Optional[str] = None, max_new_tokens: Optional[int] = None, layout: Optional[bool | str] = None, preserve_markup: bool = False, function: Optional[CustomOCRCallable] = None, source_label: str = 'custom-ocr', confidence: Optional[float] = None, pages: Optional[int | Iterable[int] | range | slice] = None, max_workers: Optional[int] = None, show_progress: bool = True,) -> SelfApply OCR across PDFs and return self.
This method has three validated modes:
- recognition (the default) recognizes text with a registered engine;
detect_only=Truerefreshes persistent text bounding boxes without deleting native or recognized text;function=recognizes text with a callable receiving each physical Region on the selected pages of every PDF.
Parameters:
- engine (
Optional[str]) – Registered OCR engine name. When omitted, resolve each PDF’s context default. Supplyingmodelorclientselects VLM OCR when no engine is named. - options (
Optional[Any]) – Typed engine-specific options object or validated mapping. - languages (
Optional[list[str]]) – Ordered language codes such as["en", "fr"]. - min_confidence (
Optional[float]) – Minimum accepted confidence between 0 and 1. - device (
Optional[str]) – Requested compute device, such as"cpu"or"cuda". - resolution (
Optional[int]) – Render resolution in DPI. - detect_only (
bool) – Refresh detection-only spatial artifacts instead of recognizing text. Detection preserves existing text. - apply_exclusions (
bool) – Mask configured exclusions in pixels sent to OCR. - replace (
OCRReplaceMode) – Recognition/function replacement policy:"ocr","all", or"none". Detection has its own refresh policy. - use_cache (
bool) – Allow the persistent OCR result cache when its identity can be proven safe. - model (
Optional[str]) – VLM model name. - client (
Optional[Any]) – OpenAI-compatible VLM client. - prompt (
Optional[str]) – Complete VLM prompt overriding the generated prompt. - instructions (
Optional[str]) – Additional VLM instructions. - max_new_tokens (
Optional[int]) – VLM generation limit. - layout (
Optional[bool | str]) – VLM layout mode (bool or registered detector name). - preserve_markup (
bool) – Preserve raw VLM markup in text metadata. - function (
Optional[CustomOCRCallable]) – Custom callable receiving a physical Region and returning recognized text orNone. It cannot be combined with engine, VLM, cache, exclusion, or detection controls. - source_label (
str) – Provenance label stored asocr_engineon custom-function output. Its selector-visible source remains"ocr"like every other OCR artifact. - confidence (
Optional[float]) – Confidence assigned to custom-function OCR text. - pages (
Optional[int | Iterable[int] | range | slice]) – Page index, iterable of indexes, range, or slice to process for every PDF. Omit to process every page in PDF order. - max_workers (
Optional[int]) – Maximum PDFs to process concurrently.Noneuses the collection default;1runs serially. - show_progress (
bool) – Display a collection-level progress bar while PDFs complete. Individual PDF progress is suppressed to avoid nested bars.
Returns:
- (
Self) – The PDF collection for fluent chaining.
Raises:
- (
TypeError) – An argument has the wrong type orfunctionis not callable. - (
ValueError) – Mode-specific arguments conflict or a value is invalid.
ask(*args, **kwargs)attr(self: Any, name: str, skip_empty: bool = True) -> List[Any]categorize
Section titled “categorize”categorize(labels: List[str], **kwargs)Categorizes PDFs in the collection based on content or features.
classify_all
Section titled “classify_all”classify_all( labels: List[str], *, using: Optional[str] = None, model: Optional[str] = None, analysis_key: str = 'classification', min_confidence: float = 0.0, multi_label: bool = False, batch_size: int = 8, progress_bar: bool = True, **kwargs,) -> PDFCollectionClassify each PDF document in the collection using provider-backed batch processing.
correct_ocr
Section titled “correct_ocr”correct_ocr( correction_callback: Callable[[Any], Optional[str]], max_workers: Optional[int] = None, progress_callback: Optional[Callable[[], None]] = None,) -> PDFCollectionApply OCR correction to all relevant elements across all pages and PDFs in the collection using a single progress bar.
Parameters:
- correction_callback (
Callable[[Any], Optional[str]]) – Function to apply to each OCR element. It receives the element and should return the corrected text (str) or None. - max_workers (
Optional[int]) – Max threads to use for parallel execution within each page. - progress_callback (
Optional[Callable[[], None]]) – Optional callback function to call after processing each element.
Returns:
- (
PDFCollection) – Self for method chaining.
describe
Section titled “describe”describe(**kwargs)Describe the PDF collection content using the describe service.
detect_checkboxes
Section titled “detect_checkboxes”detect_checkboxes(*args, **kwargs)detect_lines
Section titled “detect_lines”detect_lines(*args, **kwargs)export_analyses
Section titled “export_analyses”export_analyses( output_path: Union[str, Path], analysis_keys: Union[str, List[str]], format: str = 'json', include_content: bool = True, include_images: bool = False, image_dir: Optional[Union[str, Path]] = None, image_format: str = 'jpg', image_resolution: int = 72, overwrite: bool = True, **kwargs,) -> strExport analysis results to a file.
Parameters:
- output_path (
Union[str, Path]) – Path to save the export file - analysis_keys (
Union[str, List[str]]) – Key(s) in the analyses dictionary to export - format (
str) – Export format (‘json’, ‘csv’, ‘excel’) - include_content (
bool) – Whether to include extracted text - include_images (
bool) – Whether to export images of elements - image_dir (
Optional[Union[str, Path]]) – Directory to save images (created if doesn’t exist) - image_format (
str) – Format to save images (‘jpg’, ‘png’) - image_resolution (
int) – Resolution for exported images - overwrite (
bool) – Whether to overwrite existing files - **kwargs – Additional format-specific options
Returns:
- (
str) – Path to the exported file
export_ocr_correction_task
Section titled “export_ocr_correction_task”export_ocr_correction_task(output_zip_path: str, **kwargs)Exports OCR results from all PDFs in this collection into a single correction task package (zip file).
Parameters:
- output_zip_path (
str) – The path to save the output zip file. - **kwargs – Additional arguments passed to create_correction_task_package (e.g., image_render_scale, overwrite).
export_training_data
Section titled “export_training_data”export_training_data(output_dir: str, **kwargs) -> dictExport cropped text images and labels for OCR model training.
Creates a HuggingFace ImageFolder-compatible directory with cropped text-element images and metadata (JSONL or CSV).
Parameters:
- output_dir (
str) – Destination directory. - **kwargs – Forwarded to :func:
~natural_pdf.exporters.training_data.export_training_data.
Returns:
- (
dict) – Summary dict withimages,skipped, andoutput_dirkeys.
extract_each_text
Section titled “extract_each_text”extract_each_text( *, layout: bool | TextLayoutOptions = False, apply_exclusions: bool = True, newlines: bool | str = True, whitespace: WhitespaceMode = 'preserve', strip: bool = True, bidi: bool = True, content_filter: ContentFilter | None = None,) -> List[str]Extract one text string per PDF without imposing a collection join.
A collection of documents has no universally meaningful document-boundary separator. Callers that want a flattened representation must choose and apply that boundary themselves.
filter
Section titled “filter”filter(self: Any, predicate: Callable[[Any], bool]) -> Anyfind( selector: Optional[str] = None, *, text: Optional[Union[str, Sequence[str]]] = None, overlap: Optional[str] = None, apply_exclusions: bool = True, regex: bool = False, case: bool = True, text_tolerance: Optional[Dict[str, Any]] = None, auto_text_tolerance: Optional[Union[bool, Dict[str, Any]]] = None, reading_order: bool = True, near_threshold: Optional[float] = None, engine: Optional[str] = None,) -> Optional['Element']Resolve a selector/text query against the host using the selector service.
find_all
Section titled “find_all”find_all( selector: Optional[str] = None, *, text: Optional[Union[str, Sequence[str]]] = None, overlap: Optional[str] = None, apply_exclusions: bool = True, regex: bool = False, case: bool = True, text_tolerance: Optional[Dict[str, Any]] = None, auto_text_tolerance: Optional[Union[bool, Dict[str, Any]]] = None, reading_order: bool = True, near_threshold: Optional[float] = None, engine: Optional[str] = None,) -> 'ElementCollection'Return every element that matches the selector/text query.
from_directory (classmethod)
Section titled “from_directory (classmethod)”from_directory( directory_path: str, recursive: bool = True, **pdf_options: Any,) -> PDFCollectionCreates a PDFCollection explicitly from PDF files within a directory.
from_glob (classmethod)
Section titled “from_glob (classmethod)”from_glob(pattern: str, recursive: bool = True, **pdf_options: Any) -> PDFCollectionCreates a PDFCollection explicitly from a single glob pattern.
from_globs (classmethod)
Section titled “from_globs (classmethod)”from_globs( patterns: List[str], recursive: bool = True, **pdf_options: Any,) -> PDFCollectionCreates a PDFCollection explicitly from a list of glob patterns.
from_paths (classmethod)
Section titled “from_paths (classmethod)”from_paths(paths_or_urls: List[str], **pdf_options: Any) -> PDFCollectionCreates a PDFCollection explicitly from a list of file paths or URLs.
inspect
Section titled “inspect”inspect(limit: int = 30, **kwargs)Inspect the PDF collection content using the describe service.
map( self: Any, func: Callable[..., Any], *args: Any, skip_empty: bool = False, **kwargs: Any,) -> Anypdfs (attribute)
Section titled “pdfs (attribute)”pdfs: List[PDF]Returns the list of PDF objects held by the collection.
search
Section titled “search”search(query: str, *, top_k: int = 5, model: Optional[str] = None) -> PageCollectionSemantic search across pages in all PDFs in this collection.
Finds the pages most relevant to the query using sentence-transformers embeddings. Pages from all PDFs are ranked together.
Parameters:
- query (
str) – Text to search for. - top_k (
int) – Number of pages to return. - model (
Optional[str]) – Embedding model name (default: all-MiniLM-L6-v2).
Returns:
- (
PageCollection) – PageCollection of the most relevant pages, ordered by relevance. - (
PageCollection) – Each page has a_search_scoreattribute with the similarity score.
selector_flow
Section titled “selector_flow”selector_flow() -> Anyselector_page
Section titled “selector_page”selector_page() -> Anyselector_region
Section titled “selector_region”selector_region() -> Anyservices (attribute)
Section titled “services (attribute)”services: ServiceNamespaceshow(limit: Optional[int] = 30, per_pdf_limit: Optional[int] = 10, **kwargs)Display all PDFs in the collection with labels.
Each PDF is shown with its pages in a grid layout (6 columns by default), and all PDFs are stacked vertically with labels.
Parameters:
- limit (
Optional[int]) – Maximum total pages to show across all PDFs (default: 30) - per_pdf_limit (
Optional[int]) – Maximum pages to show per PDF (default: 10) - **kwargs – Additional arguments passed to each PDF’s show() method (e.g., columns, exclusions, resolution, etc.)
Returns:
- Displayed image in Jupyter or None
unique
Section titled “unique”unique(self: Any, key: Optional[Callable[[Any], Any]] = None) -> AnyBases: ClassificationResultAccessorMixin, OCRDirectTargetMixin, SpatialTextMixin, ServiceHostMixin, SelectorHostMixin, SinglePageContextMixin, SupportsSections, Visualizable
Page( page: PdfPlumberPage, parent: PDF, index: int, font_attrs=None, load_text: bool = True, context: Optional[PDFContext] = None,)Enhanced Page wrapper built on top of pdfplumber.Page.
This class provides a fluent interface for working with PDF pages, with improved selection, navigation, extraction, and question-answering capabilities. It integrates multiple analysis capabilities through mixins and provides spatial navigation with CSS-like selectors.
The Page class serves as the primary interface for document analysis, offering:
- Element selection and spatial navigation
- OCR and layout analysis integration
- Table detection and extraction
- AI-powered classification and data extraction
- Visual debugging with highlighting and cropping
- Text style analysis and structure detection
Attributes:
- index (
int) – Zero-based index of this page in the PDF. - number (
int) – One-based page number (index + 1). - width (
float) – Page width in points. - height (
float) – Page height in points. - bbox (
float) – Bounding box tuple (x0, top, x1, bottom) of the page. - chars (
List[Any]) – Collection of character elements on the page. - words (
List[Any]) – Collection of word elements on the page. - lines (
List[Any]) – Collection of line elements on the page. - rects (
List[Any]) – Collection of rectangle elements on the page. - images (
List[Any]) – Collection of image elements on the page. - metadata (
Dict[str, Any]) – Dictionary for storing analysis results and custom data.
Example:
Basic usage:```pythonpdf = npdf.PDF("document.pdf")page = pdf.pages[0]
# Find elements with CSS-like selectorsheaders = page.find_all('text[size>12]:bold')summaries = page.find('text:contains("Summary")')
# Spatial navigationcontent_below = summaries.below(until='text[size>12]:bold')
# Table extractiontables = page.extract_table()Advanced usage:
# Apply OCR if neededpage.apply_ocr(engine='rapidocr', resolution=300)
# Layout analysispage.analyze_layout(engine='yolo')
# AI-powered extractiondata = page.extract_structured_data(MySchema)
# Visual debuggingpage.find('text:contains("Important")').show()Initialize a page wrapper.
Creates an enhanced Page object that wraps a pdfplumber page with additionalfunctionality for spatial navigation, analysis, and AI-powered extraction.
**Parameters:**
- **page** (`PdfPlumberPage`) – The underlying pdfplumber page object that provides raw PDF data.- **parent** (`PDF`) – Parent PDF object that contains this page and provides access to managers and global settings.- **index** (`int`) – Zero-based index of this page in the PDF document.- **font_attrs** – List of font attributes to consider when grouping characters into words. Common attributes include ['fontname', 'size', 'flags']. If None, uses default character-to-word grouping rules.- **load_text** (`bool`) – If True, load and process text elements from the PDF's text layer. If False, skip text layer processing (useful for OCR-only workflows).
> **Note:**> This constructor is typically called automatically when accessing pages> through the PDF.pages collection. Direct instantiation is rarely needed.
**Example:**
```python```python# Pages are usually accessed through the PDF objectpdf = npdf.PDF("document.pdf")page = pdf.pages[0] # Page object created automatically
# Direct construction (advanced usage)import pdfplumberwith pdfplumber.open("document.pdf") as plumber_pdf: plumber_page = plumber_pdf.pages[0] page = Page(plumber_page, pdf, 0, load_text=True)<a id="natural_pdf.Page.add_element"></a>
#### `add_element`
```pythonadd_element(element: Any, element_type: str = 'words') -> boolAdd an element to the backing collection.
add_exclusion
Section titled “add_exclusion”add_exclusion(exclusion: Any, label: Optional[str] = None, method: str = 'region')Register an exclusion on the host via the exclusion service.
add_highlight
Section titled “add_highlight”add_highlight( bbox: Optional[Tuple[float, float, float, float]] = None, color: Optional[Union[Tuple, str]] = None, label: Optional[str] = None, use_color_cycling: bool = False, element: Optional[Any] = None, annotate: Optional[List[str]] = None, existing: str = 'append',) -> PageAdd a highlight to a bounding box or the entire page. Delegates to the central HighlightingService.
Parameters:
- bbox (
Optional[Tuple[float, float, float, float]]) – Bounding box (x0, top, x1, bottom). If None, highlight entire page. - color (
Optional[Union[Tuple, str]]) – RGBA color tuple/string for the highlight. - label (
Optional[str]) – Optional label for the highlight. - use_color_cycling (
bool) – If True and no label/color, use next cycle color. - element (
Optional[Any]) – Optional original element being highlighted (for attribute extraction). - annotate (
Optional[List[str]]) – List of attribute names from ‘element’ to display. - existing (
str) – How to handle existing highlights (‘append’ or ‘replace’).
Returns:
- (
Page) – Self for method chaining.
add_highlight_polygon
Section titled “add_highlight_polygon”add_highlight_polygon( polygon: List[Tuple[float, float]], color: Optional[Union[Tuple, str]] = None, label: Optional[str] = None, use_color_cycling: bool = False, element: Optional[Any] = None, annotate: Optional[List[str]] = None, existing: str = 'append',) -> PageHighlight a polygon shape on the page. Delegates to the central HighlightingService.
Parameters:
- polygon (
List[Tuple[float, float]]) – List of (x, y) points defining the polygon. - color (
Optional[Union[Tuple, str]]) – RGBA color tuple/string for the highlight. - label (
Optional[str]) – Optional label for the highlight. - use_color_cycling (
bool) – If True and no label/color, use next cycle color. - element (
Optional[Any]) – Optional original element being highlighted (for attribute extraction). - annotate (
Optional[List[str]]) – List of attribute names from ‘element’ to display. - existing (
str) – How to handle existing highlights (‘append’ or ‘replace’).
Returns:
- (
Page) – Self for method chaining.
add_region
Section titled “add_region”add_region( region: Region, name: Optional[str] = None, *, source: Optional[str] = None,) -> PageAdd a region to the page.
Parameters:
- region (
Region) – Region object to add - name (
Optional[str]) – Optional name for the region - source (
Optional[str]) – Optional provenance label; if provided it will be recorded on the region.
Returns:
- (
Page) – Self for method chaining
add_regions
Section titled “add_regions”add_regions( regions: List[Region], prefix: Optional[str] = None, *, source: Optional[str] = None,) -> PageAdd multiple regions to the page.
Parameters:
- regions (
List[Region]) – List of Region objects to add - prefix (
Optional[str]) – Optional prefix for automatic naming (regions will be named prefix_1, prefix_2, etc.) - source (
Optional[str]) – Optional provenance label applied to each region.
Returns:
- (
Page) – Self for method chaining
analyses (attribute)
Section titled “analyses (attribute)”analyses: Dict[str, Any]analyze_layout
Section titled “analyze_layout”analyze_layout( engine: Optional[str] = None, *, options: Optional[Any] = None, confidence: Optional[float] = None, classes: Optional[List[str]] = None, exclude_classes: Optional[List[str]] = None, device: Optional[str] = None, existing: str = 'replace', model_name: Optional[str] = None, client: Optional[Any] = None, show_progress: Optional[bool] = None,) -> AnyDelegate layout analysis to the configured layout service.
analyze_text_styles
Section titled “analyze_text_styles”analyze_text_styles(options: Optional[TextStyleOptions] = None) -> ElementCollectionAnalyze text elements by style, adding attributes directly to elements.
This method uses TextStyleAnalyzer to process text elements (typically words) on the page. It adds the following attributes to each processed element:
- style_label: A descriptive or numeric label for the style group.
- style_key: A hashable tuple representing the style properties used for grouping.
- style_properties: A dictionary containing the extracted style properties.
Parameters:
- options (
Optional[TextStyleOptions]) – Optional TextStyleOptions to configure the analysis. If None, the analyzer’s default options are used.
Returns:
- (
ElementCollection) – ElementCollection containing all processed text elements with added style attributes.
apply_custom_ocr
Section titled “apply_custom_ocr”apply_custom_ocr( *, ocr_function, source_label: str = 'custom-ocr', replace: OCRReplaceMode = 'ocr', confidence: Optional[float] = None, add_to_page: bool = True,) -> PageApply a custom OCR function via the shared OCR service.
apply_ocr
Section titled “apply_ocr”apply_ocr( engine: Optional[str] = None, *, options: Optional[Any] = None, languages: Optional[list[str]] = None, min_confidence: Optional[float] = None, device: Optional[str] = None, resolution: Optional[int] = None, detect_only: bool = False, apply_exclusions: bool = True, replace: OCRReplaceMode = 'ocr', use_cache: bool = True, model: Optional[str] = None, client: Optional[Any] = None, prompt: Optional[str] = None, instructions: Optional[str] = None, max_new_tokens: Optional[int] = None, layout: Optional[bool | str] = None, preserve_markup: bool = False, function: Optional[CustomOCRCallable] = None, source_label: str = 'custom-ocr', confidence: Optional[float] = None,) -> SelfApply OCR within this object’s spatial scope and return self.
This method has three validated modes:
- recognition (the default) recognizes text with a registered engine;
detect_only=Truerefreshes persistent text bounding boxes without deleting native or recognized text;function=recognizes text with a callable receiving each physical Region in the scope.
Parameters:
- engine (
Optional[str]) – Registered OCR engine name. When omitted, resolve the context default. Supplyingmodelorclientselects VLM OCR when no engine is named. - options (
Optional[Any]) – Typed engine-specific options object or validated mapping. - languages (
Optional[list[str]]) – Ordered language codes such as["en", "fr"]. - min_confidence (
Optional[float]) – Minimum accepted confidence between 0 and 1. - device (
Optional[str]) – Requested compute device, such as"cpu"or"cuda". - resolution (
Optional[int]) – Render resolution in DPI. - detect_only (
bool) – Refresh detection-only spatial artifacts instead of recognizing text. Detection preserves existing text. - apply_exclusions (
bool) – Mask configured exclusions in pixels sent to OCR. - replace (
OCRReplaceMode) – Recognition/function replacement policy:"ocr","all", or"none". Detection has its own refresh policy. - use_cache (
bool) – Allow the persistent OCR result cache when its identity can be proven safe. - model (
Optional[str]) – VLM model name. - client (
Optional[Any]) – OpenAI-compatible VLM client. - prompt (
Optional[str]) – Complete VLM prompt overriding the generated prompt. - instructions (
Optional[str]) – Additional VLM instructions. - max_new_tokens (
Optional[int]) – VLM generation limit. - layout (
Optional[bool | str]) – VLM layout mode (bool or registered detector name). - preserve_markup (
bool) – Preserve raw VLM markup in text metadata. - function (
Optional[CustomOCRCallable]) – Custom callable receiving a physical Region and returning recognized text orNone. It cannot be combined with engine, VLM, cache, exclusion, or detection controls. - source_label (
str) – Provenance label stored asocr_engineon custom-function output. Its selector-visible source remains"ocr"like every other OCR artifact. - confidence (
Optional[float]) – Confidence assigned to custom-function OCR text.
Returns:
- (
Self) – The receiving object for fluent chaining.
Raises:
- (
TypeError) – An argument has the wrong type orfunctionis not callable. - (
ValueError) – Mode-specific arguments conflict or a value is invalid.
ask( question: Any, min_confidence: float = 0.1, model: Optional[str] = None, debug: bool = False, *, client: Any = None, using: str = 'text', engine: Optional[str] = None, **kwargs: Any,) -> StructuredDataResultAsk a question about the page content.
Parameters:
- question (
Any) – Question string or list of question strings. - min_confidence (
float) – Minimum confidence for extractive QA. - model (
Optional[str]) – Model name for the QA / VLM engine. - debug (
bool) – Enable debug output. - client (
Any) – OpenAI-compatible client for LLM-backed QA. When provided,.ask()uses the LLM extraction path unlessengine='vlm'. - using (
str) – Content mode —'text'or'vision'for the client-backed extraction path. Ignored for default doc-QA. - engine (
Optional[str]) – Extraction engine —None(auto),'doc_qa', or'vlm'.
Returns:
- (
StructuredDataResult) – class:StructuredDataResultwith ananswerfield.
category (attribute)
Section titled “category (attribute)”category: Optional[str]Top category label for the last classification run.
category_confidence (attribute)
Section titled “category_confidence (attribute)”category_confidence: Optional[float]Confidence score associated with category.
chars (attribute)
Section titled “chars (attribute)”chars: List[Any]Get all character elements on this page.
classification_results (attribute)
Section titled “classification_results (attribute)”classification_results: Optional[Dict[str, Any]]Full classification payload converted into a dictionary.
classify
Section titled “classify”classify( labels: List[str], *, model: Optional[str] = None, using: Optional[str] = None, min_confidence: float = 0.0, analysis_key: str = 'classification', multi_label: bool = False, **kwargs: Any,)Delegate classification to the classification service and return the result.
clear_detected_layout_regions
Section titled “clear_detected_layout_regions”clear_detected_layout_regions() -> PageRemoves all regions from this page that were added by layout analysis
(i.e., regions where source attribute is ‘detected’).
The ElementManager repository is authoritative; the compatibility
page._regions view reflects the removal automatically.
Returns:
- (
Page) – Self for method chaining.
clear_exclusions
Section titled “clear_exclusions”clear_exclusions() -> PageClear all exclusions from the page.
clear_highlights
Section titled “clear_highlights”clear_highlights() -> PageClear all highlights from this specific page via HighlightingService.
Returns:
- (
Page) – Self for method chaining
clear_text_layer
Section titled “clear_text_layer”clear_text_layer(*args, **kwargs) -> Tuple[int, int]Clear the underlying word/char layers for this page.
compare_ocr
Section titled “compare_ocr”compare_ocr( engines: List, *, normalize: str = 'collapse', strategy: str = 'auto', resolution: int = 150, languages: Optional[List[str]] = None, min_confidence: Optional[float] = None, device: Optional[str] = None, engine_options: Optional[Dict[str, Any]] = None, apply_exclusions: bool = True, **kwargs,)Compare multiple OCR engines on this page.
Runs each engine and produces a comparison without modifying
the page’s element store. Use .apply(engine=...) on the
result to persist the chosen engine’s output.
Parameters:
- engines (
List) – Engine specs to compare. Each can be a string (e.g."rapidocr") or a dict with"engine"key plus overrides (e.g.{"engine": "rapidocr", "resolution": 72}). - normalize (
str) – Text normalization —"collapse"(default),"strict", or"ignore"(strip spaces). - strategy (
str) – Alignment —"auto"(default),"rows","tiles". - resolution (
int) – Render DPI (default 150). - languages (
Optional[List[str]]) – Language codes for OCR. - min_confidence (
Optional[float]) – Minimum confidence filter. - device (
Optional[str]) –"cpu","cuda", or"mps". - engine_options (
Optional[Dict[str, Any]]) – Per-engine overrides (deprecated — use dict specs). - apply_exclusions (
bool) – Mask configured exclusion zones for every run.
Returns:
- class:
~natural_pdf.ocr.comparison.OcrComparisonwith .summary(),.show(),.heatmap(),.diff(),- and
.apply(engine=...).
create_region
Section titled “create_region”create_region(x0: float, top: float, x1: float, bottom: float) -> AnyCreate a region on this page with the specified coordinates.
Parameters:
- x0 (
float) – Left x-coordinate - top (
float) – Top y-coordinate - x1 (
float) – Right x-coordinate - bottom (
float) – Bottom y-coordinate
Returns:
- (
Any) – Region object for the specified coordinates
create_text_elements_from_ocr
Section titled “create_text_elements_from_ocr”create_text_elements_from_ocr(*args, **kwargs)Proxy for ElementManager.create_text_elements_from_ocr.
crop(bbox: Optional[Bounds] = None, **kwargs: Any) -> AnyCrop the page to the specified bounding box.
This is a direct wrapper around pdfplumber’s crop method.
Parameters:
- bbox (
Optional[Bounds]) – Bounding box (x0, top, x1, bottom) or None - **kwargs (
Any) – Additional parameters (top, bottom, left, right)
Returns:
- (
Any) – Cropped page object (pdfplumber.Page)
describe
Section titled “describe”describe(**kwargs)Describe the page content using the describe service.
deskew
Section titled “deskew”deskew( *, resolution: int = 300, angle: Optional[float] = None, detection_resolution: int = 72, engine: Optional[str] = None, **deskew_kwargs,) -> Optional[Image.Image]Creates and returns a deskewed PIL image of the page.
If angle is not provided, it will first try to detect the skew angle
using detect_skew_angle (or use the cached angle if available).
Parameters:
- resolution (
int) – DPI resolution for the output deskewed image. - angle (
Optional[float]) – The specific angle (in degrees) to rotate by. If None, detects automatically. - detection_resolution (
int) – DPI resolution used for detection ifangleis None. - engine (
Optional[str]) – Engine name —"projection"(default),"hough", or"standard". - **deskew_kwargs – Additional keyword arguments passed to the detection engine if automatic detection is performed.
Returns:
- (
Optional[Image.Image]) – A deskewed PIL.Image.Image object.
Raises:
- (
Exception) – Any errors raised by the configured deskew provider.
detect_checkboxes
Section titled “detect_checkboxes”detect_checkboxes(*args, **kwargs)detect_form_cells
Section titled “detect_form_cells”detect_form_cells(*args, **kwargs)detect_layout (attribute)
Section titled “detect_layout (attribute)”detect_layout = analyze_layoutdetect_lines
Section titled “detect_lines”detect_lines(*args, **kwargs)detect_skew_angle
Section titled “detect_skew_angle”detect_skew_angle( *, resolution: int = 72, grayscale: bool = True, force_recalculate: bool = False, engine: Optional[str] = None, **deskew_kwargs,) -> Optional[float]Detect the skew angle of this page using the deskew provider.
Parameters:
- resolution (
int) – DPI resolution for rendering before detection. - grayscale (
bool) – Whether to convert to grayscale before detection. - force_recalculate (
bool) – Re-detect even if a cached angle exists. - engine (
Optional[str]) – Engine name —"projection"(default),"hough", or"standard". - **deskew_kwargs – Extra arguments forwarded to the detection engine. Unknown keys are rejected with a ValueError.
Returns:
- (
Optional[float]) – The correction angle in degrees,0.0when content is present - (
Optional[float]) – but not significantly skewed, orNonewhen detection was not - (
Optional[float]) – possible (e.g. a blank page).Noneresults are cached too.
ensure_elements_loaded
Section titled “ensure_elements_loaded”ensure_elements_loaded() -> NoneForce the underlying element manager to load elements.
export
Section titled “export”export( path: Union[str, Path], *, resolution: Optional[float] = None, width: Optional[int] = None, layout: Literal['stack', 'grid', 'single'] = 'stack', stack_direction: Literal['vertical', 'horizontal'] = 'vertical', gap: int = 5, columns: Optional[int] = None, crop: Union[bool, Literal['content']] = False, crop_bbox: Optional[Tuple[float, float, float, float]] = None, format: Optional[str] = None, **kwargs,) -> NoneExport a clean image to file.
This is a convenience method that renders and saves in one step.
Parameters:
- path (
Union[str, Path]) – Output file path - resolution (
Optional[float]) – DPI for rendering - width (
Optional[int]) – Target width in pixels - layout (
Literal['stack', 'grid', 'single']) – How to arrange multiple pages/regions - stack_direction (
Literal['vertical', 'horizontal']) – Direction for stack layout - gap (
int) – Pixels between stacked images - columns (
Optional[int]) – Number of columns for grid layout - crop (
Union[bool, Literal['content']]) – Cropping mode (False, True, int for padding, ‘wide’, or Region) - crop_bbox (
Optional[Tuple[float, float, float, float]]) – Explicit crop bounds - format (
Optional[str]) – Image format (inferred from path if not specified) - **kwargs – Additional parameters passed to rendering
extract
Section titled “extract”extract( schema: Union[Type[Any], Sequence[str]], client: Any = None, analysis_key: str = 'structured', prompt: Optional[str] = None, using: str = 'text', model: Optional[str] = None, engine: Optional[str] = None, overwrite: bool = True, **kwargs: Any,)Run structured extraction and return the result.
Parameters:
- schema (
Union[Type[Any], Sequence[str]]) – A Pydantic BaseModel class or list of field name strings. - client (
Any) – An OpenAI-compatible client instance. When provided andengineis not set, extraction defaults to the LLM text path. - analysis_key (
str) – Key to store results under inself.analyses. - prompt (
Optional[str]) – Custom system prompt for the LLM. - using (
str) – Content mode —'text'(layout text) or'vision'(rendered image). Vision extraction requires eitherclient=...orengine='vlm'. - model (
Optional[str]) – Model identifier passed to the LLM client. - engine (
Optional[str]) –'llm','doc_qa','vlm', or None (auto-detect from client). - overwrite (
bool) – Re-run if results already exist for analysis_key. - **kwargs (
Any) – Extra arguments forwarded to the extraction engine.citations(bool): When True, each field’s result includes source citations mapping the value back to PDF elements.confidence: Per-field confidence scoring. AcceptsTrueor'range'for 0.0–1.0 scale, alistof categorical levels, or adictmapping values to descriptions.instructions(str): Domain-specific guidance appended to the LLM prompt, affecting all reasoning.
Returns:
- class:
StructuredDataResultwith attribute, item, and iteration access:
.. code-block:: python
result = page.extract(MySchema, client=client, citations=True)
result.site # "Chicago" (attribute access)result["site"].value # "Chicago" (item access)result["site"].citations # ElementCollection of source elementsresult["site"].citations.show()result["site"].confidence # 0.95 (when confidence= is set)result.confidences # {"site": 0.95, ...}result.to_dict() # {"site": "Chicago", ...}result.show() # highlight all citations on pageextract_anchored_rows
Section titled “extract_anchored_rows”extract_anchored_rows( anchors: Union[str, Iterable[Any], Callable[[Any], Iterable[Any]]], *, content_selector: str = 'text', elements: Optional[Union[str, Iterable[Any], Callable[[Any], Iterable[Any]]]] = None, side: Literal['right', 'left', 'both'] = 'right', y_tolerance: Optional[float] = None, x_gap: float = 0, include_anchor: bool = False, sort: bool = True, apply_exclusions: bool = True,) -> List[AnchoredRow]Collect same-row text-like elements relative to anchor elements.
Use this when the visual structure is row-oriented but not a normal table: margin line numbers, stable first-column IDs, or other anchors that identify which same-row content belongs together.
Parameters:
- anchors (
Union[str, Iterable[Any], Callable[[Any], Iterable[Any]]]) – Selector, iterable, or callable returning the row anchors. Callable inputs receive this page. - content_selector (
str) – Selector used for candidate row content whenelementsis not supplied. - elements (
Optional[Union[str, Iterable[Any], Callable[[Any], Iterable[Any]]]]) – Optional selector, iterable, or callable for candidate row content. Use this to limit matching to a table/section band. - side (
Literal['right', 'left', 'both']) – Collect content to the"right","left", or on"both"sides of each anchor. - y_tolerance (
Optional[float]) – Maximum vertical midpoint distance for same-row matching. Defaults to a value derived from anchor height. - x_gap (
float) – Required gap between anchor and content for left/right matching. - include_anchor (
bool) – Include the anchor itself in the returned row text. - sort (
bool) – Sort row elements by x-position before joining text. - apply_exclusions (
bool) – Respect exclusions when resolving selector inputs.
Returns:
- (
List[AnchoredRow]) – A list ofAnchoredRowobjects with the anchor, collected elements, - (
List[AnchoredRow]) – joined text, union bbox, and page number.
extract_ocr_elements
Section titled “extract_ocr_elements”extract_ocr_elements( *, engine: Optional[str] = None, options: Optional[Any] = None, languages: Optional[List[str]] = None, min_confidence: Optional[float] = None, device: Optional[str] = None, resolution: Optional[int] = None, apply_exclusions: bool = True, model: Optional[str] = None, client: Optional[Any] = None, prompt: Optional[str] = None, instructions: Optional[str] = None, max_new_tokens: Optional[int] = None, layout: Optional[bool | str] = None, preserve_markup: bool = False,) -> List[Any]Extract classic or VLM OCR elements without mutating the page.
extract_structured_data
Section titled “extract_structured_data”extract_structured_data(*args, **kwargs)Alias for :meth:extract.
extract_table
Section titled “extract_table”extract_table( method: Optional[str] = None, table_settings: Optional[dict] = None, use_ocr: bool = False, ocr_config: Optional[dict] = None, text_options: Optional[Dict[str, Any]] = None, cell_extraction_func: Optional[Callable[[Any], Optional[str]]] = None, cell_extract: Literal['text', 'words'] = 'text', cell_overlap: Literal['center', 'full', 'partial'] = 'center', cell_newlines: Union[bool, str] = True, show_progress: bool = False, content_filter: Optional[Union[str, Sequence[str], Callable[[str], bool]]] = None, apply_exclusions: bool = True, verticals: Optional[Sequence[float]] = None, horizontals: Optional[Sequence[float]] = None, outer: bool = False, structure_engine: Optional[str] = None,) -> TableResultCall the table service with the canonical extract_table signature.
For tiny table text where character-level spacing is unreliable, use
cell_extract="words" with cell_overlap and cell_newlines.
Arbitrary cell_extraction_func callbacks are supported but run once
per cell and are slower on large tables.
extract_table_guided
Section titled “extract_table_guided”extract_table_guided( headers: Union[str, ElementCollection[Any], Sequence[Any], None], row_anchors: Union[str, Iterable[Any], Callable[[Any], Iterable[Any]]], *, header_anchor: Optional[Any] = None, header_method: Literal['min_crossings', 'seam_carving'] = 'min_crossings', min_width: Optional[float] = None, max_width: Optional[float] = None, margin: float = 0.5, row_stabilization: bool = True, num_samples: int = 400, snap_vertical: bool = True, snap_vertical_kwargs: Optional[Dict[str, Any]] = None, row_align: Union[Literal['left', 'right', 'center', 'between'], Literal['top', 'bottom']] = 'between', row_outer: Union[bool, Literal['first', 'last']] = True, source: str = 'guides_temp', cell_padding: float = 0.5, include_outer_boundaries: bool = True, method: Optional[str] = None, table_settings: Optional[dict] = None, use_ocr: bool = False, ocr_config: Optional[dict] = None, text_options: Optional[Dict[str, Any]] = None, cell_extraction_func: Optional[Callable[[Any], Optional[str]]] = None, cell_extract: Literal['text', 'words'] = 'words', cell_overlap: Literal['center', 'full', 'partial'] = 'center', cell_newlines: Union[bool, str] = True, show_progress: bool = False, content_filter: Optional[Union[str, Sequence[str], Callable[[str], bool]]] = None, apply_exclusions: bool = True, header: Union[str, List[str], None] = 'first', skip_repeating_headers: Optional[bool] = None, structure_engine: Optional[str] = None,) -> TableResultExtract a table using header-derived columns and row anchors.
This is a convenience wrapper for the common difficult-table pattern: visible headers define approximate vertical column boundaries, stable row IDs/case numbers define horizontal row boundaries, and vertical guides are optionally snapped into nearby whitespace before extraction.
Parameters:
- headers (
Union[str, ElementCollection[Any], Sequence[Any], None]) – Header elements or names used for vertical guides. Header text strings are accepted for simple unique headers, but selected header elements are more reliable for crowded tables, duplicate labels, and repeated page text. If element headers are provided andheader_anchoris omitted, the first header element is used to include the header row as the first horizontal guide. If header names are provided andheader_anchoris omitted, the first matching header text is used as the header row anchor when it can be found. - row_anchors (
Union[str, Iterable[Any], Callable[[Any], Iterable[Any]]]) – Selector, iterable, or callable returning stable row markers such as IDs, case numbers, or first-column values. - header_anchor (
Optional[Any]) – Optional element or selector for the header row marker. Use this when string headers are repeated or ambiguous. - header_method (
Literal['min_crossings', 'seam_carving']) – Strategy passed tovertical.from_headers(...). - min_width (
Optional[float]) – Optional minimum column width for header-derived guides. - max_width (
Optional[float]) – Optional maximum column width for header-derived guides. - margin (
float) – Header-search margin used byfrom_headers. - row_stabilization (
bool) – Stabilize header separators with nearby row text. - num_samples (
int) – Sample count used by seam/min-crossing detection. - snap_vertical (
bool) – Whether to snap vertical guides into whitespace gaps. - snap_vertical_kwargs (
Optional[Dict[str, Any]]) – Options forvertical.snap_to_whitespace. - row_align (
Union[Literal['left', 'right', 'center', 'between'], Literal['top', 'bottom']]) – Alignment mode for row-anchor horizontal guides. - row_outer (
Union[bool, Literal['first', 'last']]) – Whether to add outer horizontal boundary guides. - source (
str) – Source label for temporary guide grid regions. - cell_padding (
float) – Padding for guide-built cell regions. - include_outer_boundaries (
bool) – Add table bounds from the page when outer guides are missing. - method (
Optional[str]) – Optional table extraction method. - table_settings (
Optional[dict]) – Optional table-engine settings. - use_ocr (
bool) – Whether to use OCR text for cell extraction. - ocr_config (
Optional[dict]) – OCR configuration. - text_options (
Optional[Dict[str, Any]]) – Text extraction options. - cell_extraction_func (
Optional[Callable[[Any], Optional[str]]]) – Optional custom cell extraction callback. - cell_extract (
Literal['text', 'words']) –"words"is the default for crowded native text; use"text"for character-map extraction. - cell_overlap (
Literal['center', 'full', 'partial']) – Word overlap mode forcell_extract="words". - cell_newlines (
Union[bool, str]) – Newline handling for extracted cell text. - show_progress (
bool) – Controls progress reporting in supported engines. - content_filter (
Optional[Union[str, Sequence[str], Callable[[str], bool]]]) – Optional content filtering function or patterns. - apply_exclusions (
bool) – Respect page exclusions while resolving anchors and extracting cell text. - header (
Union[str, List[str], None]) – Header handling passed toGuides.extract_table. - skip_repeating_headers (
Optional[bool]) – Remove duplicate header rows when relevant. - structure_engine (
Optional[str]) – Optional provider-backed structure engine.
Returns:
- (
TableResult) – ATableResultextracted from the generated guides.
extract_tables
Section titled “extract_tables”extract_tables( method: Optional[str] = None, table_settings: Optional[dict] = None,) -> List[TableResult]Call the table service to extract every table for the host.
extract_text
Section titled “extract_text”extract_text( *, layout: bool | TextLayoutOptions = False, apply_exclusions: bool = True, newlines: bool | str = True, whitespace: WhitespaceMode = 'preserve', strip: bool = True, bidi: bool = True, content_filter: ContentFilter | None = None,) -> strExtract spatial text with explicit acquisition and transform options.
layout enables spatial layout reconstruction, while
apply_exclusions controls registered exclusion regions. Newline,
whitespace, bidi, filtering, and stripping transforms are applied in a
stable order after acquisition. Regex filters remove matches; callable
filters are predicates invoked once for each Unicode codepoint.
extract_text_result
Section titled “extract_text_result”extract_text_result( *, layout: bool | TextLayoutOptions = False, apply_exclusions: bool = True,) -> ExtractedTextReturn raw spatial text and provenance using acquisition options only.
extracted
Section titled “extracted”extracted(analysis_key: Optional[str] = None) -> AnyRetrieve the stored result from a previous .extract() call.
Returns the same :class:StructuredDataResult that .extract()
returned, or None if the extraction failed.
find( selector: Optional[str] = None, *, text: Optional[Union[str, Sequence[str]]] = None, overlap: Optional[str] = None, apply_exclusions: bool = True, regex: bool = False, case: bool = True, text_tolerance: Optional[Dict[str, Any]] = None, auto_text_tolerance: Optional[Union[bool, Dict[str, Any]]] = None, reading_order: bool = True, near_threshold: Optional[float] = None, engine: Optional[str] = None,) -> Optional['Element']Resolve a selector/text query against the host using the selector service.
find_all
Section titled “find_all”find_all( selector: Optional[str] = None, *, text: Optional[Union[str, Sequence[str]]] = None, overlap: Optional[str] = None, apply_exclusions: bool = True, regex: bool = False, case: bool = True, text_tolerance: Optional[Dict[str, Any]] = None, auto_text_tolerance: Optional[Union[bool, Dict[str, Any]]] = None, reading_order: bool = True, near_threshold: Optional[float] = None, engine: Optional[str] = None,) -> 'ElementCollection'Return every element that matches the selector/text query.
get_all_elements_raw
Section titled “get_all_elements_raw”get_all_elements_raw() -> List[Element]Return all elements without applying exclusions.
get_config
Section titled “get_config”get_config(key: str, default: Any = None, *, scope: str = 'region') -> Anyget_elements
Section titled “get_elements”get_elements(apply_exclusions=True, debug_exclusions: bool = False) -> List[Element]Get all elements on this page.
Parameters:
- apply_exclusions – Whether to apply exclusion regions (default: True).
- debug_exclusions (
bool) – Whether to output detailed exclusion debugging info (default: False).
Returns:
- (
List[Element]) – List of all elements on the page, potentially filtered by exclusions.
get_elements_by_type
Section titled “get_elements_by_type”get_elements_by_type(element_type: str) -> List[Any]Return the elements for a specific backing collection (e.g. ‘words’).
get_highlighter
Section titled “get_highlighter”get_highlighter() -> HighlightingServiceExpose the page-level HighlightingService for Visualizable consumers.
get_rendering_service
Section titled “get_rendering_service”get_rendering_service()Public accessor for the rendering service (primarily for tests).
get_section_between
Section titled “get_section_between”get_section_between( start_element=None, end_element=None, include_boundaries='both', orientation='vertical',) -> RegionGet a section between two elements on this page.
Parameters:
- start_element – Element marking the start of the section
- end_element – Element marking the end of the section
- include_boundaries – How to include boundary elements: ‘start’, ‘end’, ‘both’, or ‘none’
- orientation – ‘vertical’ (default) or ‘horizontal’ - determines section direction
Returns:
- (
Region) – Region representing the section
Raises:
- (
ValueError) – Propagated from Region.get_section_between for invalid inputs.
get_sections
Section titled “get_sections”get_sections( start_elements: Union[str, Sequence[Element], ElementCollection, None] = None, end_elements: Union[str, Sequence[Element], ElementCollection, None] = None, include_boundaries: str = 'start', y_threshold: float = 5.0, bounding_box: Optional[Bounds] = None, orientation: str = 'vertical', **kwargs: Any,) -> ElementCollection[Region]Delegate section extraction to the Region implementation.
guides
Section titled “guides”guides(*args, **kwargs)has_element_cache
Section titled “has_element_cache”has_element_cache() -> boolReturn True if the element manager currently holds any elements.
height (attribute)
Section titled “height (attribute)”height: floatGet page height.
highlight
Section titled “highlight”highlight(*elements, **kwargs)Convenience method for highlighting elements in Jupyter/Colab.
This method creates a highlight context, adds the elements, and returns the resulting image. It’s designed for simple one-liner usage in notebooks.
Parameters:
- *elements – Elements or element collections to highlight
- **kwargs – Additional parameters passed to show()
Returns:
- PIL Image with highlights
Example:
# Simple one-liner highlightingpage.highlight(left, mid, right)
# With custom colorspage.highlight( (tables, 'blue'), (headers, 'red'), (footers, 'green'))highlights
Section titled “highlights”highlights(show: bool = False) -> HighlightContextCreate a highlight context for accumulating highlights.
This allows for clean syntax to show multiple highlight groups:
Example:
with page.highlights() as h: h.add(page.find_all('table'), label='tables', color='blue') h.add(page.find_all('text:bold'), label='bold text', color='red') h.show()Or With Automatic Display: with page.highlights(show=True) as h: h.add(page.find_all(‘table’), label=‘tables’) h.add(page.find_all(‘text:bold’), label=‘bold’) # Automatically shows when exiting the context
Parameters:
- show (
bool) – If True, automatically show highlights when exiting context
Returns:
- (
HighlightContext) – HighlightContext for accumulating highlights
images (attribute)
Section titled “images (attribute)”images: List[Any]Get all embedded raster images on this page.
index (attribute)
Section titled “index (attribute)”index: intGet page index (0-based).
inspect
Section titled “inspect”inspect(limit: int = 30, **kwargs)Inspect the page content using the describe service.
invalidate_element_cache
Section titled “invalidate_element_cache”invalidate_element_cache() -> NoneInvalidate the cached elements so they are reloaded on next access.
iter_regions
Section titled “iter_regions”iter_regions() -> List[Region]Return a list of regions currently registered with the page.
layout_analyzer (attribute)
Section titled “layout_analyzer (attribute)”layout_analyzer: LayoutAnalyzerGet or create the layout analyzer for this page.
lines (attribute)
Section titled “lines (attribute)”lines: List[Any]Get all line elements on this page.
metadata (attribute)
Section titled “metadata (attribute)”metadata: Dict[str, Any] = {}number (attribute)
Section titled “number (attribute)”number: intGet page number (1-based).
page_number (attribute)
Section titled “page_number (attribute)”page_number: intGet page number (1-based).
pages (attribute)
Section titled “pages (attribute)”pagespdf (attribute)
Section titled “pdf (attribute)”pdf: PDFProvides public access to the parent PDF object.
qa_target (attribute)
Section titled “qa_target (attribute)”qa_target = 'page'rects (attribute)
Section titled “rects (attribute)”rects: List[Any]Get all rectangle elements on this page.
region
Section titled “region”region( left: Optional[float] = None, top: Optional[float] = None, right: Optional[float] = None, bottom: Optional[float] = None, width: Union[str, float, None] = None, height: Optional[float] = None,) -> AnyCreate a region on this page with more intuitive named parameters, allowing definition by coordinates or by coordinate + dimension.
Parameters:
- left (
Optional[float]) – Left x-coordinate (default: 0 if width not used). - top (
Optional[float]) – Top y-coordinate (default: 0 if height not used). - right (
Optional[float]) – Right x-coordinate (default: page width if width not used). - bottom (
Optional[float]) – Bottom y-coordinate (default: page height if height not used). - width (
Union[str, float, None]) – Width definition. Can be: - Numeric: The width of the region in points. Cannot be used with both left and right. - String ‘full’: Sets region width to full page width (overrides left/right). - String ‘element’ or None (default): Uses provided/calculated left/right, defaulting to page width if neither are specified. - height (
Optional[float]) – Numeric height of the region. Cannot be used with both top and bottom.
Returns:
- (
Any) – Region object for the specified coordinates
Raises:
- (
ValueError) – If conflicting arguments are provided (e.g., top, bottom, and height) or if width is an invalid string.
Examples:
>>> page.region(top=100, height=50) # Region from y=100 to y=150, default width>>> page.region(left=50, width=100) # Region from x=50 to x=150, default height>>> page.region(bottom=500, height=50) # Region from y=450 to y=500>>> page.region(right=200, width=50) # Region from x=150 to x=200>>> page.region(top=100, bottom=200, width="full") # Explicit full widthremove_element
Section titled “remove_element”remove_element(element: Any, element_type: Optional[str] = None) -> boolRemove an element from the backing collection.
remove_elements_by_source
Section titled “remove_elements_by_source”remove_elements_by_source(element_type: str, source: str) -> intRemove all elements of a given type whose source matches.
remove_ocr_elements
Section titled “remove_ocr_elements”remove_ocr_elements(*args, **kwargs) -> intRemove OCR-derived elements from the backing element manager.
remove_regions
Section titled “remove_regions”remove_regions( *, name: Optional[str] = None, source: Optional[str] = None, region_type: Optional[str] = None, predicate: Optional[Callable[[Region], bool]] = None,) -> intRemove regions from the page based on optional filters.
Parameters:
- name (
Optional[str]) – Match the stable name used when the Region was registered. - source (
Optional[str]) – Match regions whoseregion.sourceequals this string. - region_type (
Optional[str]) – Match regions whoseregion.region_typeequals this string. - predicate (
Optional[Callable[[Region], bool]]) – Additional callable that returns True when a region should be removed.
Returns:
- (
int) – The number of regions removed.
remove_regions_by_source
Section titled “remove_regions_by_source”remove_regions_by_source(source: str) -> intRemove all registered regions that match the requested source.
remove_text_layer
Section titled “remove_text_layer”remove_text_layer() -> PageRemove all text elements from this page.
This removes all text elements (words and characters) from the page, effectively clearing the text layer.
Returns:
- (
Page) – Self for method chaining
render
Section titled “render”render( *, resolution: Optional[float] = None, width: Optional[int] = None, highlights: Optional[Union[List[Dict[str, Any]], bool]] = None, labels: bool = False, label_format: Optional[str] = None, render_ocr: bool = False, layout: Literal['stack', 'grid', 'single'] = 'stack', stack_direction: Literal['vertical', 'horizontal'] = 'vertical', gap: int = 5, columns: Optional[int] = None, crop: Union[bool, int, str, 'Region', Literal['wide']] = False, crop_bbox: Optional[Tuple[float, float, float, float]] = None, **kwargs,) -> Optional[PILImage]Generate a clean image, with optional explicit highlights.
This method produces publication-ready images without any debugging annotations or persistent highlights.
Parameters:
- resolution (
Optional[float]) – DPI for rendering (default from global settings) - width (
Optional[int]) – Target width in pixels (overrides resolution) - highlights (
Optional[Union[List[Dict[str, Any]], bool]]) – Optional explicit highlight groups/specs to render - labels (
bool) – Whether to render a legend for explicit highlights - label_format (
Optional[str]) – Format string for generated highlight labels - render_ocr (
bool) – Whether to render OCR text overlay on the image - layout (
Literal['stack', 'grid', 'single']) – How to arrange multiple pages/regions - stack_direction (
Literal['vertical', 'horizontal']) – Direction for stack layout - gap (
int) – Pixels between stacked images - columns (
Optional[int]) – Number of columns for grid layout - crop (
Union[bool, int, str, 'Region', Literal['wide']]) – Cropping mode (False, True, int for padding, ‘wide’, or Region) - crop_bbox (
Optional[Tuple[float, float, float, float]]) – Explicit crop bounds - **kwargs – Additional parameters passed to rendering
Returns:
- (
Optional[PILImage]) – PIL Image object or None if nothing to render
rotate
Section titled “rotate”rotate( angle: int = 90, direction: Literal['clockwise', 'counterclockwise'] = 'clockwise',) -> PageReturn a rotated view of this page without mutating the original.
Rotations are limited to right angles and are applied before pdfplumber processes layout, so all downstream extraction (text, tables, etc.) sees the content in the new orientation.
Parameters:
- angle (
int) – Magnitude of rotation in degrees (0/90/180/270). - direction (
Literal['clockwise', 'counterclockwise']) – Direction of rotation; defaults to clockwise.
Returns:
- (
Page) – A new Page instance backed by a rotated pdfplumber.Page.
save_image
Section titled “save_image”save_image( filename: str, width: Optional[int] = None, labels: bool = True, legend_position: str = 'right', render_ocr: bool = False, include_highlights: bool = True, resolution: float = 144, **kwargs,) -> PageSave the page image to a file, rendering highlights via HighlightingService.
Parameters:
- filename (
str) – Path to save the image to. - width (
Optional[int]) – Optional width for the output image. - labels (
bool) – Whether to include a legend. - legend_position (
str) – Position of the legend. - render_ocr (
bool) – Whether to render OCR text. - include_highlights (
bool) – Whether to render highlights. - resolution (
float) – Resolution in DPI for base image rendering (default: 144 DPI, equivalent to previous scale=2.0). - **kwargs – Additional args for rendering.
Returns:
- (
Page) – Self for method chaining.
save_searchable
Section titled “save_searchable”save_searchable(output_path: Union[str, Path], dpi: int = 300)Saves the PDF page with an OCR text layer, making content searchable.
Requires optional dependencies. Install with: pip install “natural-pdf[export]”
Ocr Must Have Been Applied To The Pages Beforehand: (e.g., pdf.apply_ocr()).
Parameters:
- output_path (
Union[str, Path]) – Path to save the searchable PDF. - dpi (
int) – Resolution for rendering and OCR overlay (default 300).
selector_flow
Section titled “selector_flow”selector_flow() -> Anyselector_page
Section titled “selector_page”selector_page() -> Anyselector_region
Section titled “selector_region”selector_region() -> Anyservices (attribute)
Section titled “services (attribute)”services: ServiceNamespaceshow( *, resolution: Optional[float] = None, width: Optional[int] = None, color: Optional[Union[str, Tuple[int, int, int]]] = None, labels: bool = True, label_format: Optional[str] = None, highlights: Optional[Union[List[Dict[str, Any]], bool]] = None, legend_position: str = 'right', annotate: Optional[Union[str, List[str]]] = None, render_ocr: bool = False, layout: Optional[Literal['stack', 'grid', 'single']] = None, stack_direction: Literal['vertical', 'horizontal'] = 'vertical', gap: int = 5, columns: Optional[int] = 6, limit: Optional[int] = 30, crop: Union[bool, int, str, 'Region', Literal['wide']] = False, crop_bbox: Optional[Tuple[float, float, float, float]] = None, **kwargs,) -> Optional[PILImage]Generate a preview image with highlights.
This method is for interactive debugging and visualization. Elements are highlighted to show what’s selected or being worked with.
Parameters:
- resolution (
Optional[float]) – DPI for rendering (default from global settings) - width (
Optional[int]) – Target width in pixels (overrides resolution) - color (
Optional[Union[str, Tuple[int, int, int]]]) – Default highlight color - labels (
bool) – Whether to show labels for highlights - label_format (
Optional[str]) – Format string for labels (e.g., “Element {index}”) - highlights (
Optional[Union[List[Dict[str, Any]], bool]]) – Additional highlight groups to show, or False to disable all highlights - legend_position (
str) – Position of legend/colorbar (‘right’, ‘left’, ‘top’, ‘bottom’) - annotate (
Optional[Union[str, List[str]]]) – Attribute name(s) to display on highlights (string or list) - render_ocr (
bool) – Whether to render OCR text overlay on the image - layout (
Optional[Literal['stack', 'grid', 'single']]) – How to arrange multiple pages/regions (defaults to ‘grid’ for multi-page, ‘single’ for single page) - stack_direction (
Literal['vertical', 'horizontal']) – Direction for stack layout - gap (
int) – Pixels between stacked images - columns (
Optional[int]) – Number of columns for grid layout (defaults to 6) - limit (
Optional[int]) – Maximum number of pages to display (default 30, None for all) - crop (
Union[bool, int, str, 'Region', Literal['wide']]) – Cropping mode: - False: No cropping (default) - True: Tight crop to element bounds - int: Padding in PDF points around element (crop bounds are computed in PDF coordinate space, then scaled by resolution) - ‘wide’: Full page width, cropped vertically to element - Region: Crop to the bounds of another region - crop_bbox (
Optional[Tuple[float, float, float, float]]) – Explicit crop bounds - **kwargs – Additional parameters passed to rendering
Returns:
- (
Optional[PILImage]) – PIL Image object or None if nothing to render
size (attribute)
Section titled “size (attribute)”size: Tuple[float, float]Get the size of the page in points.
skew_angle (attribute)
Section titled “skew_angle (attribute)”skew_angle: Optional[float]Get the detected skew angle for this page (if calculated).
split(divider, **kwargs: Any) -> ElementCollection[Region]Divide the page into sections based on the provided divider elements.
text_style_labels (attribute)
Section titled “text_style_labels (attribute)”text_style_labels: List[str]Get a sorted list of unique text style labels found on the page.
Runs text style analysis with default options if it hasn’t been run yet.
To use custom options, call analyze_text_styles(options=...) explicitly first.
Returns:
- (
List[str]) – A sorted list of unique style label strings.
to_llm
Section titled “to_llm”to_llm(**kwargs) -> strReturn an LLM-optimized text representation of this page.
to_markdown
Section titled “to_markdown”to_markdown( *, model: Optional[str] = None, client: Optional[Any] = None, resolution: int = 144, render_kwargs: Optional[Dict[str, Any]] = None, max_new_tokens: Optional[int] = None, prompt: Optional[str] = None,) -> strConvert this page to Markdown using a VLM.
Falls back to extract_text() when no model is configured.
Recommended models (olmOCR-bench scores):
-
Local (HuggingFace):
"rednote-hilab/dots.mocr"(83.9) — 3B, needs GPU."lightonai/LightOnOCR-2-1B"(83.2) — 1B, runs on CPU/MPS/GPU. Install:pip install transformers>=5.0.0"Qwen/Qwen2.5-VL-7B-Instruct"(65.5) — 7B, needs GPU. -
Remote (via
client=):"gpt-4o"(69.9),"gemini-2.0-flash"(63.8).
Parameters:
- model (
Optional[str]) – HuggingFace model ID or remote model name. - client (
Optional[Any]) – OpenAI-compatible client for remote inference. - resolution (
int) – DPI for rendering the page image. - render_kwargs (
Optional[Dict[str, Any]]) – Extra kwargs forrender(). - max_new_tokens (
Optional[int]) – Maximum tokens for the VLM to generate. - prompt (
Optional[str]) – Custom prompt override.
Returns:
- (
str) – Markdown string.
to_region
Section titled “to_region”to_region() -> RegionReturn a Region covering the full page.
until( selector: str, include_endpoint: bool = True, *, text: Optional[Union[str, Sequence[str]]] = None, apply_exclusions: bool = True, regex: bool = False, case: bool = True, text_tolerance: Optional[Dict[str, Any]] = None, auto_text_tolerance: Optional[Union[bool, Dict[str, Any]]] = None, reading_order: bool = True,) -> AnySelect content from the top of the page until matching selector.
Parameters:
- selector (
str) – CSS-like selector string - include_endpoint (
bool) – Whether to include the endpoint element in the region - **kwargs – Additional selection parameters
Returns:
- (
Any) – Region object representing the selected content
Examples:
>>> page.until('text:contains("Conclusion")') # Select from top to conclusion>>> page.until('line[width>=2]', include_endpoint=False) # Select up to thick lineupdate_ocr
Section titled “update_ocr”update_ocr( transform: Callable[[Any], Optional[str]], *, apply_exclusions: bool = False, max_workers: Optional[int] = None, progress_callback: Optional[Callable[[], None]] = None, show_progress: bool = True,) -> Pageupdate_text
Section titled “update_text”update_text( transform: Callable[[Any], Optional[str]], *, selector: str = 'text', apply_exclusions: bool = False, max_workers: Optional[int] = None, progress_callback: Optional[Callable[[], None]] = None, show_progress: bool = True,) -> Pageviewer
Section titled “viewer”viewer( *, resolution: int = 150, elements_to_render: Optional[List[Element]] = None, include_attributes: Optional[List[str]] = None,) -> AnyCreates and returns an interactive viewer for exploring elements on this page.
The viewer shows every element on the page (exclusions are NOT applied — this is a debugging view), unless an explicit element list is given.
Parameters:
- resolution (
int) – Rendering resolution in DPI (default 150). - elements_to_render (
Optional[List[Element]]) – Explicit list of elements to overlay instead of all page elements. - include_attributes (
Optional[List[str]]) – Extra element attributes to show in the info panel.
Returns:
- (
Any) – An InteractiveViewerWidget instance ready for display in Jupyter.
width (attribute)
Section titled “width (attribute)”width: floatGet page width.
without_exclusions
Section titled “without_exclusions”without_exclusions()Context manager that temporarily disables exclusion processing.
This prevents infinite recursion when exclusion callables themselves use find() operations. While in this context, all find operations will skip exclusion filtering.
Example:
```python# This exclusion would normally cause infinite recursion:page.add_exclusion(lambda p: p.find("text:contains('Header')").expand())
# But internally, it's safe because we use:with page.without_exclusions(): region = exclusion_callable(page)**Yields:**
- The page object with exclusions temporarily disabled.
<a id="natural_pdf.Page.words"></a>
#### `words` *(attribute)*
```pythonwords: List[Any]Get all word elements on this page.
Region
Section titled “Region”Bases: ClassificationResultAccessorMixin, OCRDirectTargetMixin, SpatialTextMixin, SelectorHostMixin, DirectionalMixin, ServiceHostMixin, SinglePageContextMixin, RegionGeometryMixin, Visualizable, SupportsSections
Region( page: 'Page', bbox: Tuple[float, float, float, float], polygon: Optional[List[Tuple[float, float]]] = None, parent: Optional['Region'] = None, label: Optional[str] = None,)Represents a rectangular region on a page.
Regions are fundamental building blocks in natural-pdf that define rectangular areas of a page for analysis, extraction, and navigation. They can be created manually or automatically through spatial navigation methods like .below(), .above(), .left(), and .right() from elements or other regions.
Regions integrate multiple analysis capabilities through mixins and provide:
- Element filtering and collection within the region boundary
- OCR processing for the region area
- Table detection and extraction
- AI-powered classification and structured data extraction
- Visual rendering and debugging capabilities
- Text extraction with spatial awareness
The Region class supports both rectangular and polygonal boundaries, making it suitable for complex document layouts and irregular shapes detected by layout analysis algorithms.
Attributes:
- page (
'Page') – Reference to the parent Page object. - bbox (
Tuple[float, float, float, float]) – Bounding box tuple (x0, top, x1, bottom) in PDF coordinates. - x0 (
float) – Left x-coordinate. - top (
float) – Top y-coordinate (minimum y). - x1 (
float) – Right x-coordinate. - bottom (
float) – Bottom y-coordinate (maximum y). - width (
float) – Region width (x1 - x0). - height (
float) – Region height (bottom - top). - polygon (
List[Tuple[float, float]]) – List of coordinate points for non-rectangular regions. - label – Optional descriptive label for the region.
- metadata (
Dict[str, Any]) – Dictionary for storing analysis results and custom data.
Example:
Creating regions:```pythonpdf = npdf.PDF("document.pdf")page = pdf.pages[0]
# Manual region creationheader_region = page.region(0, 0, page.width, 100)
# Spatial navigation from elementssummary_text = page.find('text:contains("Summary")')content_region = summary_text.below(until='text[size>12]:bold')
# Extract content from regiontables = content_region.extract_table()text = content_region.get_text()Advanced usage:
# OCR processingregion.apply_ocr(engine='rapidocr', resolution=300)
# AI-powered extractiondata = region.extract_structured_data(MySchema)
# Visual debuggingregion.show(highlights=['tables', 'text'])Initialize a region.
Creates a Region object that represents a rectangular or polygonal area on a page.Regions are used for spatial navigation, content extraction, and analysis operations.
**Parameters:**
- **page** (`'Page'`) – Parent Page object that contains this region and provides access to document elements and analysis capabilities.- **bbox** (`Tuple[float, float, float, float]`) – Bounding box coordinates as (x0, top, x1, bottom) tuple in PDF coordinate system (points, with origin at bottom-left).- **polygon** (`Optional[List[Tuple[float, float]]]`) – Optional list of coordinate points [(x1,y1), (x2,y2), ...] for non-rectangular regions. If provided, the region will use polygon-based intersection calculations instead of simple rectangle overlap.- **parent** (`Optional['Region']`) – Optional parent region for hierarchical document structure. Useful for maintaining tree-like relationships between regions.- **label** (`Optional[str]`) – Optional descriptive label for the region, useful for debugging and identification in complex workflows.
**Example:**
```python```pythonpdf = npdf.PDF("document.pdf")page = pdf.pages[0]
# Rectangular regionheader = Region(page, (0, 0, page.width, 100), label="header")
# Polygonal region (from layout detection)table_polygon = [(50, 100), (300, 100), (300, 400), (50, 400)]table_region = Region(page, (50, 100, 300, 400), polygon=table_polygon, label="table")> **Note:**> Regions are typically created through page methods like page.region() or> spatial navigation methods like element.below(). Direct instantiation is> used mainly for advanced workflows or layout analysis integration.
<a id="natural_pdf.Region.above"></a>
#### `above`
```pythonabove( height: Optional[float] = None, width: str = 'full', include_source: bool = False, until: Optional[str] = None, include_endpoint: bool = True, offset: Optional[float] = None, apply_exclusions: bool = True, multipage: Optional[bool] = None, within: Optional['Region'] = None, anchor: str = 'start', **kwargs,) -> Optional[Union['Region', 'FlowRegion']]Select region above this region.
Parameters:
- height (
Optional[float]) – Height of the region above, in points - width (
str) – Width mode - “full” for full page width or “element” for element width - include_source (
bool) – Whether to include this region in the result (default: False) - until (
Optional[str]) – Optional selector string to specify an upper boundary element - include_endpoint (
bool) – Whether to include the boundary element in the region (default: True) - offset (
Optional[float]) – Pixel offset when excluding source/endpoint (default: None, uses natural_pdf.options.layout.directional_offset) - multipage (
Optional[bool]) – Override global multipage behaviour; defaults to None meaning use global option. - **kwargs – Additional parameters
Returns:
- (
Optional[Union['Region', 'FlowRegion']]) – Region object representing the area above, or None if within constraint has no overlap
add_child
Section titled “add_child”add_child(child)Add a child region to this region.
Used for hierarchical document structure when using models like Docling that understand document hierarchy.
Parameters:
- child – Region object to add as a child
Returns:
- Self for method chaining
alt_text (attribute)
Section titled “alt_text (attribute)”alt_text: Optional[str] = Noneanalyses (attribute)
Section titled “analyses (attribute)”analyses: Dict[str, Any]analyze_text_table_structure
Section titled “analyze_text_table_structure”analyze_text_table_structure( snap_tolerance: int = 10, join_tolerance: int = 3, min_words_vertical: int = 3, min_words_horizontal: int = 1, intersection_tolerance: int = 3, expand_bbox: Optional[Dict[str, int]] = None, **kwargs,) -> Optional[Dict]Analyzes the text elements within the region (or slightly expanded area) to find potential table structure (lines, cells) using text alignment logic adapted from pdfplumber.
Parameters:
- snap_tolerance (
int) – Tolerance for snapping parallel lines. - join_tolerance (
int) – Tolerance for joining collinear lines. - min_words_vertical (
int) – Minimum words needed to define a vertical line. - min_words_horizontal (
int) – Minimum words needed to define a horizontal line. - intersection_tolerance (
int) – Tolerance for detecting line intersections. - expand_bbox (
Optional[Dict[str, int]]) – Optional dictionary to expand the search area slightly beyond the region’s exact bounds (e.g., {‘left’: 5, ‘right’: 5}). - **kwargs – Additional keyword arguments passed to find_text_based_tables (e.g., specific x/y tolerances).
Returns:
- (
Optional[Dict]) – A dictionary containing ‘horizontal_edges’, ‘vertical_edges’, ‘cells’ (list of dicts), - (
Optional[Dict]) – and ‘intersections’, or None if pdfplumber is unavailable or an error occurs.
apply_custom_ocr
Section titled “apply_custom_ocr”apply_custom_ocr( ocr_function: CustomOCRCallable, source_label: str = 'custom-ocr', replace: OCRReplaceMode = 'ocr', confidence: Optional[float] = None, add_to_page: bool = True,) -> 'Region'apply_ocr
Section titled “apply_ocr”apply_ocr( engine: Optional[str] = None, *, options: Optional[Any] = None, languages: Optional[list[str]] = None, min_confidence: Optional[float] = None, device: Optional[str] = None, resolution: Optional[int] = None, detect_only: bool = False, apply_exclusions: bool = True, replace: OCRReplaceMode = 'ocr', use_cache: bool = True, model: Optional[str] = None, client: Optional[Any] = None, prompt: Optional[str] = None, instructions: Optional[str] = None, max_new_tokens: Optional[int] = None, layout: Optional[bool | str] = None, preserve_markup: bool = False, function: Optional[CustomOCRCallable] = None, source_label: str = 'custom-ocr', confidence: Optional[float] = None,) -> SelfApply OCR within this object’s spatial scope and return self.
This method has three validated modes:
- recognition (the default) recognizes text with a registered engine;
detect_only=Truerefreshes persistent text bounding boxes without deleting native or recognized text;function=recognizes text with a callable receiving each physical Region in the scope.
Parameters:
- engine (
Optional[str]) – Registered OCR engine name. When omitted, resolve the context default. Supplyingmodelorclientselects VLM OCR when no engine is named. - options (
Optional[Any]) – Typed engine-specific options object or validated mapping. - languages (
Optional[list[str]]) – Ordered language codes such as["en", "fr"]. - min_confidence (
Optional[float]) – Minimum accepted confidence between 0 and 1. - device (
Optional[str]) – Requested compute device, such as"cpu"or"cuda". - resolution (
Optional[int]) – Render resolution in DPI. - detect_only (
bool) – Refresh detection-only spatial artifacts instead of recognizing text. Detection preserves existing text. - apply_exclusions (
bool) – Mask configured exclusions in pixels sent to OCR. - replace (
OCRReplaceMode) – Recognition/function replacement policy:"ocr","all", or"none". Detection has its own refresh policy. - use_cache (
bool) – Allow the persistent OCR result cache when its identity can be proven safe. - model (
Optional[str]) – VLM model name. - client (
Optional[Any]) – OpenAI-compatible VLM client. - prompt (
Optional[str]) – Complete VLM prompt overriding the generated prompt. - instructions (
Optional[str]) – Additional VLM instructions. - max_new_tokens (
Optional[int]) – VLM generation limit. - layout (
Optional[bool | str]) – VLM layout mode (bool or registered detector name). - preserve_markup (
bool) – Preserve raw VLM markup in text metadata. - function (
Optional[CustomOCRCallable]) – Custom callable receiving a physical Region and returning recognized text orNone. It cannot be combined with engine, VLM, cache, exclusion, or detection controls. - source_label (
str) – Provenance label stored asocr_engineon custom-function output. Its selector-visible source remains"ocr"like every other OCR artifact. - confidence (
Optional[float]) – Confidence assigned to custom-function OCR text.
Returns:
- (
Self) – The receiving object for fluent chaining.
Raises:
- (
TypeError) – An argument has the wrong type orfunctionis not callable. - (
ValueError) – Mode-specific arguments conflict or a value is invalid.
ask(*args, **kwargs)associated_text_elements (attribute)
Section titled “associated_text_elements (attribute)”associated_text_elements: List[TextElement] = []attr(name: str) -> AnyGet an attribute value from this region.
This method provides a consistent interface for attribute access that works on both individual regions/elements and collections. When called on a single region, it simply returns the attribute value. When called on collections, it extracts the attribute from all items.
Parameters:
- name (
str) – The attribute name to retrieve (e.g., ‘text’, ‘width’, ‘height’)
Returns:
- (
Any) – The attribute value, or None if the attribute doesn’t exist
Examples:
# On a single regionregion = page.find('text:contains("Title")').expand(10)width = region.attr('width') # Same as region.width
# Consistent API across elements and regionsobj = page.find('*:contains("Title")') # Could be element or regiontext = obj.attr('text') # Works for bothbbox (attribute)
Section titled “bbox (attribute)”bbox: Tuple[float, float, float, float]Get the bounding box as (x0, top, x1, bottom).
below( height: Optional[float] = None, width: str = 'full', include_source: bool = False, until: Optional[str] = None, include_endpoint: bool = True, offset: Optional[float] = None, apply_exclusions: bool = True, multipage: Optional[bool] = None, within: Optional['Region'] = None, anchor: str = 'start', **kwargs,) -> Optional[Union['Region', 'FlowRegion']]Select region below this region.
Parameters:
- height (
Optional[float]) – Height of the region below, in points - width (
str) – Width mode - “full” for full page width or “element” for element width - include_source (
bool) – Whether to include this region in the result (default: False) - until (
Optional[str]) – Optional selector string to specify a lower boundary element - include_endpoint (
bool) – Whether to include the boundary element in the region (default: True) - offset (
Optional[float]) – Pixel offset when excluding source/endpoint (default: None, uses natural_pdf.options.layout.directional_offset) - multipage (
Optional[bool]) – Override global multipage behaviour; defaults to None meaning use global option. - **kwargs – Additional parameters
Returns:
- (
Optional[Union['Region', 'FlowRegion']]) – Region object representing the area below, or None if within constraint has no overlap
bottom (attribute)
Section titled “bottom (attribute)”bottom: floatGet the bottom coordinate.
boundary_element (attribute)
Section titled “boundary_element (attribute)”boundary_element: Optional['Element'] = Nonecategory (attribute)
Section titled “category (attribute)”category: Optional[str]Top category label for the last classification run.
category_confidence (attribute)
Section titled “category_confidence (attribute)”category_confidence: Optional[float]Confidence score associated with category.
checkbox_state (attribute)
Section titled “checkbox_state (attribute)”checkbox_state: Optional[str] = Nonechild_regions (attribute)
Section titled “child_regions (attribute)”child_regions: List['Region'] = []classification_results (attribute)
Section titled “classification_results (attribute)”classification_results: Optional[Dict[str, Any]]Full classification payload converted into a dictionary.
classify
Section titled “classify”classify( labels: List[str], *, model: Optional[str] = None, using: Optional[str] = None, min_confidence: float = 0.0, analysis_key: str = 'classification', multi_label: bool = False, **kwargs: Any,)Delegate classification to the classification service and return the result.
clear_text_layer
Section titled “clear_text_layer”clear_text_layer(*args, **kwargs) -> Tuple[int, int]Clear OCR results from the underlying managers and return totals.
clip( obj: Optional[Any] = None, left: Optional[float] = None, top: Optional[float] = None, right: Optional[float] = None, bottom: Optional[float] = None,) -> 'Region'Clip this region to specific bounds, either from another object with bbox or explicit coordinates.
The clipped region will be constrained to not exceed the specified boundaries. You can provide either an object with bounding box properties, specific coordinates, or both. When both are provided, explicit coordinates take precedence.
Parameters:
- obj (
Optional[Any]) – Optional object with bbox properties (Region, Element, TextElement, etc.) - left (
Optional[float]) – Optional left boundary (x0) to clip to - top (
Optional[float]) – Optional top boundary to clip to - right (
Optional[float]) – Optional right boundary (x1) to clip to - bottom (
Optional[float]) – Optional bottom boundary to clip to
Returns:
- (
'Region') – New Region with bounds clipped to the specified constraints
Examples:
# Clip to another region's boundsclipped = region.clip(container_region)
# Clip to any element's boundsclipped = region.clip(text_element)
# Clip to specific coordinatesclipped = region.clip(left=100, right=400)
# Mix object bounds with specific overridesclipped = region.clip(obj=container, bottom=page.height/2)confidence (attribute)
Section titled “confidence (attribute)”confidence: Optional[float] = Nonecontains
Section titled “contains”contains(element) -> boolcorrect_ocr
Section titled “correct_ocr”correct_ocr(*args, **kwargs)create_cells
Section titled “create_cells”create_cells()Create cell regions for a detected table by intersecting its row and column regions, and add them to the page.
Assumes child row and column regions are already present on the page.
Returns:
- Self for method chaining.
create_region
Section titled “create_region”create_region( left: float, top: float, right: float, bottom: float, *, relative: bool = True, label: Optional[str] = None,) -> 'Region'Create a child region anchored to this region.
Parameters:
- left (
float) – Left coordinate. Interpreted relative to this region whenrelativeis True. - top (
float) – Top coordinate. - right (
float) – Right coordinate. - bottom (
float) – Bottom coordinate. - relative (
bool) – When True (default), coordinates are treated as offsets from this region’s bounds. Set to False to provide absolute page coordinates. - label (
Optional[str]) – Optional label to assign to the new region.
Returns:
- (
'Region') – The newly created child region.
create_text_elements_from_ocr
Section titled “create_text_elements_from_ocr”create_text_elements_from_ocr(*args, **kwargs)Delegate to the OCR service for text element creation.
describe
Section titled “describe”describe(**kwargs)Describe the region content using the describe service.
detect_checkboxes
Section titled “detect_checkboxes”detect_checkboxes(*args, **kwargs)detect_form_cells
Section titled “detect_form_cells”detect_form_cells(*args, **kwargs)detect_lines
Section titled “detect_lines”detect_lines(*args, **kwargs)end_element (attribute)
Section titled “end_element (attribute)”end_element: Optional['Element'] = Noneendpoint (attribute)
Section titled “endpoint (attribute)”endpoint: Optional['Element']Get the boundary element that matched the ‘until’ selector.
When a region is created using directional navigation with an ‘until’
parameter (e.g., element.above(until='text[size>10]')), this property
returns the element that matched the selector and defined the boundary.
Returns:
- (
Optional['Element']) – The element that matched the ‘until’ selector, or None if no - (
Optional['Element']) – ‘until’ was specified or no match was found.
Example:
```python# Find the header above a price elementregion = price.above(until='text[size>14]')header = region.endpoint # The text element that matched<a id="natural_pdf.Region.exclude"></a>
#### `exclude`
```pythonexclude()Exclude this region from text extraction and other operations.
This excludes everything within the region’s bounds.
expand
Section titled “expand”expand( amount: Optional[float] = None, left: Union[float, bool, str] = 0, right: Union[float, bool, str] = 0, top: Union[float, bool, str] = 0, bottom: Union[float, bool, str] = 0, width_factor: float = 1.0, height_factor: float = 1.0, apply_exclusions: bool = True,) -> Union['Region', 'FlowRegion']Create a new region expanded from this element/region.
Parameters:
- amount (
Optional[float]) – If provided as the first positional argument, expand all edges by this amount - left (
Union[float, bool, str]) – Amount to expand left edge: - float: Fixed pixel expansion - True: Expand to page edge - str: Selector to expand until (excludes target by default, prefix with ’+’ to include) - right (
Union[float, bool, str]) – Amount to expand right edge (same options as left) - top (
Union[float, bool, str]) – Amount to expand top edge (same options as left) - bottom (
Union[float, bool, str]) – Amount to expand bottom edge (same options as left) - width_factor (
float) – Factor to multiply width by (applied after absolute expansion) - height_factor (
float) – Factor to multiply height by (applied after absolute expansion) - apply_exclusions (
bool) – Whether to respect exclusions when using selectors (default: True)
Returns:
- (
Union['Region', 'FlowRegion']) – New expanded Region object
Examples:
# Expand 5 pixels in all directionsexpanded = element.expand(5)
# Expand by different amounts in each directionexpanded = element.expand(left=10, right=5, top=3, bottom=7)
# Expand to page edgesexpanded = element.expand(left=True, right=True) # Full width
# Expand until specific elementsstatute = page.find('text:contains("Statute")')expanded = statute.expand(right='text:contains("Repeat?")') # Excludes "Repeat?"expanded = statute.expand(right='+text:contains("Repeat?")') # Includes "Repeat?"
# Use width/height factorsexpanded = element.expand(width_factor=1.5, height_factor=2.0)export
Section titled “export”export( path: Union[str, Path], *, resolution: Optional[float] = None, width: Optional[int] = None, layout: Literal['stack', 'grid', 'single'] = 'stack', stack_direction: Literal['vertical', 'horizontal'] = 'vertical', gap: int = 5, columns: Optional[int] = None, crop: Union[bool, Literal['content']] = False, crop_bbox: Optional[Tuple[float, float, float, float]] = None, format: Optional[str] = None, **kwargs,) -> NoneExport a clean image to file.
This is a convenience method that renders and saves in one step.
Parameters:
- path (
Union[str, Path]) – Output file path - resolution (
Optional[float]) – DPI for rendering - width (
Optional[int]) – Target width in pixels - layout (
Literal['stack', 'grid', 'single']) – How to arrange multiple pages/regions - stack_direction (
Literal['vertical', 'horizontal']) – Direction for stack layout - gap (
int) – Pixels between stacked images - columns (
Optional[int]) – Number of columns for grid layout - crop (
Union[bool, Literal['content']]) – Cropping mode (False, True, int for padding, ‘wide’, or Region) - crop_bbox (
Optional[Tuple[float, float, float, float]]) – Explicit crop bounds - format (
Optional[str]) – Image format (inferred from path if not specified) - **kwargs – Additional parameters passed to rendering
extract
Section titled “extract”extract(*args, **kwargs)Run structured extraction on this region.
Accepts the same arguments as :meth:Page.extract. Pass
citations=True for per-field source citations within this
region, confidence=True for per-field confidence scores,
and instructions="..." for domain-specific LLM guidance.
Returns:
- class:
StructuredDataResult
extract_ocr_elements
Section titled “extract_ocr_elements”extract_ocr_elements( *, engine: Optional[str] = None, options: Optional[Any] = None, languages: Optional[List[str]] = None, min_confidence: Optional[float] = None, device: Optional[str] = None, resolution: Optional[int] = None, apply_exclusions: bool = True, model: Optional[str] = None, client: Optional[Any] = None, prompt: Optional[str] = None, instructions: Optional[str] = None, max_new_tokens: Optional[int] = None, layout: Optional[bool | str] = None, preserve_markup: bool = False,) -> List[Any]Run OCR and return the resulting text elements without mutating this region.
Parameters:
- engine (
Optional[str]) – OCR engine name (defaults follow the scope configuration). - options (
Optional[Any]) – Engine-specific options payload or dataclass. - languages (
Optional[List[str]]) – Optional list of language codes. - min_confidence (
Optional[float]) – Optional minimum confidence threshold. - device (
Optional[str]) – Preferred execution device. - resolution (
Optional[int]) – Explicit render DPI; falls back to config/context when omitted. - apply_exclusions (
bool) – Mask configured exclusion zones in the crop. - model (
Optional[str]) – Optional VLM model name. - client (
Optional[Any]) – Optional OpenAI-compatible VLM client. - prompt (
Optional[str]) – Optional complete VLM prompt. - instructions (
Optional[str]) – Optional instructions appended to the VLM prompt. - max_new_tokens (
Optional[int]) – Optional VLM generation limit. - layout (
Optional[bool | str]) – Optional VLM layout mode. - preserve_markup (
bool) – Keep raw VLM markup in extracted text metadata.
Returns:
- (
List[Any]) – List of text elements created from OCR (not added to the page).
extract_structured_data
Section titled “extract_structured_data”extract_structured_data(*args, **kwargs)Alias for :meth:extract.
extract_table
Section titled “extract_table”extract_table(*args, **kwargs) -> TableResultextract_tables
Section titled “extract_tables”extract_tables(*args, **kwargs) -> 'List[TableResult]'extract_text
Section titled “extract_text”extract_text( *, layout: bool | TextLayoutOptions = False, apply_exclusions: bool = True, newlines: bool | str = True, whitespace: WhitespaceMode = 'preserve', strip: bool = True, bidi: bool = True, content_filter: ContentFilter | None = None,) -> strExtract spatial text with explicit acquisition and transform options.
layout enables spatial layout reconstruction, while
apply_exclusions controls registered exclusion regions. Newline,
whitespace, bidi, filtering, and stripping transforms are applied in a
stable order after acquisition. Regex filters remove matches; callable
filters are predicates invoked once for each Unicode codepoint.
extract_text_result
Section titled “extract_text_result”extract_text_result( *, layout: bool | TextLayoutOptions = False, apply_exclusions: bool = True,) -> ExtractedTextReturn raw spatial text and provenance using acquisition options only.
extracted
Section titled “extracted”extracted(*args, **kwargs)find( selector: Optional[str] = None, *, text: Optional[Union[str, Sequence[str]]] = None, overlap: Optional[str] = None, apply_exclusions: bool = True, regex: bool = False, case: bool = True, text_tolerance: Optional[Dict[str, Any]] = None, auto_text_tolerance: Optional[Union[bool, Dict[str, Any]]] = None, reading_order: bool = True, near_threshold: Optional[float] = None, engine: Optional[str] = None,) -> Optional['Element']Resolve a selector/text query against the host using the selector service.
find_all
Section titled “find_all”find_all( selector: Optional[str] = None, *, text: Optional[Union[str, Sequence[str]]] = None, overlap: Optional[str] = None, apply_exclusions: bool = True, regex: bool = False, case: bool = True, text_tolerance: Optional[Dict[str, Any]] = None, auto_text_tolerance: Optional[Union[bool, Dict[str, Any]]] = None, reading_order: bool = True, near_threshold: Optional[float] = None, engine: Optional[str] = None,) -> 'ElementCollection'Return every element that matches the selector/text query.
get_children
Section titled “get_children”get_children(selector=None)Get immediate child regions, optionally filtered by selector.
Parameters:
- selector – Optional selector to filter children
Returns:
- List of child regions matching the selector
Raises:
- (
SelectorParseError) – Ifselectoris malformed or unsupported. - (
SelectorMatchError) – If evaluating the selector against a child fails.
get_config
Section titled “get_config”get_config(key: str, default: Any = None, *, scope: str = 'region') -> Anyget_descendants
Section titled “get_descendants”get_descendants(selector=None)Get all descendant regions (children, grandchildren, etc.), optionally filtered by selector.
Parameters:
- selector – Optional selector to filter descendants
Returns:
- List of descendant regions matching the selector
Raises:
- (
SelectorParseError) – Ifselectoris malformed or unsupported. - (
SelectorMatchError) – If evaluating the selector against a descendant fails.
get_elements
Section titled “get_elements”get_elements( selector: Optional[str] = None, apply_exclusions=True, **kwargs,) -> List['Element']Get all elements within this region.
Parameters:
- selector (
Optional[str]) – Optional selector to filter elements - apply_exclusions – Whether to apply exclusion regions
- **kwargs – Additional parameters for element filtering
Returns:
- (
List['Element']) – List of elements in the region
get_highlighter
Section titled “get_highlighter”get_highlighter()get_rendering_service
Section titled “get_rendering_service”get_rendering_service()Public accessor for the rendering service (primarily for tests).
get_section_between
Section titled “get_section_between”get_section_between( start_element=None, end_element=None, include_boundaries='both', orientation='vertical',)Get a section between two elements within this region.
Parameters:
- start_element – Element marking the start of the section
- end_element – Element marking the end of the section
- include_boundaries – How to include boundary elements: ‘start’, ‘end’, ‘both’, or ‘none’
- orientation – ‘vertical’ (default) or ‘horizontal’ - determines section direction
Returns:
- Region representing the section
get_sections
Section titled “get_sections”get_sections( start_elements: Union[str, Sequence['Element'], 'ElementCollection', None] = None, end_elements: Union[str, Sequence['Element'], 'ElementCollection', None] = None, include_boundaries: str = 'both', orientation: str = 'vertical', **kwargs: Any,) -> 'ElementCollection[Region]'Get sections within this region based on start/end elements.
Parameters:
- start_elements (
Union[str, Sequence['Element'], 'ElementCollection', None]) – Elements or selector string that mark the start of sections - end_elements (
Union[str, Sequence['Element'], 'ElementCollection', None]) – Elements or selector string that mark the end of sections - include_boundaries (
str) – How to include boundary elements: ‘start’, ‘end’, ‘both’, or ‘none’ - orientation (
str) – ‘vertical’ (default) or ‘horizontal’ - determines section direction
Returns:
- (
'ElementCollection[Region]') – List of Region objects representing the extracted sections
get_text_table_cells
Section titled “get_text_table_cells”get_text_table_cells( snap_tolerance: int = 10, join_tolerance: int = 3, min_words_vertical: int = 3, min_words_horizontal: int = 1, intersection_tolerance: int = 3, expand_bbox: Optional[Dict[str, int]] = None, **kwargs,) -> 'ElementCollection[Region]'Analyzes text alignment to find table cells and returns them as temporary Region objects without adding them to the page.
Parameters:
- snap_tolerance (
int) – Tolerance for snapping parallel lines. - join_tolerance (
int) – Tolerance for joining collinear lines. - min_words_vertical (
int) – Minimum words needed to define a vertical line. - min_words_horizontal (
int) – Minimum words needed to define a horizontal line. - intersection_tolerance (
int) – Tolerance for detecting line intersections. - expand_bbox (
Optional[Dict[str, int]]) – Optional dictionary to expand the search area slightly beyond the region’s exact bounds (e.g., {‘left’: 5, ‘right’: 5}). - **kwargs – Additional keyword arguments passed to find_text_based_tables (e.g., specific x/y tolerances).
Returns:
- (
'ElementCollection[Region]') – An ElementCollection containing temporary Region objects for each detected cell, - (
'ElementCollection[Region]') – or an empty ElementCollection if no cells are found or an error occurs.
guides
Section titled “guides”guides(*args, **kwargs)has_polygon (attribute)
Section titled “has_polygon (attribute)”has_polygon: boolCheck if this region has polygon coordinates.
height (attribute)
Section titled “height (attribute)”height: floatGet the height of the region.
highlight
Section titled “highlight”highlight( label: Optional[str] = None, color: Optional[Union[Tuple, str]] = None, use_color_cycling: bool = False, annotate: Optional[List[str]] = None, existing: str = 'append',) -> NoneHighlight this region on the page.
Parameters:
- label (
Optional[str]) – Optional label for the highlight - color (
Optional[Union[Tuple, str]]) – Color tuple/string for the highlight, or None to use automatic color - use_color_cycling (
bool) – Force color cycling even with no label (default: False) - annotate (
Optional[List[str]]) – List of attribute names to display on the highlight (e.g., [‘confidence’, ‘type’]) - existing (
str) – How to handle existing highlights (‘append’ or ‘replace’).
Returns:
- (
None) – None
includes_source (attribute)
Section titled “includes_source (attribute)”includes_source: bool = Falseinspect
Section titled “inspect”inspect(limit: int = 30, **kwargs)Inspect the region content using the describe service.
intersects
Section titled “intersects”intersects(element) -> boolis_checked (attribute)
Section titled “is_checked (attribute)”is_checked: Optional[bool] = Noneis_element_center_inside
Section titled “is_element_center_inside”is_element_center_inside(element) -> boolis_point_inside
Section titled “is_point_inside”is_point_inside(x: float, y: float) -> boollabel (attribute)
Section titled “label (attribute)”label = labelleft( width: Optional[float] = None, height: str = 'element', include_source: bool = False, until: Optional[str] = None, include_endpoint: bool = True, offset: Optional[float] = None, apply_exclusions: bool = True, multipage: Optional[bool] = None, within: Optional['Region'] = None, anchor: str = 'start', **kwargs,) -> Optional[Union['Region', 'FlowRegion']]Select region to the left of this region.
Parameters:
- width (
Optional[float]) – Width of the region to the left, in points - height (
str) – Height mode - “full” for full page height or “element” for element height - include_source (
bool) – Whether to include this region in the result (default: False) - until (
Optional[str]) – Optional selector string to specify a left boundary element - include_endpoint (
bool) – Whether to include the boundary element in the region (default: True) - offset (
Optional[float]) – Pixel offset when excluding source/endpoint (default: None, uses natural_pdf.options.layout.directional_offset) - multipage (
Optional[bool]) – Override global multipage behaviour; defaults to None meaning use global option. - **kwargs – Additional parameters
Returns:
- (
Optional[Union['Region', 'FlowRegion']]) – Region object representing the area to the left, or None if within constraint has no overlap
metadata (attribute)
Section titled “metadata (attribute)”metadata: Dict[str, Any] = {}model (attribute)
Section titled “model (attribute)”model: Optional[str] = Nonename (attribute)
Section titled “name (attribute)”name: Optional[str] = Nonenormalized_type (attribute)
Section titled “normalized_type (attribute)”normalized_type: Optional[str] = Noneobject_type (attribute)
Section titled “object_type (attribute)”object_type: str = 'region'origin (attribute)
Section titled “origin (attribute)”origin: Optional[Union['Element', 'Region']]The element/region that created this region (if it was created via directional method).
original_class (attribute)
Section titled “original_class (attribute)”original_class: Optional[str] = Nonepage (attribute)
Section titled “page (attribute)”page: 'Page'Get the parent page.
pages (attribute)
Section titled “pages (attribute)”pagesparent
Section titled “parent”parent(selector: Optional[str] = None, *, mode: str = 'contains') -> Optional['Element']Return the smallest element/region that encloses this one.
The search is purely geometric – no pre-existing hierarchy is assumed.
Parameters
Section titled “Parameters”selector : str, optional CSS-style selector used to filter candidate containers first. mode : str, default “contains” How to decide if a candidate encloses this element.
• ``"contains"`` – candidate bbox fully contains *self* bbox.• ``"center"`` – candidate contains the centroid of *self*.• ``"overlap"`` – any bbox intersection > 0 pt².Returns
Section titled “Returns”Element | Region | None The smallest-area container that matches, or None if none found.
parent_region (attribute)
Section titled “parent_region (attribute)”parent_region: Optional['Region'] = parentpolygon (attribute)
Section titled “polygon (attribute)”polygon: List[Tuple[float, float]]Get polygon coordinates if available, otherwise return rectangle corners.
region
Section titled “region”region( left: Optional[float] = None, top: Optional[float] = None, right: Optional[float] = None, bottom: Optional[float] = None, width: Union[str, float, None] = None, height: Optional[float] = None, relative: bool = False,) -> 'Region'Create a sub-region within this region using the same API as Page.region().
By default, coordinates are absolute (relative to the page), matching Page.region(). Set relative=True to use coordinates relative to this region’s top-left corner.
Parameters:
- left (
Optional[float]) – Left x-coordinate (absolute by default, or relative to region if relative=True) - top (
Optional[float]) – Top y-coordinate (absolute by default, or relative to region if relative=True) - right (
Optional[float]) – Right x-coordinate (absolute by default, or relative to region if relative=True) - bottom (
Optional[float]) – Bottom y-coordinate (absolute by default, or relative to region if relative=True) - width (
Union[str, float, None]) – Width definition (same as Page.region()) - height (
Optional[float]) – Height of the region (same as Page.region()) - relative (
bool) – If True, coordinates are relative to this region’s top-left (0,0). If False (default), coordinates are absolute page coordinates.
Returns:
- (
'Region') – Region object for the specified coordinates, clipped to this region’s bounds
Examples:
# Absolute coordinates (default) - same as page.region()sub = region.region(left=100, top=200, width=50, height=30)
# Relative to region's top-leftsub = region.region(left=10, top=10, width=50, height=30, relative=True)
# Mix relative positioning with this region's boundssub = region.region(left=region.x0 + 10, width=50, height=30)region_type (attribute)
Section titled “region_type (attribute)”region_type: Optional[str] = Noneremove_ocr_elements
Section titled “remove_ocr_elements”remove_ocr_elements(*args, **kwargs) -> intRemove OCR text from constituent regions.
render
Section titled “render”render( *, resolution: Optional[float] = None, width: Optional[int] = None, highlights: Optional[Union[List[Dict[str, Any]], bool]] = None, labels: bool = False, label_format: Optional[str] = None, render_ocr: bool = False, layout: Literal['stack', 'grid', 'single'] = 'stack', stack_direction: Literal['vertical', 'horizontal'] = 'vertical', gap: int = 5, columns: Optional[int] = None, crop: Union[bool, int, str, 'Region', Literal['wide']] = False, crop_bbox: Optional[Tuple[float, float, float, float]] = None, **kwargs,) -> Optional[PILImage]Generate a clean image, with optional explicit highlights.
This method produces publication-ready images without any debugging annotations or persistent highlights.
Parameters:
- resolution (
Optional[float]) – DPI for rendering (default from global settings) - width (
Optional[int]) – Target width in pixels (overrides resolution) - highlights (
Optional[Union[List[Dict[str, Any]], bool]]) – Optional explicit highlight groups/specs to render - labels (
bool) – Whether to render a legend for explicit highlights - label_format (
Optional[str]) – Format string for generated highlight labels - render_ocr (
bool) – Whether to render OCR text overlay on the image - layout (
Literal['stack', 'grid', 'single']) – How to arrange multiple pages/regions - stack_direction (
Literal['vertical', 'horizontal']) – Direction for stack layout - gap (
int) – Pixels between stacked images - columns (
Optional[int]) – Number of columns for grid layout - crop (
Union[bool, int, str, 'Region', Literal['wide']]) – Cropping mode (False, True, int for padding, ‘wide’, or Region) - crop_bbox (
Optional[Tuple[float, float, float, float]]) – Explicit crop bounds - **kwargs – Additional parameters passed to rendering
Returns:
- (
Optional[PILImage]) – PIL Image object or None if nothing to render
right( width: Optional[float] = None, height: str = 'element', include_source: bool = False, until: Optional[str] = None, include_endpoint: bool = True, offset: Optional[float] = None, apply_exclusions: bool = True, multipage: Optional[bool] = None, within: Optional['Region'] = None, anchor: str = 'start', **kwargs,) -> Optional[Union['Region', 'FlowRegion']]Select region to the right of this region.
Parameters:
- width (
Optional[float]) – Width of the region to the right, in points - height (
str) – Height mode - “full” for full page height or “element” for element height - include_source (
bool) – Whether to include this region in the result (default: False) - until (
Optional[str]) – Optional selector string to specify a right boundary element - include_endpoint (
bool) – Whether to include the boundary element in the region (default: True) - offset (
Optional[float]) – Pixel offset when excluding source/endpoint (default: None, uses natural_pdf.options.layout.directional_offset) - multipage (
Optional[bool]) – Override global multipage behaviour; defaults to None meaning use global option. - **kwargs – Additional parameters
Returns:
- (
Optional[Union['Region', 'FlowRegion']]) – Region object representing the area to the right, or None if within constraint has no overlap
rotate
Section titled “rotate”rotate( angle: int = 90, direction: Literal['clockwise', 'counterclockwise'] = 'clockwise',) -> 'Region'Return a rotated view of this region as a new Region bound to a virtual page.
The rotation is applied to underlying pdfplumber objects (chars, rects, lines, images) before extraction, so text/tables are reprocessed in the new orientation. The original page/region are not mutated.
save( filename: str, resolution: Optional[float] = None, labels: bool = True, legend_position: str = 'right',) -> 'Region'Save the page with this region highlighted to an image file.
Parameters:
- filename (
str) – Path to save the image to - resolution (
Optional[float]) – Resolution in DPI for rendering (default: uses global options, fallback to 144 DPI) - labels (
bool) – Whether to include a legend for labels - legend_position (
str) – Position of the legend
Returns:
- (
'Region') – Self for method chaining
save_image
Section titled “save_image”save_image( filename: str, resolution: Optional[float] = None, crop: bool = False, include_highlights: bool = True, **kwargs,) -> 'Region'Save an image of just this region to a file.
Parameters:
- filename (
str) – Path to save the image to - resolution (
Optional[float]) – Resolution in DPI for rendering (default: uses global options, fallback to 144 DPI) - crop (
bool) – If True, only crop the region without highlighting its boundaries - include_highlights (
bool) – Whether to include existing highlights (default: True) - **kwargs – Additional parameters for rendering
Returns:
- (
'Region') – Self for method chaining
save_pdf
Section titled “save_pdf”save_pdf(path: str, method: str = 'crop') -> 'Region'Save this region as a PDF file. The region becomes a single page in the output.
Uses pikepdf to manipulate the original vector PDF, preserving selectable text.
Parameters:
- path (
str) – Output file path for the PDF. - method (
str) – ‘crop’ (default) sets CropBox to region bounds, producing a page sized to the region. ‘whiteout’ keeps the full page but draws white rectangles over areas outside the region.
Returns:
- (
'Region') – Self for method chaining.
Raises:
- (
ImportError) – If pikepdf is not installed. - (
ValueError) – If method is not ‘crop’ or ‘whiteout’.
Examples:
```pythonregion = page.find('text:bold').below()region.save_pdf("output.pdf")region.save_pdf("whiteout.pdf", method="whiteout")<a id="natural_pdf.Region.selector_flow"></a>
#### `selector_flow`
```pythonselector_flow() -> Anyselector_page
Section titled “selector_page”selector_page() -> Anyselector_region
Section titled “selector_region”selector_region() -> Anyservices (attribute)
Section titled “services (attribute)”services: ServiceNamespaceshow( *, resolution: Optional[float] = None, width: Optional[int] = None, color: Optional[Union[str, Tuple[int, int, int]]] = None, labels: bool = True, label_format: Optional[str] = None, highlights: Optional[Union[List[Dict[str, Any]], bool]] = None, legend_position: str = 'right', annotate: Optional[Union[str, List[str]]] = None, render_ocr: bool = False, layout: Optional[Literal['stack', 'grid', 'single']] = None, stack_direction: Literal['vertical', 'horizontal'] = 'vertical', gap: int = 5, columns: Optional[int] = 6, limit: Optional[int] = 30, crop: Union[bool, int, str, 'Region', Literal['wide']] = False, crop_bbox: Optional[Tuple[float, float, float, float]] = None, **kwargs,) -> Optional[PILImage]Generate a preview image with highlights.
This method is for interactive debugging and visualization. Elements are highlighted to show what’s selected or being worked with.
Parameters:
- resolution (
Optional[float]) – DPI for rendering (default from global settings) - width (
Optional[int]) – Target width in pixels (overrides resolution) - color (
Optional[Union[str, Tuple[int, int, int]]]) – Default highlight color - labels (
bool) – Whether to show labels for highlights - label_format (
Optional[str]) – Format string for labels (e.g., “Element {index}”) - highlights (
Optional[Union[List[Dict[str, Any]], bool]]) – Additional highlight groups to show, or False to disable all highlights - legend_position (
str) – Position of legend/colorbar (‘right’, ‘left’, ‘top’, ‘bottom’) - annotate (
Optional[Union[str, List[str]]]) – Attribute name(s) to display on highlights (string or list) - render_ocr (
bool) – Whether to render OCR text overlay on the image - layout (
Optional[Literal['stack', 'grid', 'single']]) – How to arrange multiple pages/regions (defaults to ‘grid’ for multi-page, ‘single’ for single page) - stack_direction (
Literal['vertical', 'horizontal']) – Direction for stack layout - gap (
int) – Pixels between stacked images - columns (
Optional[int]) – Number of columns for grid layout (defaults to 6) - limit (
Optional[int]) – Maximum number of pages to display (default 30, None for all) - crop (
Union[bool, int, str, 'Region', Literal['wide']]) – Cropping mode: - False: No cropping (default) - True: Tight crop to element bounds - int: Padding in PDF points around element (crop bounds are computed in PDF coordinate space, then scaled by resolution) - ‘wide’: Full page width, cropped vertically to element - Region: Crop to the bounds of another region - crop_bbox (
Optional[Tuple[float, float, float, float]]) – Explicit crop bounds - **kwargs – Additional parameters passed to rendering
Returns:
- (
Optional[PILImage]) – PIL Image object or None if nothing to render
source (attribute)
Section titled “source (attribute)”source: Optional[str] = Nonesource_element (attribute)
Section titled “source_element (attribute)”source_element: Optional[Union['Element', 'Region']] = Nonesplit(divider, **kwargs) -> 'ElementCollection[Region]'Divide this region into sections based on the provided divider elements.
Parameters:
- divider – Elements or selector string that mark section boundaries
- **kwargs – Additional parameters passed to get_sections() - include_boundaries: How to include boundary elements (default: ‘start’) - orientation: ‘vertical’ or ‘horizontal’ (default: ‘vertical’)
Returns:
- (
'ElementCollection[Region]') – ElementCollection of Region objects representing the sections
Example:
# Split a region by bold textsections = region.split("text:bold")
# Split horizontally by vertical linessections = region.split("line[orientation=vertical]", orientation="horizontal")start_element (attribute)
Section titled “start_element (attribute)”start_element: Optional['Element'] = Nonetext (attribute)
Section titled “text (attribute)”text: strGet text content of this region (delegates to extract_text()).
text_content (attribute)
Section titled “text_content (attribute)”text_content: Optional[str] = Noneto_llm
Section titled “to_llm”to_llm(**kwargs) -> strReturn an LLM-optimized text representation of this region.
to_region
Section titled “to_region”to_region() -> 'Region'Regions already satisfy the section surface; return self.
to_text_element
Section titled “to_text_element”to_text_element( text_content: Optional[Union[str, Callable[['Region'], Optional[str]]]] = None, source_label: str = 'derived_from_region', object_type: str = 'word', default_font_size: float = 10.0, default_font_name: str = 'RegionContent', confidence: Optional[float] = None, add_to_page: bool = False,) -> 'TextElement'Creates a new TextElement object based on this region’s geometry.
The text for the new TextElement can be provided directly, generated by a callback function, or left as None.
Parameters:
- text_content (
Optional[Union[str, Callable[['Region'], Optional[str]]]]) – - If a string, this will be the text of the new TextElement. - If a callable, it will be called with this region instance and its return value (a string or None) will be the text. - If None (default), the TextElement’s text will be None. - source_label (
str) – The ‘source’ attribute for the new TextElement. - object_type (
str) – The ‘object_type’ for the TextElement’s data dict (e.g., “word”, “char”). - default_font_size (
float) – Placeholder font size if text is generated. - default_font_name (
str) – Placeholder font name if text is generated. - confidence (
Optional[float]) – Confidence score for the text. If text_content is None, defaults to 0.0. If text is provided/generated, defaults to 1.0 unless specified. - add_to_page (
bool) – If True, the created TextElement will be added to the region’s parent page. (Default: False)
Returns:
- (
'TextElement') – A new TextElement instance.
Raises:
- (
ValueError) – If the region does not have a valid ‘page’ attribute.
top (attribute)
Section titled “top (attribute)”top: floatGet the top coordinate.
trim( padding: float = 1, threshold: float = 0.95, resolution: Optional[float] = None, pre_shrink: float = 0.5, method: Literal['auto', 'elements', 'any', 'average'] = 'any',) -> 'Region'Trim whitespace from the edges of this region.
Similar to Python’s string .strip() method. Stops at ANY non-white pixel by default.
Parameters:
- padding (
float) – Padding to keep around content in PDF points (default: 1) - threshold (
float) – For pixel methods, threshold for whitespace detection (0.0-1.0, default: 0.95) - resolution (
Optional[float]) – Resolution for pixel-based methods in DPI (default: 144) - pre_shrink (
float) – For pixel methods, shrink before trim to avoid border artifacts (default: 0.5) - method (
Literal['auto', 'elements', 'any', 'average']) – Trimming strategy: - ‘any’ (default): Pixel-based, stop at ANY non-white pixel (like string.strip()) - ‘auto’: Use ‘elements’ if available, fall back to ‘any’ - ‘elements’: Use bounding boxes of text/elements (best for digital PDFs) - ‘average’: Pixel-based, use row/column averages (for noisy scans)
Returns:
- (
'Region') – New Region with whitespace trimmed from all edges
Examples:
```python# Default: stop at any content pixel (like string.strip())trimmed = region.trim()
# Use element bounding boxes (faster, but may include empty elements)trimmed = region.trim(method='elements')
# For noisy scanned documentstrimmed = region.trim(method='average', threshold=0.9)<a id="natural_pdf.Region.type"></a>
#### `type` *(attribute)*
```pythontype: strElement type.
update_ocr
Section titled “update_ocr”update_ocr(*args, **kwargs)update_text
Section titled “update_text”update_text(*args, **kwargs)viewer
Section titled “viewer”viewer( *, resolution: int = 150, include_chars: bool = False, include_attributes: Optional[List[str]] = None,) -> Optional[Any]Create an interactive ipywidget viewer for this specific region.
The method renders the region to an image (cropped to the region bounds) and
overlays all elements that intersect the region (optionally excluding noisy
character-level elements). The resulting widget offers the same zoom / pan
experience as :py:meth:Page.viewer but scoped to the region.
Parameters
Section titled “Parameters”resolution : int, default 150 Rendering resolution (DPI). This should match the value used by the page-level viewer so element scaling is accurate. include_chars : bool, default False Whether to include individual char elements in the overlay. These are often too dense for a meaningful visualisation so are skipped by default. include_attributes : list[str], optional Additional element attributes to expose in the info panel (on top of the default set used by the page viewer).
Returns
Section titled “Returns”InteractiveViewerWidget The widget instance.
width (attribute)
Section titled “width (attribute)”width: floatGet the width of the region.
within
Section titled “within”within()Context manager that constrains directional operations to this region.
When used as a context manager, all directional navigation operations (above, below, left, right) in the current thread/task will be constrained to the bounds of this region. Nested contexts restore their outer constraint even if the inner block raises an exception.
Returns:
- RegionContext – A context manager that yields this region
Examples:
```python# Create a column regionleft_col = page.region(right=page.width/2)
# All directional operations are constrained to left_colwith left_col.within() as col: header = col.find("text[size>14]") content = header.below(until="text[size>14]") # content will only include elements within left_col
# Operations outside the context are not constrainedfull_page_below = header.below() # Searches full page<a id="natural_pdf.Region.x0"></a>
#### `x0` *(attribute)*
```pythonx0: floatGet the left coordinate.
x1 (attribute)
Section titled “x1 (attribute)”x1: floatGet the right coordinate.
Bases: AggregateTextMixin, OCRScopeMixin, ServiceHostMixin, Visualizable, SelectorHostMixin
Flow( segments: Union[Sequence[SupportsSections], PageCollection], arrangement: Literal['vertical', 'horizontal'], alignment: Literal['start', 'center', 'end', 'top', 'left', 'bottom', 'right'] = 'start', segment_gap: float = 0.0,)Defines a logical flow or sequence of physical Page or Region objects.
A Flow represents a continuous logical document structure that spans across multiple pages or regions, enabling operations on content that flows across boundaries. This is essential for handling multi-page tables, articles that span columns, or any content that requires reading order across segments.
Flows specify arrangement (vertical/horizontal) and alignment rules to create a unified coordinate system for element extraction and text processing. They enable natural-pdf to treat fragmented content as a single continuous area for analysis and extraction operations.
The Flow system is particularly useful for:
- Multi-page tables that break across page boundaries
- Multi-column articles with complex reading order
- Forms that span multiple pages
- Any content requiring logical continuation across segments
Attributes:
- segments (
List[PhysicalRegion]) – List of Page or Region objects in flow order. - arrangement (
Literal['vertical', 'horizontal']) – Primary flow direction (‘vertical’ or ‘horizontal’). - alignment (
Literal['start', 'center', 'end', 'top', 'left', 'bottom', 'right']) – Cross-axis alignment for segments of different sizes. - segment_gap (
float) – Virtual gap between segments in PDF points.
Example:
Multi-page table flow:```pythonpdf = npdf.PDF("multi_page_table.pdf")
# Create flow for table spanning pages 2-4table_flow = Flow( segments=[pdf.pages[1], pdf.pages[2], pdf.pages[3]], arrangement='vertical', alignment='left', segment_gap=10.0)
# Extract table as if it were continuoustable_data = table_flow.extract_table()text_content = table_flow.extract_text()Multi-column article flow:
page = pdf.pages[0]left_column = page.region(0, 0, 300, page.height)right_column = page.region(320, 0, page.width, page.height)
# Create horizontal flow for columnsarticle_flow = Flow( segments=[left_column, right_column], arrangement='horizontal', alignment='top')
# Read in proper orderarticle_text = article_flow.extract_text()> **Note:**> Flows create virtual coordinate systems that map element positions across> segments, enabling spatial navigation and element selection to work> seamlessly across boundaries.
Initializes a Flow object.
**Parameters:**
- **segments** (`Union[Sequence[SupportsSections], PageCollection]`) – An ordered sequence of objects implementing SupportsSections (e.g., Page, Region) that constitute the flow, or a PageCollection containing pages.- **arrangement** (`Literal['vertical', 'horizontal']`) – The primary direction of the flow. - "vertical": Segments are stacked top-to-bottom. - "horizontal": Segments are arranged left-to-right.- **alignment** (`Literal['start', 'center', 'end', 'top', 'left', 'bottom', 'right']`) – How segments are aligned on their cross-axis if they have differing dimensions. For a "vertical" arrangement: - "left" (or "start"): Align left edges. - "center": Align centers. - "right" (or "end"): Align right edges. For a "horizontal" arrangement: - "top" (or "start"): Align top edges. - "center": Align centers. - "bottom" (or "end"): Align bottom edges.- **segment_gap** (`float`) – The virtual gap (in PDF points) between segments.
<a id="natural_pdf.Flow.alignment"></a>
#### `alignment` *(attribute)*
```pythonalignment: Literal['start', 'center', 'end', 'top', 'left', 'bottom', 'right'] = ...analyze_layout
Section titled “analyze_layout”analyze_layout(*args, **kwargs)apply_ocr
Section titled “apply_ocr”apply_ocr( engine: Optional[str] = None, *, options: Optional[Any] = None, languages: Optional[list[str]] = None, min_confidence: Optional[float] = None, device: Optional[str] = None, resolution: Optional[int] = None, detect_only: bool = False, apply_exclusions: bool = True, replace: OCRReplaceMode = 'ocr', use_cache: bool = True, model: Optional[str] = None, client: Optional[Any] = None, prompt: Optional[str] = None, instructions: Optional[str] = None, max_new_tokens: Optional[int] = None, layout: Optional[bool | str] = None, preserve_markup: bool = False, function: Optional[CustomOCRCallable] = None, source_label: str = 'custom-ocr', confidence: Optional[float] = None,) -> SelfApply OCR within this object’s spatial scope and return self.
This method has three validated modes:
- recognition (the default) recognizes text with a registered engine;
detect_only=Truerefreshes persistent text bounding boxes without deleting native or recognized text;function=recognizes text with a callable receiving each physical Region in the scope.
Parameters:
- engine (
Optional[str]) – Registered OCR engine name. When omitted, resolve the context default. Supplyingmodelorclientselects VLM OCR when no engine is named. - options (
Optional[Any]) – Typed engine-specific options object or validated mapping. - languages (
Optional[list[str]]) – Ordered language codes such as["en", "fr"]. - min_confidence (
Optional[float]) – Minimum accepted confidence between 0 and 1. - device (
Optional[str]) – Requested compute device, such as"cpu"or"cuda". - resolution (
Optional[int]) – Render resolution in DPI. - detect_only (
bool) – Refresh detection-only spatial artifacts instead of recognizing text. Detection preserves existing text. - apply_exclusions (
bool) – Mask configured exclusions in pixels sent to OCR. - replace (
OCRReplaceMode) – Recognition/function replacement policy:"ocr","all", or"none". Detection has its own refresh policy. - use_cache (
bool) – Allow the persistent OCR result cache when its identity can be proven safe. - model (
Optional[str]) – VLM model name. - client (
Optional[Any]) – OpenAI-compatible VLM client. - prompt (
Optional[str]) – Complete VLM prompt overriding the generated prompt. - instructions (
Optional[str]) – Additional VLM instructions. - max_new_tokens (
Optional[int]) – VLM generation limit. - layout (
Optional[bool | str]) – VLM layout mode (bool or registered detector name). - preserve_markup (
bool) – Preserve raw VLM markup in text metadata. - function (
Optional[CustomOCRCallable]) – Custom callable receiving a physical Region and returning recognized text orNone. It cannot be combined with engine, VLM, cache, exclusion, or detection controls. - source_label (
str) – Provenance label stored asocr_engineon custom-function output. Its selector-visible source remains"ocr"like every other OCR artifact. - confidence (
Optional[float]) – Confidence assigned to custom-function OCR text.
Returns:
- (
Self) – The receiving object for fluent chaining.
Raises:
- (
TypeError) – An argument has the wrong type orfunctionis not callable. - (
ValueError) – Mode-specific arguments conflict or a value is invalid.
arrangement (attribute)
Section titled “arrangement (attribute)”arrangement: Literal['vertical', 'horizontal'] = arrangementask(*args, **kwargs)clear_text_layer
Section titled “clear_text_layer”clear_text_layer() -> Tuple[int, int]Clear the underlying text layers (words/chars) for every segment page.
create_text_elements_from_ocr
Section titled “create_text_elements_from_ocr”create_text_elements_from_ocr( ocr_results: Any, scale_x: Optional[float] = None, scale_y: Optional[float] = None, *, offset_x: float = 0.0, offset_y: float = 0.0,) -> List[Any]Utility for constructing text elements from OCR output.
detect_layout (attribute)
Section titled “detect_layout (attribute)”detect_layout = analyze_layoutexport
Section titled “export”export( path: Union[str, Path], *, resolution: Optional[float] = None, width: Optional[int] = None, layout: Literal['stack', 'grid', 'single'] = 'stack', stack_direction: Literal['vertical', 'horizontal'] = 'vertical', gap: int = 5, columns: Optional[int] = None, crop: Union[bool, Literal['content']] = False, crop_bbox: Optional[Tuple[float, float, float, float]] = None, format: Optional[str] = None, **kwargs,) -> NoneExport a clean image to file.
This is a convenience method that renders and saves in one step.
Parameters:
- path (
Union[str, Path]) – Output file path - resolution (
Optional[float]) – DPI for rendering - width (
Optional[int]) – Target width in pixels - layout (
Literal['stack', 'grid', 'single']) – How to arrange multiple pages/regions - stack_direction (
Literal['vertical', 'horizontal']) – Direction for stack layout - gap (
int) – Pixels between stacked images - columns (
Optional[int]) – Number of columns for grid layout - crop (
Union[bool, Literal['content']]) – Cropping mode (False, True, int for padding, ‘wide’, or Region) - crop_bbox (
Optional[Tuple[float, float, float, float]]) – Explicit crop bounds - format (
Optional[str]) – Image format (inferred from path if not specified) - **kwargs – Additional parameters passed to rendering
extract_ocr_elements
Section titled “extract_ocr_elements”extract_ocr_elements(*args: Any, **kwargs: Any) -> List[Any]Extract OCR-derived text elements from all segments.
extract_table
Section titled “extract_table”extract_table(*args, **kwargs) -> TableResultExtract table from the flow, delegating to the analysis region.
extract_tables
Section titled “extract_tables”extract_tables(*args, **kwargs) -> List[TableResult]Extract tables from the flow, delegating to the analysis region.
extract_text
Section titled “extract_text”extract_text( *, separator: str | None = None, layout: bool | TextLayoutOptions = False, apply_exclusions: bool = True, newlines: bool | str = True, whitespace: WhitespaceMode = 'preserve', strip: bool = True, bidi: bool = True, content_filter: ContentFilter | None = None,) -> strExtract members independently, then join them at exact host boundaries.
separator=None uses the host’s natural separator. Empty member
handling is host policy. Transforms run on members only: separators are
never normalized, stripped, bidi-processed, or included in a regex match.
extract_text_result
Section titled “extract_text_result”extract_text_result( *, separator: str | None = None, layout: bool | TextLayoutOptions = False, apply_exclusions: bool = True,) -> ExtractedTextJoin raw member results with exact source offsets.
find( selector: Optional[str] = None, *, text: Optional[Union[str, Sequence[str]]] = None, overlap: Optional[str] = None, apply_exclusions: bool = True, regex: bool = False, case: bool = True, text_tolerance: Optional[Dict[str, Any]] = None, auto_text_tolerance: Optional[Union[bool, Dict[str, Any]]] = None, reading_order: bool = True, near_threshold: Optional[float] = None, engine: Optional[str] = None,) -> Optional['Element']Resolve a selector/text query against the host using the selector service.
find_all
Section titled “find_all”find_all( selector: Optional[str] = None, *, text: Optional[Union[str, Sequence[str]]] = None, overlap: Optional[str] = None, apply_exclusions: bool = True, regex: bool = False, case: bool = True, text_tolerance: Optional[Dict[str, Any]] = None, auto_text_tolerance: Optional[Union[bool, Dict[str, Any]]] = None, reading_order: bool = True, near_threshold: Optional[float] = None, engine: Optional[str] = None,) -> 'ElementCollection'Return every element that matches the selector/text query.
get_rendering_service
Section titled “get_rendering_service”get_rendering_service()Public accessor for the rendering service (primarily for tests).
get_sections
Section titled “get_sections”get_sections( start_elements=None, end_elements=None, new_section_on_page_break: bool = False, include_boundaries: str = 'both', orientation: str = 'vertical',) -> PhysicalElementCollectionExtract logical sections from the Flow based on start and end boundary elements, mirroring the behaviour of PDF/PageCollection.get_sections().
This implementation is a thin wrapper that converts the Flow into a temporary PageCollection (constructed from the unique pages that the Flow spans) and then delegates the heavy‐lifting to that existing implementation. Any FlowElement / FlowElementCollection inputs are automatically unwrapped to their underlying physical elements so that PageCollection can work with them directly.
Parameters:
- start_elements – Elements or selector string that mark the start of sections (optional).
- end_elements – Elements or selector string that mark the end of sections (optional).
- new_section_on_page_break (
bool) – Whether to start a new section at page boundaries (default: False). - include_boundaries (
str) – How to include boundary elements: ‘start’, ‘end’, ‘both’, or ‘none’ (default: ‘both’). - orientation (
str) – ‘vertical’ (default) or ‘horizontal’ - determines section direction.
Returns:
- (
PhysicalElementCollection) – ElementCollection of Region/FlowRegion objects representing the - (
PhysicalElementCollection) – extracted sections.
highlight
Section titled “highlight”highlight(*elements, **kwargs)Convenience method for highlighting elements in Jupyter/Colab.
This method creates a highlight context, adds the elements, and returns the resulting image. It’s designed for simple one-liner usage in notebooks.
Parameters:
- *elements – Elements or element collections to highlight
- **kwargs – Additional parameters passed to show()
Returns:
- PIL Image with highlights
Example:
# Simple one-liner highlightingpage.highlight(left, mid, right)
# With custom colorspage.highlight( (tables, 'blue'), (headers, 'red'), (footers, 'green'))highlights
Section titled “highlights”highlights(show: bool = False)Create a highlight context for accumulating highlights.
This allows for clean syntax to show multiple highlight groups:
Example:
with flow.highlights() as h: h.add(flow.find_all('table'), label='tables', color='blue') h.add(flow.find_all('text:bold'), label='bold text', color='red') h.show()Or With Automatic Display: with flow.highlights(show=True) as h: h.add(flow.find_all(‘table’), label=‘tables’) h.add(flow.find_all(‘text:bold’), label=‘bold’) # Automatically shows when exiting the context
Parameters:
- show (
bool) – If True, automatically show highlights when exiting context
Returns:
- HighlightContext for accumulating highlights
remove_ocr_elements
Section titled “remove_ocr_elements”remove_ocr_elements() -> intRemove OCR elements that were previously added to constituent pages.
render
Section titled “render”render( *, resolution: Optional[float] = None, width: Optional[int] = None, highlights: Optional[Union[List[Dict[str, Any]], bool]] = None, labels: bool = False, label_format: Optional[str] = None, render_ocr: bool = False, layout: Literal['stack', 'grid', 'single'] = 'stack', stack_direction: Literal['vertical', 'horizontal'] = 'vertical', gap: int = 5, columns: Optional[int] = None, crop: Union[bool, int, str, 'Region', Literal['wide']] = False, crop_bbox: Optional[Tuple[float, float, float, float]] = None, **kwargs,) -> Optional[PILImage]Generate a clean image, with optional explicit highlights.
This method produces publication-ready images without any debugging annotations or persistent highlights.
Parameters:
- resolution (
Optional[float]) – DPI for rendering (default from global settings) - width (
Optional[int]) – Target width in pixels (overrides resolution) - highlights (
Optional[Union[List[Dict[str, Any]], bool]]) – Optional explicit highlight groups/specs to render - labels (
bool) – Whether to render a legend for explicit highlights - label_format (
Optional[str]) – Format string for generated highlight labels - render_ocr (
bool) – Whether to render OCR text overlay on the image - layout (
Literal['stack', 'grid', 'single']) – How to arrange multiple pages/regions - stack_direction (
Literal['vertical', 'horizontal']) – Direction for stack layout - gap (
int) – Pixels between stacked images - columns (
Optional[int]) – Number of columns for grid layout - crop (
Union[bool, int, str, 'Region', Literal['wide']]) – Cropping mode (False, True, int for padding, ‘wide’, or Region) - crop_bbox (
Optional[Tuple[float, float, float, float]]) – Explicit crop bounds - **kwargs – Additional parameters passed to rendering
Returns:
- (
Optional[PILImage]) – PIL Image object or None if nothing to render
segment_gap (attribute)
Section titled “segment_gap (attribute)”segment_gap: float = segment_gapsegments (attribute)
Section titled “segments (attribute)”segments: List[PhysicalRegion] = self._normalize_segments(segment_list)selector_flow
Section titled “selector_flow”selector_flow() -> Anyselector_page
Section titled “selector_page”selector_page() -> Anyselector_region
Section titled “selector_region”selector_region() -> Anyservices (attribute)
Section titled “services (attribute)”services: ServiceNamespaceshow( *, resolution: Optional[float] = None, width: Optional[int] = None, color: Optional[Union[str, Tuple[int, int, int]]] = None, labels: bool = True, label_format: Optional[str] = None, highlights: Optional[Union[List[Dict[str, Any]], bool]] = None, legend_position: str = 'right', annotate: Optional[Union[str, List[str]]] = None, layout: Optional[Literal['stack', 'grid', 'single']] = None, stack_direction: Optional[Literal['vertical', 'horizontal']] = None, gap: int = 5, columns: Optional[int] = 6, crop: Union[bool, int, str, PhysicalRegion, Literal['wide']] = False, crop_bbox: Optional[Tuple[float, float, float, float]] = None, in_context: Optional[bool] = None, separator_color: Optional[Tuple[int, int, int]] = None, separator_thickness: int = 2, **kwargs,) -> Optional[PIL_Image]Generate a preview image with highlights.
By default, Flow.show stacks multiple segments in the order of the flow arrangement so you can see them as a single continuous surface. Set in_context=False to revert to the traditional page-highlighting behavior. You can also pass in_context=True explicitly to force the stacked visualization.
Parameters:
- resolution (
Optional[float]) – DPI for rendering (default from global settings) - width (
Optional[int]) – Target width in pixels (overrides resolution) - color (
Optional[Union[str, Tuple[int, int, int]]]) – Default highlight color - labels (
bool) – Whether to show labels for highlights - label_format (
Optional[str]) – Format string for labels - highlights (
Optional[Union[List[Dict[str, Any]], bool]]) – Additional highlight groups to show - layout (
Optional[Literal['stack', 'grid', 'single']]) – How to arrange multiple pages/regions - stack_direction (
Optional[Literal['vertical', 'horizontal']]) – Direction for stack layout - gap (
int) – Pixels between stacked images - columns (
Optional[int]) – Number of columns for grid layout - crop (
Union[bool, int, str, PhysicalRegion, Literal['wide']]) – Whether to crop - crop_bbox (
Optional[Tuple[float, float, float, float]]) – Explicit crop bounds - in_context (
Optional[bool]) – If True, use special Flow visualization with separators - separator_color (
Optional[Tuple[int, int, int]]) – RGB color for separator lines (default: red) - separator_thickness (
int) – Thickness of separator lines - **kwargs – Additional parameters passed to rendering
Returns:
- (
Optional[PIL_Image]) – PIL Image object or None if nothing to render
FlowRegion
Section titled “FlowRegion”Bases: AggregateTextMixin, OCRScopeMixin, SelectorHostMixin, ServiceHostMixin, SupportsSections, Visualizable, MultiRegionAnalysisMixin, ContextResolverMixin
FlowRegion( flow: 'Flow', constituent_regions: List['PhysicalRegion'], source_flow_element: Optional['FlowElement'] = None, boundary_element_found: Optional[Union['PhysicalElement', 'PhysicalRegion']] = None,)Represents a selected area within a Flow, potentially composed of multiple physical Region objects (constituent_regions) that might span across different original pages or disjoint physical regions defined in the Flow.
A FlowRegion is the result of a directional operation (e.g., .below(), .above()) on a FlowElement.
Initializes a FlowRegion.
Parameters:
- flow (
'Flow') – The Flow instance this region belongs to. - constituent_regions (
List['PhysicalRegion']) – A list of physical natural_pdf.elements.region.Region objects that make up this FlowRegion. - source_flow_element (
Optional['FlowElement']) – The FlowElement that created this FlowRegion. - boundary_element_found (
Optional[Union['PhysicalElement', 'PhysicalRegion']]) – The physical element that stopped an ‘until’ search, if applicable.
above(*args, **kwargs)add_exclusion
Section titled “add_exclusion”add_exclusion(*args, **kwargs)apply_ocr
Section titled “apply_ocr”apply_ocr( engine: Optional[str] = None, *, options: Optional[Any] = None, languages: Optional[list[str]] = None, min_confidence: Optional[float] = None, device: Optional[str] = None, resolution: Optional[int] = None, detect_only: bool = False, apply_exclusions: bool = True, replace: OCRReplaceMode = 'ocr', use_cache: bool = True, model: Optional[str] = None, client: Optional[Any] = None, prompt: Optional[str] = None, instructions: Optional[str] = None, max_new_tokens: Optional[int] = None, layout: Optional[bool | str] = None, preserve_markup: bool = False, function: Optional[CustomOCRCallable] = None, source_label: str = 'custom-ocr', confidence: Optional[float] = None,) -> SelfApply OCR within this object’s spatial scope and return self.
This method has three validated modes:
- recognition (the default) recognizes text with a registered engine;
detect_only=Truerefreshes persistent text bounding boxes without deleting native or recognized text;function=recognizes text with a callable receiving each physical Region in the scope.
Parameters:
- engine (
Optional[str]) – Registered OCR engine name. When omitted, resolve the context default. Supplyingmodelorclientselects VLM OCR when no engine is named. - options (
Optional[Any]) – Typed engine-specific options object or validated mapping. - languages (
Optional[list[str]]) – Ordered language codes such as["en", "fr"]. - min_confidence (
Optional[float]) – Minimum accepted confidence between 0 and 1. - device (
Optional[str]) – Requested compute device, such as"cpu"or"cuda". - resolution (
Optional[int]) – Render resolution in DPI. - detect_only (
bool) – Refresh detection-only spatial artifacts instead of recognizing text. Detection preserves existing text. - apply_exclusions (
bool) – Mask configured exclusions in pixels sent to OCR. - replace (
OCRReplaceMode) – Recognition/function replacement policy:"ocr","all", or"none". Detection has its own refresh policy. - use_cache (
bool) – Allow the persistent OCR result cache when its identity can be proven safe. - model (
Optional[str]) – VLM model name. - client (
Optional[Any]) – OpenAI-compatible VLM client. - prompt (
Optional[str]) – Complete VLM prompt overriding the generated prompt. - instructions (
Optional[str]) – Additional VLM instructions. - max_new_tokens (
Optional[int]) – VLM generation limit. - layout (
Optional[bool | str]) – VLM layout mode (bool or registered detector name). - preserve_markup (
bool) – Preserve raw VLM markup in text metadata. - function (
Optional[CustomOCRCallable]) – Custom callable receiving a physical Region and returning recognized text orNone. It cannot be combined with engine, VLM, cache, exclusion, or detection controls. - source_label (
str) – Provenance label stored asocr_engineon custom-function output. Its selector-visible source remains"ocr"like every other OCR artifact. - confidence (
Optional[float]) – Confidence assigned to custom-function OCR text.
Returns:
- (
Self) – The receiving object for fluent chaining.
Raises:
- (
TypeError) – An argument has the wrong type orfunctionis not callable. - (
ValueError) – Mode-specific arguments conflict or a value is invalid.
ask(*args, **kwargs)bbox (attribute)
Section titled “bbox (attribute)”bbox: Optional[Tuple[float, float, float, float]]The bounding box that encloses all constituent regions.
For single-page FlowRegions this is a true geometric union. For
multi-page FlowRegions the result is a merge_bboxes over all
constituent regions regardless of page — useful for sorting and
size estimates, but not a physically meaningful rectangle.
Returns None only when there are no constituent regions.
below(*args, **kwargs)bottom (attribute)
Section titled “bottom (attribute)”bottom: floatboundary_element_found (attribute)
Section titled “boundary_element_found (attribute)”boundary_element_found: Optional[Union['PhysicalElement', 'PhysicalRegion']] = ...clear_text_layer
Section titled “clear_text_layer”clear_text_layer() -> Tuple[int, int]constituent_regions (attribute)
Section titled “constituent_regions (attribute)”constituent_regions: List['PhysicalRegion'] = constituent_regionscontains
Section titled “contains”contains(element) -> boolcreate_text_elements_from_ocr
Section titled “create_text_elements_from_ocr”create_text_elements_from_ocr( ocr_results: Any, scale_x: Optional[float] = None, scale_y: Optional[float] = None, *, offset_x: float = 0.0, offset_y: float = 0.0,) -> List[Any]elements
Section titled “elements”elements(apply_exclusions: bool = True) -> 'ElementCollection'Collects all unique physical elements from all constituent physical regions.
Parameters:
- apply_exclusions (
bool) – Whether to respect PDF exclusion zones within each constituent physical region when gathering elements.
Returns:
- (
'ElementCollection') – An ElementCollection containing all unique elements.
end_element (attribute)
Section titled “end_element (attribute)”end_element: Optional[Union['PhysicalElement', 'PhysicalRegion']] = Noneexpand
Section titled “expand”expand( amount: Optional[float] = None, *, left: Union[float, bool, str] = 0, right: Union[float, bool, str] = 0, top: Union[float, bool, str] = 0, bottom: Union[float, bool, str] = 0, width_factor: float = 1.0, height_factor: float = 1.0, apply_exclusions: bool = True,) -> 'FlowRegion'Create a new FlowRegion with all constituent regions expanded.
Parameters:
- left (
Union[float, bool, str]) – Amount to expand left edge (positive value expands leftwards) - right (
Union[float, bool, str]) – Amount to expand right edge (positive value expands rightwards) - top (
Union[float, bool, str]) – Amount to expand top edge (positive value expands upwards) - bottom (
Union[float, bool, str]) – Amount to expand bottom edge (positive value expands downwards) - width_factor (
float) – Factor to multiply width by (applied after absolute expansion) - height_factor (
float) – Factor to multiply height by (applied after absolute expansion)
Returns:
- (
'FlowRegion') – New FlowRegion with expanded constituent regions
export
Section titled “export”export( path: Union[str, Path], *, resolution: Optional[float] = None, width: Optional[int] = None, layout: Literal['stack', 'grid', 'single'] = 'stack', stack_direction: Literal['vertical', 'horizontal'] = 'vertical', gap: int = 5, columns: Optional[int] = None, crop: Union[bool, Literal['content']] = False, crop_bbox: Optional[Tuple[float, float, float, float]] = None, format: Optional[str] = None, **kwargs,) -> NoneExport a clean image to file.
This is a convenience method that renders and saves in one step.
Parameters:
- path (
Union[str, Path]) – Output file path - resolution (
Optional[float]) – DPI for rendering - width (
Optional[int]) – Target width in pixels - layout (
Literal['stack', 'grid', 'single']) – How to arrange multiple pages/regions - stack_direction (
Literal['vertical', 'horizontal']) – Direction for stack layout - gap (
int) – Pixels between stacked images - columns (
Optional[int]) – Number of columns for grid layout - crop (
Union[bool, Literal['content']]) – Cropping mode (False, True, int for padding, ‘wide’, or Region) - crop_bbox (
Optional[Tuple[float, float, float, float]]) – Explicit crop bounds - format (
Optional[str]) – Image format (inferred from path if not specified) - **kwargs – Additional parameters passed to rendering
extract_ocr_elements
Section titled “extract_ocr_elements”extract_ocr_elements(*args: Any, **kwargs: Any) -> List[Any]Extract OCR elements from each constituent region and flatten the results.
extract_table
Section titled “extract_table”extract_table(*args, **kwargs) -> TableResultextract_tables
Section titled “extract_tables”extract_tables(*args, **kwargs) -> 'List[TableResult]'extract_text
Section titled “extract_text”extract_text( *, separator: str | None = None, layout: bool | TextLayoutOptions = False, apply_exclusions: bool = True, newlines: bool | str = True, whitespace: WhitespaceMode = 'preserve', strip: bool = True, bidi: bool = True, content_filter: ContentFilter | None = None,) -> strExtract members independently, then join them at exact host boundaries.
separator=None uses the host’s natural separator. Empty member
handling is host policy. Transforms run on members only: separators are
never normalized, stripped, bidi-processed, or included in a regex match.
extract_text_result
Section titled “extract_text_result”extract_text_result( *, separator: str | None = None, layout: bool | TextLayoutOptions = False, apply_exclusions: bool = True,) -> ExtractedTextJoin raw member results with exact source offsets.
find( selector: Optional[str] = None, *, text: Optional[Union[str, Sequence[str]]] = None, overlap: Optional[str] = None, apply_exclusions: bool = True, regex: bool = False, case: bool = True, text_tolerance: Optional[Dict[str, Any]] = None, auto_text_tolerance: Optional[Union[bool, Dict[str, Any]]] = None, reading_order: bool = True, near_threshold: Optional[float] = None, engine: Optional[str] = None,) -> Optional['Element']Resolve a selector/text query against the host using the selector service.
find_all
Section titled “find_all”find_all( selector: Optional[str] = None, *, text: Optional[Union[str, Sequence[str]]] = None, overlap: Optional[str] = None, apply_exclusions: bool = True, regex: bool = False, case: bool = True, text_tolerance: Optional[Dict[str, Any]] = None, auto_text_tolerance: Optional[Union[bool, Dict[str, Any]]] = None, reading_order: bool = True, near_threshold: Optional[float] = None, engine: Optional[str] = None,) -> 'ElementCollection'Return every element that matches the selector/text query.
flow (attribute)
Section titled “flow (attribute)”flow: 'Flow' = flowget_config
Section titled “get_config”get_config(key: str, default: Any = None, *, scope: str = 'region') -> Anyget_highlight_specs
Section titled “get_highlight_specs”get_highlight_specs() -> List[Dict[str, Any]]Get highlight specifications for all constituent regions.
This implements the highlighting protocol for FlowRegions, returning specs for each constituent region so they can be highlighted on their respective pages.
Returns:
- (
List[Dict[str, Any]]) – List of highlight specification dictionaries, one for each - (
List[Dict[str, Any]]) – constituent region.
get_highlighter
Section titled “get_highlighter”get_highlighter() -> 'HighlightingService'Resolve a highlighting service from the constituent regions.
get_rendering_service
Section titled “get_rendering_service”get_rendering_service()Public accessor for the rendering service (primarily for tests).
get_sections
Section titled “get_sections”get_sections( start_elements=None, end_elements=None, new_section_on_page_break: bool = False, include_boundaries: str = 'both', orientation: str = 'vertical', **kwargs: Any,) -> 'ElementCollection'Extract logical sections from this FlowRegion based on start/end boundary elements.
This delegates to the parent Flow’s get_sections() method, but only operates on the segments that are part of this FlowRegion.
Parameters:
- start_elements – Elements or selector string that mark the start of sections
- end_elements – Elements or selector string that mark the end of sections
- new_section_on_page_break (
bool) – Whether to start a new section at page boundaries - include_boundaries (
str) – How to include boundary elements: ‘start’, ‘end’, ‘both’, or ‘none’ - orientation (
str) – ‘vertical’ (default) or ‘horizontal’ - determines section direction
Returns:
- (
'ElementCollection') – ElementCollection of FlowRegion objects representing the extracted sections
Example:
# Split a multi-page table region by headerstable_region = flow.find("text:contains('Table 4')").below(until="text:contains('Table 5')")sections = table_region.get_sections(start_elements="text:bold")guides
Section titled “guides”guides(*args, **kwargs)has_polygon (attribute)
Section titled “has_polygon (attribute)”has_polygon: boolheight (attribute)
Section titled “height (attribute)”height: Optional[float]highlight
Section titled “highlight”highlight( label: Optional[str] = None, color: Optional[Union[Tuple, str]] = None, **kwargs,) -> Optional['PIL_Image']Highlights all constituent physical regions on their respective pages.
Parameters:
- label (
Optional[str]) – A base label for the highlights. Each constituent region might get an indexed label. - color (
Optional[Union[Tuple, str]]) – Color for the highlight. - **kwargs – Additional arguments for the underlying highlight method.
Returns:
- (
Optional['PIL_Image']) – Image generated by the underlying highlight call, or None if no highlights were added.
highlights
Section titled “highlights”highlights(show: bool = False) -> 'HighlightContext'Create a highlight context for accumulating highlights.
This allows for clean syntax to show multiple highlight groups:
Example:
with flow_region.highlights() as h: h.add(flow_region.find_all('table'), label='tables', color='blue') h.add(flow_region.find_all('text:bold'), label='bold text', color='red') h.show()Or With Automatic Display: with flow_region.highlights(show=True) as h: h.add(flow_region.find_all(‘table’), label=‘tables’) h.add(flow_region.find_all(‘text:bold’), label=‘bold’) # Automatically shows when exiting the context
Parameters:
- show (
bool) – If True, automatically show highlights when exiting context
Returns:
- (
'HighlightContext') – HighlightContext for accumulating highlights
intersects
Section titled “intersects”intersects(element) -> boolis_element_center_inside
Section titled “is_element_center_inside”is_element_center_inside(element) -> boolis_empty (attribute)
Section titled “is_empty (attribute)”is_empty: boolTrue when this FlowRegion contains no constituent regions.
is_point_inside
Section titled “is_point_inside”is_point_inside(x: float, y: float) -> boolleft(*args, **kwargs)map_parts
Section titled “map_parts”map_parts(fn: Callable[['PhysicalRegion'], Any]) -> List[Any]Apply fn to each constituent region and return the results.
metadata (attribute)
Section titled “metadata (attribute)”metadata: Dict[str, Any] = {}normalized_type (attribute)
Section titled “normalized_type (attribute)”normalized_type: Optional[str]Return the normalized type for selector compatibility. This allows FlowRegion to be found by selectors like ‘table’.
page (attribute)
Section titled “page (attribute)”page: 'Page'Return the primary page for this region (first page when multi-page).
pages (attribute)
Section titled “pages (attribute)”pages: Tuple['Page', ...]Return the distinct pages covered by this flow region.
parts (attribute)
Section titled “parts (attribute)”parts: List['PhysicalRegion']Alias for constituent_regions — the physical region parts of this FlowRegion.
polygon (attribute)
Section titled “polygon (attribute)”polygon: List[Tuple[float, float]]region_type (attribute)
Section titled “region_type (attribute)”region_type: Optional[str] = Nonerender
Section titled “render”render( *, resolution: Optional[float] = None, width: Optional[int] = None, highlights: Optional[Union[List[Dict[str, Any]], bool]] = None, labels: bool = False, label_format: Optional[str] = None, render_ocr: bool = False, layout: Literal['stack', 'grid', 'single'] = 'stack', stack_direction: Literal['vertical', 'horizontal'] = 'vertical', gap: int = 5, columns: Optional[int] = None, crop: Union[bool, int, str, 'Region', Literal['wide']] = False, crop_bbox: Optional[Tuple[float, float, float, float]] = None, **kwargs,) -> Optional[PILImage]Generate a clean image, with optional explicit highlights.
This method produces publication-ready images without any debugging annotations or persistent highlights.
Parameters:
- resolution (
Optional[float]) – DPI for rendering (default from global settings) - width (
Optional[int]) – Target width in pixels (overrides resolution) - highlights (
Optional[Union[List[Dict[str, Any]], bool]]) – Optional explicit highlight groups/specs to render - labels (
bool) – Whether to render a legend for explicit highlights - label_format (
Optional[str]) – Format string for generated highlight labels - render_ocr (
bool) – Whether to render OCR text overlay on the image - layout (
Literal['stack', 'grid', 'single']) – How to arrange multiple pages/regions - stack_direction (
Literal['vertical', 'horizontal']) – Direction for stack layout - gap (
int) – Pixels between stacked images - columns (
Optional[int]) – Number of columns for grid layout - crop (
Union[bool, int, str, 'Region', Literal['wide']]) – Cropping mode (False, True, int for padding, ‘wide’, or Region) - crop_bbox (
Optional[Tuple[float, float, float, float]]) – Explicit crop bounds - **kwargs – Additional parameters passed to rendering
Returns:
- (
Optional[PILImage]) – PIL Image object or None if nothing to render
right(*args, **kwargs)save_pdf
Section titled “save_pdf”save_pdf(path: str, method: str = 'crop') -> 'FlowRegion'Save this FlowRegion as a PDF. Each constituent region becomes a page.
Parameters:
- path (
str) – Output file path for the PDF. - method (
str) – ‘crop’ (default) or ‘whiteout’.
Returns:
- (
'FlowRegion') – Self for method chaining.
Raises:
- (
ValueError) – If there are no constituent regions or method is invalid. - (
ImportError) – If pikepdf is not installed.
selector_flow
Section titled “selector_flow”selector_flow() -> Anyselector_page
Section titled “selector_page”selector_page() -> Anyselector_region
Section titled “selector_region”selector_region() -> Anyservices (attribute)
Section titled “services (attribute)”services: ServiceNamespaceshow( *, resolution: Optional[float] = None, width: Optional[int] = None, color: Optional[Union[str, Tuple[int, int, int]]] = None, labels: bool = True, label_format: Optional[str] = None, highlights: Optional[Union[List[Dict[str, Any]], bool]] = None, legend_position: str = 'right', annotate: Optional[Union[str, List[str]]] = None, render_ocr: bool = False, layout: Optional[Literal['stack', 'grid', 'single']] = None, stack_direction: Literal['vertical', 'horizontal'] = 'vertical', gap: int = 5, columns: Optional[int] = 6, limit: Optional[int] = 30, crop: Union[bool, int, str, 'Region', Literal['wide']] = False, crop_bbox: Optional[Tuple[float, float, float, float]] = None, **kwargs,) -> Optional[PILImage]Generate a preview image with highlights.
This method is for interactive debugging and visualization. Elements are highlighted to show what’s selected or being worked with.
Parameters:
- resolution (
Optional[float]) – DPI for rendering (default from global settings) - width (
Optional[int]) – Target width in pixels (overrides resolution) - color (
Optional[Union[str, Tuple[int, int, int]]]) – Default highlight color - labels (
bool) – Whether to show labels for highlights - label_format (
Optional[str]) – Format string for labels (e.g., “Element {index}”) - highlights (
Optional[Union[List[Dict[str, Any]], bool]]) – Additional highlight groups to show, or False to disable all highlights - legend_position (
str) – Position of legend/colorbar (‘right’, ‘left’, ‘top’, ‘bottom’) - annotate (
Optional[Union[str, List[str]]]) – Attribute name(s) to display on highlights (string or list) - render_ocr (
bool) – Whether to render OCR text overlay on the image - layout (
Optional[Literal['stack', 'grid', 'single']]) – How to arrange multiple pages/regions (defaults to ‘grid’ for multi-page, ‘single’ for single page) - stack_direction (
Literal['vertical', 'horizontal']) – Direction for stack layout - gap (
int) – Pixels between stacked images - columns (
Optional[int]) – Number of columns for grid layout (defaults to 6) - limit (
Optional[int]) – Maximum number of pages to display (default 30, None for all) - crop (
Union[bool, int, str, 'Region', Literal['wide']]) – Cropping mode: - False: No cropping (default) - True: Tight crop to element bounds - int: Padding in PDF points around element (crop bounds are computed in PDF coordinate space, then scaled by resolution) - ‘wide’: Full page width, cropped vertically to element - Region: Crop to the bounds of another region - crop_bbox (
Optional[Tuple[float, float, float, float]]) – Explicit crop bounds - **kwargs – Additional parameters passed to rendering
Returns:
- (
Optional[PILImage]) – PIL Image object or None if nothing to render
source (attribute)
Section titled “source (attribute)”source: Optional[str] = Nonesource_flow_element (attribute)
Section titled “source_flow_element (attribute)”source_flow_element: Optional['FlowElement'] = source_flow_elementsplit( by: Optional[str] = None, page_breaks: bool = True, **kwargs,) -> 'ElementCollection'Split this FlowRegion into sections.
This is a convenience method that wraps get_sections() with common splitting patterns.
Parameters:
- by (
Optional[str]) – Selector string for elements that mark section boundaries (e.g., “text:bold”) - page_breaks (
bool) – Whether to also split at page boundaries (default: True) - **kwargs – Additional arguments passed to get_sections()
Returns:
- (
'ElementCollection') – ElementCollection of FlowRegion objects representing the sections
Example:
# Split by bold headerssections = flow_region.split(by="text:bold")
# Split only by specific text pattern, ignoring page breakssections = flow_region.split( by="text:contains('Section')", page_breaks=False)start_element (attribute)
Section titled “start_element (attribute)”start_element: Optional[Union['PhysicalElement', 'PhysicalRegion']] = Noneto_images
Section titled “to_images”to_images(resolution: float = 150, **kwargs) -> List['PIL_Image']Generates and returns a list of cropped PIL Images, one for each constituent physical region of this FlowRegion.
to_region
Section titled “to_region”to_region()top (attribute)
Section titled “top (attribute)”top: floattype (attribute)
Section titled “type (attribute)”type: Optional[str]Return the type attribute for selector compatibility. This is an alias for normalized_type.
width (attribute)
Section titled “width (attribute)”width: Optional[float]x0 (attribute)
Section titled “x0 (attribute)”x0: floatx1 (attribute)
Section titled “x1 (attribute)”x1: floatGuides
Section titled “Guides”Guides( verticals: Optional[Union[Iterable[float], GuidesContext]] = None, horizontals: Optional[Iterable[float]] = None, context: Optional[GuidesContext] = None, bounds: Optional[Tuple[float, float, float, float]] = None, relative: bool = False, snap_behavior: Literal['raise', 'warn', 'ignore'] = 'warn',)Manages vertical and horizontal guide lines for table extraction and layout analysis.
Guides are collections of coordinates that can be used to define table boundaries, column positions, or general layout structures. They can be created through various detection methods or manually specified.
Attributes:
- verticals – List of x-coordinates for vertical guide lines
- horizontals – List of y-coordinates for horizontal guide lines
- context – Optional Page/Region that these guides relate to
- bounds (
Optional[Bounds]) – Optional bounding box (x0, y0, x1, y1) for relative coordinate conversion - snap_behavior – How to handle failed snapping operations (‘warn’, ‘ignore’, ‘raise’)
Initialize a Guides object.
Parameters:
- verticals (
Optional[Union[Iterable[float], GuidesContext]]) – Iterable of x-coordinates for vertical guides, or a context object shorthand - horizontals (
Optional[Iterable[float]]) – Iterable of y-coordinates for horizontal guides - context (
Optional[GuidesContext]) – Object providing spatial context (page, region, flow, etc.) - bounds (
Optional[Tuple[float, float, float, float]]) – Bounding box (x0, top, x1, bottom) if context not provided - relative (
bool) – Whether coordinates are relative (0-1) or absolute - snap_behavior (
Literal['raise', 'warn', 'ignore']) – How to handle snapping conflicts (‘raise’, ‘warn’, or ‘ignore’)
above(guide_index: int, obj: Optional[Union[Page, Region]] = None) -> RegionGet a region above a horizontal guide.
Parameters:
- guide_index (
int) – Horizontal guide index - obj (
Optional[Union[Page, Region]]) – Page or Region to create the region on (uses self.context if None)
Returns:
- (
Region) – Region above the specified guide
add_content
Section titled “add_content”add_content( axis: Literal['vertical', 'horizontal'] = 'vertical', markers: Union[str, List[str], ElementCollection, None] = None, obj: Optional[Union[Page, Region]] = None, align: Literal['left', 'right', 'center', 'between'] = 'left', outer: OuterBoundaryMode = True, apply_exclusions: bool = True,) -> GuidesInstance method: Add guides from content, allowing chaining. This allows: Guides.new(page).add_content(axis=‘vertical’, markers=[…])
Parameters:
- axis (
Literal['vertical', 'horizontal']) – Which axis to create guides for - markers (
Union[str, List[str], ElementCollection, None]) – Content to search for. Can be: - str: single selector or literal text - List[str]: list of selectors or literal text strings - ElementCollection: collection of elements to extract text from - None: no markers - obj (
Optional[Union[Page, Region]]) – Page or Region to search (uses self.context if None) - align (
Literal['left', 'right', 'center', 'between']) – How to align guides relative to found elements - outer (
OuterBoundaryMode) – Whether to add outer boundary guides. Can be: - bool: True/False to add/not add both - “first”: To add boundary before the first element - “last”: To add boundary before the last element - apply_exclusions (
bool) – Whether to apply exclusion zones when searching for text
Returns:
- (
Guides) – Self for method chaining
add_horizontal
Section titled “add_horizontal”add_horizontal(y: float) -> GuidesAdd a horizontal guide at the specified y-coordinate.
add_lines
Section titled “add_lines”add_lines( axis: Literal['vertical', 'horizontal', 'both'] = 'both', obj: Optional[Union[Page, Region]] = None, threshold: Union[float, str] = 'auto', source_label: Optional[str] = None, max_lines_h: Optional[int] = None, max_lines_v: Optional[int] = None, outer: bool = False, detection_method: str = 'auto', resolution: int = 192, **detect_kwargs,) -> GuidesInstance method: Add guides from lines, allowing chaining. This allows: Guides.new(page).add_lines(axis=‘horizontal’)
Parameters:
- axis (
Literal['vertical', 'horizontal', 'both']) – Which axis to detect lines for - obj (
Optional[Union[Page, Region]]) – Page or Region to search (uses self.context if None) - threshold (
Union[float, str]) – Line detection threshold (‘auto’ or float 0.0-1.0) - source_label (
Optional[str]) – Filter lines by source label (vector) or label for detected lines (pixels) - max_lines_h (
Optional[int]) – Maximum horizontal lines to use - max_lines_v (
Optional[int]) – Maximum vertical lines to use - outer (
bool) – Whether to add outer boundary guides - detection_method (
str) – ‘auto’ (default), ‘vector’, or ‘pixels’. ‘auto’ uses vector line information when available and falls back to pixel detection otherwise. - resolution (
int) – DPI for pixel-based detection (default: 192) - **detect_kwargs – Additional parameters for pixel detection (see from_lines)
Returns:
- (
Guides) – Self for method chaining
add_vertical
Section titled “add_vertical”add_vertical(x: float) -> GuidesAdd a vertical guide at the specified x-coordinate.
add_whitespace
Section titled “add_whitespace”add_whitespace( axis: Literal['vertical', 'horizontal', 'both'] = 'both', obj: Optional[Union[Page, Region]] = None, min_gap: float = 10,) -> GuidesInstance method: Add guides from whitespace, allowing chaining. This allows: Guides.new(page).add_whitespace(axis=‘both’)
Parameters:
- axis (
Literal['vertical', 'horizontal', 'both']) – Which axis to create guides for - obj (
Optional[Union[Page, Region]]) – Page or Region to search (uses self.context if None) - min_gap (
float) – Minimum gap size to consider
Returns:
- (
Guides) – Self for method chaining
below(guide_index: int, obj: Optional[Union[Page, Region]] = None) -> RegionGet a region below a horizontal guide.
Parameters:
- guide_index (
int) – Horizontal guide index - obj (
Optional[Union[Page, Region]]) – Page or Region to create the region on (uses self.context if None)
Returns:
- (
Region) – Region below the specified guide
between_horizontal
Section titled “between_horizontal”between_horizontal( start_index: int, end_index: int, obj: Optional[Union[Page, Region]] = None,) -> RegionGet a region between two horizontal guides.
Parameters:
- start_index (
int) – Starting horizontal guide index - end_index (
int) – Ending horizontal guide index - obj (
Optional[Union[Page, Region]]) – Page or Region to create the region on (uses self.context if None)
Returns:
- (
Region) – Region between the specified guides
between_vertical
Section titled “between_vertical”between_vertical( start_index: int, end_index: int, obj: Optional[Union[Page, Region]] = None,) -> RegionGet a region between two vertical guides.
Parameters:
- start_index (
int) – Starting vertical guide index - end_index (
int) – Ending vertical guide index - obj (
Optional[Union[Page, Region]]) – Page or Region to create the region on (uses self.context if None)
Returns:
- (
Region) – Region between the specified guides
bounds (attribute)
Section titled “bounds (attribute)”bounds: Optional[Bounds] = coerced_boundsbuild_grid
Section titled “build_grid”build_grid( target: Optional[GuidesContext] = None, source: str = 'guides', cell_padding: float = 0.5, include_outer_boundaries: bool = False, *, multi_page: Literal['auto', True, False] = 'auto',) -> Dict[str, Any]Create table structure (table, rows, columns, cells) from guide coordinates.
Parameters:
- target (
Optional[GuidesContext]) – Page or Region to create regions on (uses self.context if None) - source (
str) – Source label for created regions (for identification) - cell_padding (
float) – Internal padding for cell regions in points - include_outer_boundaries (
bool) – Whether to add boundaries at edges if missing - multi_page (
Literal['auto', True, False]) – Controls multi-region table creation for FlowRegions. - “auto”: (default) Creates a unified grid if there are multiple regions or guides span pages. - True: Forces creation of a unified multi-region grid. - False: Creates separate grids for each region.
Returns:
- (
Dict[str, Any]) – Dictionary with ‘counts’ and ‘regions’ created.
cell(row: int, col: int, obj: Optional[Union[Page, Region]] = None) -> RegionGet a cell region from the guides.
Parameters:
- row (
int) – Row index (0-based) - col (
int) – Column index (0-based) - obj (
Optional[Union[Page, Region]]) – Page or Region to create the cell on (uses self.context if None)
Returns:
- (
Region) – Region representing the specified cell
Raises:
- (
IndexError) – If row or column index is out of range
cells (attribute)
Section titled “cells (attribute)”cells: GuideCellsAccess cells via guides.cells[row][col] or guides.cells[row, col].
column
Section titled “column”column(index: int, obj: Optional[Union[Page, Region]] = None) -> RegionGet a column region from the guides.
Parameters:
- index (
int) – Column index (0-based) - obj (
Optional[Union[Page, Region]]) – Page or Region to create the column on (uses self.context if None)
Returns:
- (
Region) – Region representing the specified column
Raises:
- (
IndexError) – If column index is out of range
columns (attribute)
Section titled “columns (attribute)”columns: GuideColumnsAccess columns by index like guides.columns[0].
context (attribute)
Section titled “context (attribute)”context = context_objdivide (classmethod)
Section titled “divide (classmethod)”divide( obj: Union[Page, Region, Tuple[float, float, float, float]], n: Optional[int] = None, cols: Optional[int] = None, rows: Optional[int] = None, axis: Literal['vertical', 'horizontal', 'both'] = 'both',) -> GuidesCreate guides by evenly dividing an object.
Parameters:
- obj (
Union[Page, Region, Tuple[float, float, float, float]]) – Object to divide (Page, Region, or bbox tuple) - n (
Optional[int]) – Number of divisions (creates n+1 guides). Used if cols/rows not specified. - cols (
Optional[int]) – Number of columns (creates cols+1 vertical guides) - rows (
Optional[int]) – Number of rows (creates rows+1 horizontal guides) - axis (
Literal['vertical', 'horizontal', 'both']) – Which axis to divide along
Returns:
- (
Guides) – New Guides object with evenly spaced lines
Examples:
# Divide into 3 columnsguides = Guides.divide(page, cols=3)
# Divide into 5 rowsguides = Guides.divide(region, rows=5)
# Divide both axesguides = Guides.divide(page, cols=3, rows=5)extract_table
Section titled “extract_table”extract_table( target: Optional[Union[Page, Region, PageCollection, ElementCollection, List[Union[Page, Region]]]] = None, source: str = 'guides_temp', cell_padding: float = 0.5, include_outer_boundaries: bool = False, method: Optional[str] = None, table_settings: Optional[dict] = None, use_ocr: bool = False, ocr_config: Optional[dict] = None, text_options: Optional[Dict] = None, cell_extraction_func: Optional[Callable[[Region], Optional[str]]] = None, cell_extract: Literal['text', 'words'] = 'text', cell_overlap: Literal['center', 'full', 'partial'] = 'center', cell_newlines: Union[bool, str] = True, show_progress: bool = False, content_filter: Optional[Union[str, Callable[[str], bool], List[str]]] = None, apply_exclusions: bool = True, *, multi_page: Literal['auto', True, False] = 'auto', header: Union[str, List[str], None] = 'first', skip_repeating_headers: Optional[bool] = None, structure_engine: Optional[str] = None,) -> TableResultExtract table data directly from guides without leaving temporary regions.
This method:
- Creates table structure using build_grid()
- Extracts table data from the created table region
- Cleans up all temporary regions
- Returns the TableResult
When passed a collection (PageCollection, ElementCollection, or list), this method will extract tables from each element and combine them into a single result.
Parameters:
- target (
Optional[Union[Page, Region, PageCollection, ElementCollection, List[Union[Page, Region]]]]) – Page, Region, or collection of Pages/Regions to extract from (uses self.context if None) - source (
str) – Source label for temporary regions (will be cleaned up) - cell_padding (
float) – Internal padding for cell regions in points - include_outer_boundaries (
bool) – Whether to add boundaries at edges if missing - method (
Optional[str]) – Table extraction method (‘tatr’, ‘pdfplumber’, ‘text’, etc.) - table_settings (
Optional[dict]) – Settings for pdfplumber table extraction - use_ocr (
bool) – Whether to use OCR for text extraction - ocr_config (
Optional[dict]) – OCR configuration parameters - text_options (
Optional[Dict]) – Dictionary of options for the ‘text’ method - cell_extraction_func (
Optional[Callable[[Region], Optional[str]]]) – Optional callable for custom cell text extraction - cell_extract (
Literal['text', 'words']) – Cell text mode. “text” preserves current behavior; “words” extracts word elements and can be batched for guide-built cells. - cell_overlap (
Literal['center', 'full', 'partial']) – Word overlap mode for cell_extract=“words”: “center”, “full”, or “partial”. - cell_newlines (
Union[bool, str]) – Newline handling for extracted cell text. - show_progress (
bool) – Controls progress bar for text method - content_filter (
Optional[Union[str, Callable[[str], bool], List[str]]]) – Content filtering function or patterns - apply_exclusions (
bool) – Whether to apply exclusion regions during text extraction (default: True) - multi_page (
Literal['auto', True, False]) – Controls multi-region table creation for FlowRegions - header (
Union[str, List[str], None]) – How to handle headers when extracting from collections: - “first”: Use first row of first element as headers (default) - “all”: Expect headers on each element, use from first element - None: No headers, use numeric indices - List[str]: Custom column names - skip_repeating_headers (
Optional[bool]) – Whether to remove duplicate header rows when extracting from collections. Defaults to True when header is “first” or “all”, False otherwise. - structure_engine (
Optional[str]) – Optional structure detection engine name passed to the underlying region extraction to leverage provider-backed table structure results.
Returns:
- TableResult (
TableResult) – Extracted table data
Raises:
- (
ValueError) – If no table region is created from the guides
Example:
```pythonfrom natural_pdf.analyzers import Guides
# Single page extractionguides = Guides.from_lines(page, source_label="detected")table_data = guides.extract_table()df = table_data.to_df()
# Multiple page extractionguides = Guides(pages[0])guides.vertical.from_content(['Column 1', 'Column 2'])table_result = guides.extract_table(pages, header=['Col1', 'Col2'])df = table_result.to_df()
# Region collection extractionregions = pdf.find_all('region[type=table]')guides = Guides(regions[0])guides.vertical.from_lines(n=3)table_result = guides.extract_table(regions)
# Tiny text where character-level cell extraction collapses spacingtable_result = guides.extract_table( include_outer_boundaries=True, cell_extract="words", cell_overlap="partial", cell_newlines=False,)<a id="natural_pdf.Guides.from_content"></a>
#### `from_content` *(classmethod)*
```pythonfrom_content( obj: GuidesContext, axis: Literal['vertical', 'horizontal'] = 'vertical', markers: Union[str, List[str], ElementCollection, None] = None, align: Union[Literal['left', 'right', 'center', 'between'], Literal['top', 'bottom']] = 'left', outer: OuterBoundaryMode = True, apply_exclusions: bool = True,) -> GuidesCreate guides based on text content positions.
Parameters:
- obj (
GuidesContext) – Page, Region, or FlowRegion to search for content - axis (
Literal['vertical', 'horizontal']) – Whether to create vertical or horizontal guides - markers (
Union[str, List[str], ElementCollection, None]) – Content to search for. Can be: - str: single selector (e.g., ‘text:contains(“Name”)’) or literal text - List[str]: list of selectors or literal text strings - ElementCollection: collection of elements to extract text from - None: no markers - align (
Union[Literal['left', 'right', 'center', 'between'], Literal['top', 'bottom']]) – Where to place guides relative to found text: - For vertical guides: ‘left’, ‘right’, ‘center’, ‘between’ - For horizontal guides: ‘top’, ‘bottom’, ‘center’, ‘between’ - outer (
OuterBoundaryMode) – Whether to add guides at the boundaries - apply_exclusions (
bool) – Whether to apply exclusion zones when searching for text
Returns:
- (
Guides) – New Guides object aligned to text content
from_headers (classmethod)
Section titled “from_headers (classmethod)”from_headers( obj: GuidesContext, axis: Literal['vertical', 'horizontal'] = 'vertical', headers: Union[ElementCollection, Sequence[Any], None] = None, method: Literal['min_crossings', 'seam_carving'] = 'min_crossings', min_width: Optional[float] = None, max_width: Optional[float] = None, margin: float = 0.5, row_stabilization: bool = True, num_samples: int = 400,) -> GuidesCreate vertical guides by analyzing header elements.
from_headers_and_row_anchors
Section titled “from_headers_and_row_anchors”from_headers_and_row_anchors( headers: Union[ElementCollection, Sequence[Any], None], row_anchors: Union[str, ElementCollection, Sequence[Any], Callable[[GuidesContext], Iterable[Any]]], *, header_anchor: Optional[Any] = None, obj: Optional[GuidesContext] = None, header_method: Literal['min_crossings', 'seam_carving'] = 'min_crossings', min_width: Optional[float] = None, max_width: Optional[float] = None, margin: float = 0.5, row_stabilization: bool = True, num_samples: int = 400, snap_vertical: bool = True, snap_vertical_kwargs: Optional[Dict[str, Any]] = None, row_align: Union[Literal['left', 'right', 'center', 'between'], Literal['top', 'bottom']] = 'between', row_outer: Union[bool, Literal['first', 'last']] = True, apply_exclusions: bool = True,) -> GuidesBuild table guides from column headers and stable row anchors.
Use this for crowded or borderless native-text tables where headers define columns and a first-column ID, case number, or similar marker defines each row. The helper intentionally composes the existing guide primitives: vertical guides from headers, optional whitespace snapping, and horizontal guides from row-anchor content.
Parameters:
- headers (
Union[ElementCollection, Sequence[Any], None]) – Header-row elements used to derive vertical column guides. Pass the visible table headers, not output schema names. - row_anchors (
Union[str, ElementCollection, Sequence[Any], Callable[[GuidesContext], Iterable[Any]]]) – Selector, elements, or callable identifying stable row markers such as first-column IDs or case numbers. - header_anchor (
Optional[Any]) – Optional header marker to include as the first horizontal guide marker, keeping the header row in the grid. - obj (
Optional[GuidesContext]) – Optional page/region/flow context. Defaults to this guide object’s context. - header_method (
Literal['min_crossings', 'seam_carving']) – Strategy passed tovertical.from_headers(...). - min_width (
Optional[float]) – Optional minimum column width for header-derived guides. - max_width (
Optional[float]) – Optional maximum column width for header-derived guides. - margin (
float) – Header-search margin used byfrom_headers. - row_stabilization (
bool) – Stabilize header separators with nearby row text. - num_samples (
int) – Sample count used by seam/min-crossing guide detection. - snap_vertical (
bool) – Whether to snap vertical guides into whitespace gaps. - snap_vertical_kwargs (
Optional[Dict[str, Any]]) – Options forvertical.snap_to_whitespace. - row_align (
Union[Literal['left', 'right', 'center', 'between'], Literal['top', 'bottom']]) – Alignment mode for row-anchor horizontal guides. - row_outer (
Union[bool, Literal['first', 'last']]) – Whether to add outer horizontal boundary guides. - apply_exclusions (
bool) – Respect exclusions when resolving row-anchor selectors.
Returns:
- (
Guides) – ThisGuidesobject, with vertical and horizontal guides populated.
from_lines (classmethod)
Section titled “from_lines (classmethod)”from_lines( obj: GuidesContext, axis: Literal['vertical', 'horizontal', 'both'] = 'both', threshold: Union[float, str] = 'auto', source_label: Optional[str] = None, max_lines_h: Optional[int] = None, max_lines_v: Optional[int] = None, outer: bool = False, detection_method: str = 'auto', resolution: int = 192, **detect_kwargs,) -> GuidesCreate guides from detected line elements.
Parameters:
- obj (
GuidesContext) – Page, Region, or FlowRegion to detect lines from - axis (
Literal['vertical', 'horizontal', 'both']) – Which orientations to detect - threshold (
Union[float, str]) – Detection threshold (‘auto’ or float 0.0-1.0) - used for pixel detection - source_label (
Optional[str]) – Filter for line source (vector method) or label for detected lines (pixel method) - max_lines_h (
Optional[int]) – Maximum number of horizontal lines to keep - max_lines_v (
Optional[int]) – Maximum number of vertical lines to keep - outer (
bool) – Whether to add outer boundary guides - detection_method (
str) – ‘auto’ (default), ‘vector’, or ‘pixels’. ‘auto’ uses vector line information when line elements exist and falls back to pixel detection otherwise. - resolution (
int) – DPI for pixel-based detection (default: 192) - **detect_kwargs – Additional parameters for pixel-based detection: - min_gap_h: Minimum gap between horizontal lines (pixels) - min_gap_v: Minimum gap between vertical lines (pixels) - binarization_method: ‘adaptive’ or ‘otsu’ - morph_op_h/v: Morphological operations (‘open’, ‘close’, ‘none’) - smoothing_sigma_h/v: Gaussian smoothing sigma - method: ‘projection’ (default) or ‘lsd’ (requires opencv)
Returns:
- (
Guides) – New Guides object with detected line positions
from_stripes (classmethod)
Section titled “from_stripes (classmethod)”from_stripes( obj: GuidesContext, axis: Literal['vertical', 'horizontal'] = 'horizontal', stripes: Optional[Union[ElementCollection, Sequence[Any]]] = None, color: Optional[str] = None,) -> GuidesCreate guides from zebra stripes or colored bands.
from_whitespace (classmethod)
Section titled “from_whitespace (classmethod)”from_whitespace( obj: GuidesContext, axis: Literal['vertical', 'horizontal', 'both'] = 'both', min_gap: float = 10,) -> GuidesCreate guides by detecting whitespace gaps (divide + snap placeholder).
get_cells
Section titled “get_cells”get_cells() -> List[Tuple[float, float, float, float]]Get all cell bounding boxes from guide intersections.
Returns:
- (
List[Tuple[float, float, float, float]]) – List of (x0, y0, x1, y1) tuples for each cell
horizontal (attribute)
Section titled “horizontal (attribute)”horizontal: GuidesListGet horizontal guide coordinates.
is_flow_region (attribute)
Section titled “is_flow_region (attribute)”is_flow_region = _is_flow_region(context_obj)last_ocr_result (attribute)
Section titled “last_ocr_result (attribute)”last_ocr_result: Optional[GuideOCRResult]Most recent successful OCR result from one of this guide’s views.
left_of
Section titled “left_of”left_of(guide_index: int, obj: Optional[Union[Page, Region]] = None) -> RegionGet a region to the left of a vertical guide.
Parameters:
- guide_index (
int) – Vertical guide index - obj (
Optional[Union[Page, Region]]) – Page or Region to create the region on (uses self.context if None)
Returns:
- (
Region) – Region to the left of the specified guide
n_cols (attribute)
Section titled “n_cols (attribute)”n_cols: intNumber of columns defined by vertical guides.
n_rows (attribute)
Section titled “n_rows (attribute)”n_rows: intNumber of rows defined by horizontal guides.
new (classmethod)
Section titled “new (classmethod)”new(context: Optional[Union[Page, Region]] = None) -> GuidesCreate a new empty Guides object, optionally with a context.
This provides a clean way to start building guides through chaining: guides = Guides.new(page).add_content(axis=‘vertical’, markers=[…])
Parameters:
- context (
Optional[Union[Page, Region]]) – Optional Page or Region to use as default context for operations
Returns:
- (
Guides) – New empty Guides object
on_no_snap (attribute)
Section titled “on_no_snap (attribute)”on_no_snap = snap_behaviorrelative (attribute)
Section titled “relative (attribute)”relative = relativeremove_horizontal
Section titled “remove_horizontal”remove_horizontal(index: int) -> GuidesRemove a horizontal guide by index.
remove_vertical
Section titled “remove_vertical”remove_vertical(index: int) -> GuidesRemove a vertical guide by index.
right_of
Section titled “right_of”right_of(guide_index: int, obj: Optional[Union[Page, Region]] = None) -> RegionGet a region to the right of a vertical guide.
Parameters:
- guide_index (
int) – Vertical guide index - obj (
Optional[Union[Page, Region]]) – Page or Region to create the region on (uses self.context if None)
Returns:
- (
Region) – Region to the right of the specified guide
row(index: int, obj: Optional[Union[Page, Region]] = None) -> RegionGet a row region from the guides.
Parameters:
- index (
int) – Row index (0-based) - obj (
Optional[Union[Page, Region]]) – Page or Region to create the row on (uses self.context if None)
Returns:
- (
Region) – Region representing the specified row
Raises:
- (
IndexError) – If row index is out of range
rows (attribute)
Section titled “rows (attribute)”rows: GuideRowsAccess rows by index like guides.rows[0].
shift( index: int, offset: float, axis: Literal['vertical', 'horizontal'] = 'vertical',) -> GuidesMove a specific guide by a offset amount.
Parameters:
- index (
int) – Index of the guide to move - offset (
float) – Amount to move (positive = right/down) - axis (
Literal['vertical', 'horizontal']) – Which guide list to modify
Returns:
- (
Guides) – Self for method chaining
show(on=None, **kwargs)Display the guides overlaid on a page or region.
Parameters:
- on – Page, Region, PIL Image, or string to display guides on. If None, uses self.context (the object guides were created from). If string ‘page’, uses the page from self.context.
- **kwargs – Additional arguments passed to render() if applicable.
Returns:
- PIL Image with guides drawn on it.
snap_behavior (attribute)
Section titled “snap_behavior (attribute)”snap_behavior = snap_behaviorsnap_to_whitespace
Section titled “snap_to_whitespace”snap_to_whitespace( axis: str = 'vertical', min_gap: float = 10.0, detection_method: str = 'pixels', threshold: Union[float, str] = 'auto', on_no_snap: str = 'warn',) -> GuidesSnap guides to nearby whitespace gaps (troughs) using optimal assignment. Modifies this Guides object in place.
Parameters:
- axis (
str) – Direction to snap (‘vertical’ or ‘horizontal’) - min_gap (
float) – Minimum gap size to consider as a valid trough - detection_method (
str) – Method for detecting troughs: ‘pixels’ - use pixel-based density analysis (default) ‘text’ - use text element spacing analysis - threshold (
Union[float, str]) – Threshold for what counts as a trough: - float (0.0-1.0): areas with this fraction or less of max density count as troughs - ‘auto’: automatically find threshold that creates enough troughs for guides (only applies when detection_method=‘pixels’) - on_no_snap (
str) – Action when snapping fails (‘warn’, ‘ignore’, ‘raise’)
Returns:
- (
Guides) – Self for method chaining.
to_absolute
Section titled “to_absolute”to_absolute(bounds: Tuple[float, float, float, float]) -> GuidesConvert relative coordinates to absolute coordinates.
Parameters:
- bounds (
Tuple[float, float, float, float]) – Target bounding box (x0, y0, x1, y1)
Returns:
- (
Guides) – New Guides object with absolute coordinates
to_dict
Section titled “to_dict”to_dict() -> Dict[str, Any]Convert to dictionary format suitable for pdfplumber table_settings.
Returns:
- (
Dict[str, Any]) – Dictionary with explicit_vertical_lines and explicit_horizontal_lines
to_relative
Section titled “to_relative”to_relative() -> GuidesConvert absolute coordinates to relative (0-1) coordinates.
Returns:
- (
Guides) – New Guides object with relative coordinates
vertical (attribute)
Section titled “vertical (attribute)”vertical: GuidesListGet vertical guide coordinates.
PageCollection
Section titled “PageCollection”Bases: AggregateTextMixin, OCRScopeMixin, ServiceHostMixin, SelectorHostMixin, ApplyMixin, SectionsCollectionMixin, QACollectionMixin, Visualizable, Sequence['Page']
PageCollection( pages: Sequence['Page'] | Iterable['Page'], *, context: Optional[PDFContext] = None,)Represents a collection of Page objects, often from a single PDF document. Provides methods for batch operations on these pages.
Initialize a page collection.
Parameters:
- pages (
Sequence['Page'] | Iterable['Page']) – List or sequence of Page objects (can be lazy)
analyze_layout
Section titled “analyze_layout”analyze_layout(*args, **kwargs)apply(self: Any, func: Callable[..., Any], *args: Any, **kwargs: Any) -> Anyapply_ocr
Section titled “apply_ocr”apply_ocr( engine: Optional[str] = None, *, options: Optional[Any] = None, languages: Optional[list[str]] = None, min_confidence: Optional[float] = None, device: Optional[str] = None, resolution: Optional[int] = None, detect_only: bool = False, apply_exclusions: bool = True, replace: OCRReplaceMode = 'ocr', use_cache: bool = True, model: Optional[str] = None, client: Optional[Any] = None, prompt: Optional[str] = None, instructions: Optional[str] = None, max_new_tokens: Optional[int] = None, layout: Optional[bool | str] = None, preserve_markup: bool = False, function: Optional[CustomOCRCallable] = None, source_label: str = 'custom-ocr', confidence: Optional[float] = None,) -> SelfApply OCR within this object’s spatial scope and return self.
This method has three validated modes:
- recognition (the default) recognizes text with a registered engine;
detect_only=Truerefreshes persistent text bounding boxes without deleting native or recognized text;function=recognizes text with a callable receiving each physical Region in the scope.
Parameters:
- engine (
Optional[str]) – Registered OCR engine name. When omitted, resolve the context default. Supplyingmodelorclientselects VLM OCR when no engine is named. - options (
Optional[Any]) – Typed engine-specific options object or validated mapping. - languages (
Optional[list[str]]) – Ordered language codes such as["en", "fr"]. - min_confidence (
Optional[float]) – Minimum accepted confidence between 0 and 1. - device (
Optional[str]) – Requested compute device, such as"cpu"or"cuda". - resolution (
Optional[int]) – Render resolution in DPI. - detect_only (
bool) – Refresh detection-only spatial artifacts instead of recognizing text. Detection preserves existing text. - apply_exclusions (
bool) – Mask configured exclusions in pixels sent to OCR. - replace (
OCRReplaceMode) – Recognition/function replacement policy:"ocr","all", or"none". Detection has its own refresh policy. - use_cache (
bool) – Allow the persistent OCR result cache when its identity can be proven safe. - model (
Optional[str]) – VLM model name. - client (
Optional[Any]) – OpenAI-compatible VLM client. - prompt (
Optional[str]) – Complete VLM prompt overriding the generated prompt. - instructions (
Optional[str]) – Additional VLM instructions. - max_new_tokens (
Optional[int]) – VLM generation limit. - layout (
Optional[bool | str]) – VLM layout mode (bool or registered detector name). - preserve_markup (
bool) – Preserve raw VLM markup in text metadata. - function (
Optional[CustomOCRCallable]) – Custom callable receiving a physical Region and returning recognized text orNone. It cannot be combined with engine, VLM, cache, exclusion, or detection controls. - source_label (
str) – Provenance label stored asocr_engineon custom-function output. Its selector-visible source remains"ocr"like every other OCR artifact. - confidence (
Optional[float]) – Confidence assigned to custom-function OCR text.
Returns:
- (
Self) – The receiving object for fluent chaining.
Raises:
- (
TypeError) – An argument has the wrong type orfunctionis not callable. - (
ValueError) – Mode-specific arguments conflict or a value is invalid.
ask(*args, **kwargs)attr(self: Any, name: str, skip_empty: bool = True) -> List[Any]describe
Section titled “describe”describe(**kwargs)deskew
Section titled “deskew”deskew( *, resolution: int = 300, detection_resolution: int = 72, force_overwrite: bool = False, engine: Optional[str] = None, **deskew_kwargs,) -> 'PDF'Creates a new, in-memory PDF object containing deskewed versions of the pages in this collection.
This method delegates the actual processing to the parent PDF object’s
deskew method.
Important: The returned PDF is image-based. Any existing text, OCR results, annotations, or other elements from the original pages will not be carried over.
Parameters:
- resolution (
int) – DPI resolution for rendering the output deskewed pages. - detection_resolution (
int) – DPI resolution used for skew detection if angles are not already cached on the page objects. - force_overwrite (
bool) – If False (default), raises a ValueError if any target page already contains processed elements (text, OCR, regions) to prevent accidental data loss. Set to True to proceed anyway. - engine (
Optional[str]) – Engine name —"projection"(default),"hough", or"standard". - **deskew_kwargs – Additional keyword arguments forwarded to the deskew engine during automatic detection.
Returns:
- (
'PDF') – A new PDF object representing the deskewed document.
Raises:
- (
ImportError) – If ‘img2pdf’ is not installed (raised by PDF.deskew). - (
ValueError) – Ifforce_overwriteis False and target pages contain elements (raised by PDF.deskew), or if the collection is empty. - (
RuntimeError) – If pages lack a parent PDF reference, or the parent PDF lacks thedeskewmethod.
detect_checkboxes
Section titled “detect_checkboxes”detect_checkboxes(*args, **kwargs)detect_layout (attribute)
Section titled “detect_layout (attribute)”detect_layout = analyze_layoutdetect_lines
Section titled “detect_lines”detect_lines(*args, **kwargs)elements (attribute)
Section titled “elements (attribute)”elements: Sequence['Page']Alias to expose pages for APIs expecting an elements attribute.
export
Section titled “export”export( path: Union[str, Path], *, resolution: Optional[float] = None, width: Optional[int] = None, layout: Literal['stack', 'grid', 'single'] = 'stack', stack_direction: Literal['vertical', 'horizontal'] = 'vertical', gap: int = 5, columns: Optional[int] = None, crop: Union[bool, Literal['content']] = False, crop_bbox: Optional[Tuple[float, float, float, float]] = None, format: Optional[str] = None, **kwargs,) -> NoneExport a clean image to file.
This is a convenience method that renders and saves in one step.
Parameters:
- path (
Union[str, Path]) – Output file path - resolution (
Optional[float]) – DPI for rendering - width (
Optional[int]) – Target width in pixels - layout (
Literal['stack', 'grid', 'single']) – How to arrange multiple pages/regions - stack_direction (
Literal['vertical', 'horizontal']) – Direction for stack layout - gap (
int) – Pixels between stacked images - columns (
Optional[int]) – Number of columns for grid layout - crop (
Union[bool, Literal['content']]) – Cropping mode (False, True, int for padding, ‘wide’, or Region) - crop_bbox (
Optional[Tuple[float, float, float, float]]) – Explicit crop bounds - format (
Optional[str]) – Image format (inferred from path if not specified) - **kwargs – Additional parameters passed to rendering
extract_anchored_rows
Section titled “extract_anchored_rows”extract_anchored_rows( anchors: str | Callable[[Any], Any] | Iterable[Any], *, content_selector: str = 'text', elements: str | Callable[[Any], Any] | Iterable[Any] | None = None, side: Literal['right', 'left', 'both'] = 'right', y_tolerance: float | None = None, x_gap: float = 0, include_anchor: bool = False, sort: bool = True, apply_exclusions: bool = True,) -> list['AnchoredRow']Collect anchored rows across pages in document order.
Parameters:
- anchors (
str | Callable[[Any], Any] | Iterable[Any]) – Selector, iterable, or callable returning anchors for each page. Callable inputs receive the current page. - content_selector (
str) – Selector used for candidate row content whenelementsis not supplied. - elements (
str | Callable[[Any], Any] | Iterable[Any] | None) – Optional selector, iterable, or callable for candidate row content. Iterables are partitioned by each element’s page. - side (
Literal['right', 'left', 'both']) – Collect content to the"right","left", or on"both"sides of each anchor. - y_tolerance (
float | None) – Maximum vertical midpoint distance for same-row matching. Defaults to a value derived from anchor height. - x_gap (
float) – Required gap between anchor and content for left/right matching. - include_anchor (
bool) – Include anchors in returned row text. - sort (
bool) – Sort row elements by x-position before joining text. - apply_exclusions (
bool) – Respect exclusions when resolving selector inputs.
Returns:
- (
list['AnchoredRow']) – A page-ordered list ofAnchoredRowobjects.
extract_each_text
Section titled “extract_each_text”extract_each_text( *, layout: bool | TextLayoutOptions = False, apply_exclusions: bool = True, newlines: bool | str = True, whitespace: WhitespaceMode = 'preserve', strip: bool = True, bidi: bool = True, content_filter: ContentFilter | None = None,) -> List[str]Extract each section through the common spatial/aggregate leaf contract.
extract_text
Section titled “extract_text”extract_text( *, separator: str | None = None, layout: bool | TextLayoutOptions = False, apply_exclusions: bool = True, newlines: bool | str = True, whitespace: WhitespaceMode = 'preserve', strip: bool = True, bidi: bool = True, content_filter: ContentFilter | None = None,) -> strExtract members independently, then join them at exact host boundaries.
separator=None uses the host’s natural separator. Empty member
handling is host policy. Transforms run on members only: separators are
never normalized, stripped, bidi-processed, or included in a regex match.
extract_text_result
Section titled “extract_text_result”extract_text_result( *, separator: str | None = None, layout: bool | TextLayoutOptions = False, apply_exclusions: bool = True,) -> ExtractedTextJoin raw member results with exact source offsets.
filter
Section titled “filter”filter(self: Any, predicate: Callable[[Any], bool]) -> Anyfind( selector: Optional[str] = None, *, text: Optional[Union[str, Sequence[str]]] = None, overlap: Optional[str] = None, apply_exclusions: bool = True, regex: bool = False, case: bool = True, text_tolerance: Optional[Dict[str, Any]] = None, auto_text_tolerance: Optional[Union[bool, Dict[str, Any]]] = None, reading_order: bool = True, near_threshold: Optional[float] = None, engine: Optional[str] = None,) -> Optional['Element']Resolve a selector/text query against the host using the selector service.
find_all
Section titled “find_all”find_all( selector: Optional[str] = None, *, text: Optional[Union[str, Sequence[str]]] = None, overlap: Optional[str] = None, apply_exclusions: bool = True, regex: bool = False, case: bool = True, text_tolerance: Optional[Dict[str, Any]] = None, auto_text_tolerance: Optional[Union[bool, Dict[str, Any]]] = None, reading_order: bool = True, near_threshold: Optional[float] = None, engine: Optional[str] = None,) -> 'ElementCollection'Return every element that matches the selector/text query.
get_rendering_service
Section titled “get_rendering_service”get_rendering_service()Public accessor for the rendering service (primarily for tests).
get_sections
Section titled “get_sections”get_sections( start_elements: BoundarySource = None, end_elements: BoundarySource = None, new_section_on_page_break: bool = False, include_boundaries: str = 'both', orientation: str = 'vertical',) -> 'ElementCollection'Extract logical sections across this collection of pages.
This delegates to :class:natural_pdf.flows.flow.Flow, which already
implements the heavy lifting for cross-segment section extraction and
returns either :class:Region or :class:FlowRegion objects as
appropriate. The arrangement is chosen based on the requested
orientation so that horizontal sections continue to work for rotated
content.
groupby
Section titled “groupby”groupby(by: Union[str, Callable], *, show_progress: bool = True) -> 'PageGroupBy'Group pages by selector text or callable result.
Parameters:
- by (
Union[str, Callable]) – CSS selector string or callable function - show_progress (
bool) – Whether to show progress bar during computation (default: True)
Returns:
- (
'PageGroupBy') – PageGroupBy object supporting iteration and dict-like access
Examples:
# Group by header textfor title, pages in pdf.pages.groupby('text[size=16]'): print(f"Section: {title}")
# Group by callablefor city, pages in pdf.pages.groupby(lambda p: p.find('text:contains("CITY")').extract_text()): process_city_pages(pages)
# Quick exploration with indexinggrouped = pdf.pages.groupby('text[size=16]')grouped.info() # Show all groupsfirst_section = grouped[0] # First grouplast_section = grouped[-1] # Last group
# Dict-like access by namemadison_pages = grouped.get('CITY OF MADISON')madison_pages = grouped['CITY OF MADISON'] # Alternative
# Disable progress bar for small collectionsgrouped = pdf.pages.groupby('text[size=16]', show_progress=False)highlight
Section titled “highlight”highlight(*elements, **kwargs)Convenience method for highlighting elements in Jupyter/Colab.
This method creates a highlight context, adds the elements, and returns the resulting image. It’s designed for simple one-liner usage in notebooks.
Parameters:
- *elements – Elements or element collections to highlight
- **kwargs – Additional parameters passed to show()
Returns:
- PIL Image with highlights
Example:
# Simple one-liner highlightingpage.highlight(left, mid, right)
# With custom colorspage.highlight( (tables, 'blue'), (headers, 'red'), (footers, 'green'))highlights
Section titled “highlights”highlights(show: bool = False) -> 'HighlightContext'Create a highlight context for accumulating highlights.
This allows for clean syntax to show multiple highlight groups:
Example:
with pages.highlights() as h: h.add(pages.find_all('table'), label='tables', color='blue') h.add(pages.find_all('text:bold'), label='bold text', color='red') h.show()Or With Automatic Display: with pages.highlights(show=True) as h: h.add(pages.find_all(‘table’), label=‘tables’) h.add(pages.find_all(‘text:bold’), label=‘bold’) # Automatically shows when exiting the context
Parameters:
- show (
bool) – If True, automatically show highlights when exiting context
Returns:
- (
'HighlightContext') – HighlightContext for accumulating highlights
inspect
Section titled “inspect”inspect(limit: int = 30, **kwargs)map( self: Any, func: Callable[..., Any], *args: Any, skip_empty: bool = False, **kwargs: Any,) -> Anypages (attribute)
Section titled “pages (attribute)”pages: Sequence['Page'] = pagesrender
Section titled “render”render( *, resolution: Optional[float] = None, width: Optional[int] = None, highlights: Optional[Union[List[Dict[str, Any]], bool]] = None, labels: bool = False, label_format: Optional[str] = None, render_ocr: bool = False, layout: Literal['stack', 'grid', 'single'] = 'stack', stack_direction: Literal['vertical', 'horizontal'] = 'vertical', gap: int = 5, columns: Optional[int] = None, crop: Union[bool, int, str, 'Region', Literal['wide']] = False, crop_bbox: Optional[Tuple[float, float, float, float]] = None, **kwargs,) -> Optional[PILImage]Generate a clean image, with optional explicit highlights.
This method produces publication-ready images without any debugging annotations or persistent highlights.
Parameters:
- resolution (
Optional[float]) – DPI for rendering (default from global settings) - width (
Optional[int]) – Target width in pixels (overrides resolution) - highlights (
Optional[Union[List[Dict[str, Any]], bool]]) – Optional explicit highlight groups/specs to render - labels (
bool) – Whether to render a legend for explicit highlights - label_format (
Optional[str]) – Format string for generated highlight labels - render_ocr (
bool) – Whether to render OCR text overlay on the image - layout (
Literal['stack', 'grid', 'single']) – How to arrange multiple pages/regions - stack_direction (
Literal['vertical', 'horizontal']) – Direction for stack layout - gap (
int) – Pixels between stacked images - columns (
Optional[int]) – Number of columns for grid layout - crop (
Union[bool, int, str, 'Region', Literal['wide']]) – Cropping mode (False, True, int for padding, ‘wide’, or Region) - crop_bbox (
Optional[Tuple[float, float, float, float]]) – Explicit crop bounds - **kwargs – Additional parameters passed to rendering
Returns:
- (
Optional[PILImage]) – PIL Image object or None if nothing to render
save_pdf
Section titled “save_pdf”save_pdf( output_path: Union[str, Path], ocr: bool = False, original: bool = False, apply_exclusions: bool = False, dpi: int = 300,)Saves the pages in this collection to a new PDF file.
Choose one saving mode:
ocr=True: Creates a new, image-based PDF using OCR results. This makes the text generated during the natural-pdf session searchable, but loses original vector content. Requires ‘ocr-export’ extras.original=True: Extracts the original pages from the source PDF, preserving all vector content, fonts, and annotations. OCR results from the natural-pdf session are NOT included. Requires ‘ocr-export’ extras.apply_exclusions=True: Saves the original pages with exclusion zones whited out. Cannot be combined with ocr=True.
Parameters:
- output_path (
Union[str, Path]) – Path to save the new PDF file. - ocr (
bool) – If True, save as a searchable, image-based PDF using OCR data. - original (
bool) – If True, save the original, vector-based pages. - apply_exclusions (
bool) – If True, save with exclusion zones whited out. - dpi (
int) – Resolution (dots per inch) used only when ocr=True for rendering page images and aligning the text layer.
Raises:
- (
ValueError) – If the collection is empty, if neither or both ‘ocr’ and ‘original’ are True, or if ‘original=True’ and pages originate from different PDFs. - (
ImportError) – If required libraries (‘pikepdf’, ‘Pillow’) are not installed for the chosen mode. - (
RuntimeError) – If an unexpected error occurs during saving.
selector_flow
Section titled “selector_flow”selector_flow() -> Anyselector_page
Section titled “selector_page”selector_page() -> Anyselector_region
Section titled “selector_region”selector_region() -> Anyservices (attribute)
Section titled “services (attribute)”services: ServiceNamespaceshow( *, resolution: Optional[float] = None, width: Optional[int] = None, color: Optional[Union[str, Tuple[int, int, int]]] = None, labels: bool = True, label_format: Optional[str] = None, highlights: Optional[Union[List[Dict[str, Any]], bool]] = None, legend_position: str = 'right', annotate: Optional[Union[str, List[str]]] = None, render_ocr: bool = False, layout: Optional[Literal['stack', 'grid', 'single']] = None, stack_direction: Literal['vertical', 'horizontal'] = 'vertical', gap: int = 5, columns: Optional[int] = 6, limit: Optional[int] = 30, crop: Union[bool, int, str, 'Region', Literal['wide']] = False, crop_bbox: Optional[Tuple[float, float, float, float]] = None, **kwargs,) -> Optional[PILImage]Generate a preview image with highlights.
This method is for interactive debugging and visualization. Elements are highlighted to show what’s selected or being worked with.
Parameters:
- resolution (
Optional[float]) – DPI for rendering (default from global settings) - width (
Optional[int]) – Target width in pixels (overrides resolution) - color (
Optional[Union[str, Tuple[int, int, int]]]) – Default highlight color - labels (
bool) – Whether to show labels for highlights - label_format (
Optional[str]) – Format string for labels (e.g., “Element {index}”) - highlights (
Optional[Union[List[Dict[str, Any]], bool]]) – Additional highlight groups to show, or False to disable all highlights - legend_position (
str) – Position of legend/colorbar (‘right’, ‘left’, ‘top’, ‘bottom’) - annotate (
Optional[Union[str, List[str]]]) – Attribute name(s) to display on highlights (string or list) - render_ocr (
bool) – Whether to render OCR text overlay on the image - layout (
Optional[Literal['stack', 'grid', 'single']]) – How to arrange multiple pages/regions (defaults to ‘grid’ for multi-page, ‘single’ for single page) - stack_direction (
Literal['vertical', 'horizontal']) – Direction for stack layout - gap (
int) – Pixels between stacked images - columns (
Optional[int]) – Number of columns for grid layout (defaults to 6) - limit (
Optional[int]) – Maximum number of pages to display (default 30, None for all) - crop (
Union[bool, int, str, 'Region', Literal['wide']]) – Cropping mode: - False: No cropping (default) - True: Tight crop to element bounds - int: Padding in PDF points around element (crop bounds are computed in PDF coordinate space, then scaled by resolution) - ‘wide’: Full page width, cropped vertically to element - Region: Crop to the bounds of another region - crop_bbox (
Optional[Tuple[float, float, float, float]]) – Explicit crop bounds - **kwargs – Additional parameters passed to rendering
Returns:
- (
Optional[PILImage]) – PIL Image object or None if nothing to render
split( divider: BoundarySource, *, include_boundaries: str = 'start', orientation: str = 'vertical', new_section_on_page_break: bool = False,) -> 'ElementCollection[Region]'Divide this page collection into sections based on the provided divider elements.
Parameters:
- divider (
BoundarySource) – Elements or selector string that mark section boundaries - include_boundaries (
str) – How to include boundary elements (default: ‘start’). - orientation (
str) – ‘vertical’ or ‘horizontal’ (default: ‘vertical’). - new_section_on_page_break (
bool) – Whether to split at page boundaries (default: False).
Returns:
- (
'ElementCollection[Region]') – ElementCollection of Region objects representing the sections
Example:
# Split a PDF by chapter titleschapters = pdf.pages.split("text[size>20]:contains('CHAPTER')")
# Split by page breakspage_sections = pdf.pages.split(None, new_section_on_page_break=True)
# Split multi-page document by section headerssections = pdf.pages[10:20].split("text:bold:contains('Section')")to_flow
Section titled “to_flow”to_flow( arrangement: Literal['vertical', 'horizontal'] = 'vertical', alignment: Literal['start', 'center', 'end', 'top', 'left', 'bottom', 'right'] = 'start', segment_gap: float = 0.0,) -> 'Flow'Convert this PageCollection to a Flow for cross-page operations.
This enables treating multiple pages as a continuous logical document structure, useful for multi-page tables, articles spanning columns, or any content requiring reading order across page boundaries.
Parameters:
- arrangement (
Literal['vertical', 'horizontal']) – Primary flow direction (‘vertical’ or ‘horizontal’). ‘vertical’ stacks pages top-to-bottom (most common). ‘horizontal’ arranges pages left-to-right. - alignment (
Literal['start', 'center', 'end', 'top', 'left', 'bottom', 'right']) – Cross-axis alignment for pages of different sizes: For vertical: ‘left’/‘start’, ‘center’, ‘right’/‘end’ For horizontal: ‘top’/‘start’, ‘center’, ‘bottom’/‘end’ - segment_gap (
float) – Virtual gap between pages in PDF points (default: 0.0).
Returns:
- (
'Flow') – Flow object that can perform operations across all pages in sequence.
Example:
Multi-page table extraction:```pythonpdf = npdf.PDF("multi_page_report.pdf")
# Create flow for pages 2-4 containing a tabletable_flow = pdf.pages[1:4].to_flow()
# Extract table as if it were continuoustable_data = table_flow.extract_table()df = table_data.dfCross-page element search:
# Find all headers across multiple pagesheaders = pdf.pages[5:10].to_flow().find_all('text[size>12]:bold')
# Analyze layout across pagesregions = pdf.pages.to_flow().analyze_layout(engine='yolo')<a id="natural_pdf.PageCollection.to_llm"></a>
#### `to_llm`
```pythonto_llm(**kwargs) -> strReturn an LLM-optimized text representation of this page collection.
to_markdown
Section titled “to_markdown”to_markdown(*, separator: str = '\n\n---\n\n', **kwargs) -> strConvert all pages in the collection to Markdown.
Parameters:
- separator (
str) – String inserted between page results. - **kwargs – Passed to each page’s
to_markdown().
Returns:
- (
str) – Combined Markdown string.
unique
Section titled “unique”unique(self: Any, key: Optional[Callable[[Any], Any]] = None) -> Anyupdate_ocr
Section titled “update_ocr”update_ocr( transform: Callable[[Any], Optional[str]], *, apply_exclusions: bool = False, **kwargs: Any,)Shortcut for updating only OCR text across the collection.
update_text
Section titled “update_text”update_text( transform: Callable[[Any], Optional[str]], *, selector: str = 'text', apply_exclusions: bool = False, **kwargs: Any,)Apply text corrections across every page in the collection.
Judge( name: str, labels: List[str], base_dir: Optional[Union[str, Path]] = None, target_prior: Optional[float] = None,)Visual classifier for regions using simple image metrics.
Requires class labels to be specified. For binary classification, requires at least one example of each class before making decisions.
Examples:
Checkbox detection:```pythonjudge = Judge("checkboxes", labels=["unchecked", "checked"])judge.add(empty_box, "unchecked")judge.add(marked_box, "checked")
result = judge.decide(new_box)if result.label == "checked": print("Box is checked!")Signature detection:
judge = Judge("signatures", labels=["unsigned", "signed"])judge.add(blank_area, "unsigned")judge.add(signature_area, "signed")
result = judge.decide(new_region)print(f"Classification: {result.label} (confidence: {result.score})")Initialize a Judge for visual classification.
**Parameters:**
- **name** (`str`) – Name for this judge (used for folder name)- **labels** (`List[str]`) – Class labels (required, typically 2 for binary classification)- **base_dir** (`Optional[Union[str, Path]]`) – Base directory for storage. Defaults to current directory- **target_prior** (`Optional[float]`) – Target prior probability for the FIRST label in the labels list. - 0.5 (default) = neutral, treats both classes equally - >0.5 = favors labels[0] - <0.5 = favors labels[1] Example: Judge("cb", ["checked", "unchecked"], target_prior=0.6) favors detecting "checked" checkboxes.
<a id="natural_pdf.Judge.add"></a>
#### `add`
```pythonadd(region: SupportsRender, label: Optional[str] = None) -> NoneAdd a region to the judge’s dataset.
Parameters:
- region (
SupportsRender) – Region object to add - label (
Optional[str]) – Class label. If None, added to unlabeled for later teaching
Raises:
- (
JudgeError) – If label is not in allowed labels
base_dir (attribute)
Section titled “base_dir (attribute)”base_dir: Path = Path(base_dir) if base_dir is not None else Path.cwd()config_path (attribute)
Section titled “config_path (attribute)”config_path: Path = self.root_dir / 'judge.json'count(target_label: str, regions: Iterable[SupportsRender]) -> intCount how many regions match the target label.
Parameters:
- target_label (
str) – The class label to count - regions (
Iterable[SupportsRender]) – List of regions to check
Returns:
- (
int) – Number of regions classified as target_label
decide
Section titled “decide”decide( regions: Union[SupportsRender, Iterable[SupportsRender]],) -> Union[Decision, List[Decision]]Classify one or more regions.
Parameters:
- regions (
Union[SupportsRender, Iterable[SupportsRender]]) – Single region or list of regions to classify
Returns:
- (
Union[Decision, List[Decision]]) – Decision or list of Decisions with label and score
Raises:
- (
JudgeError) – If not enough training examples
forget
Section titled “forget”forget(region: Optional[SupportsRender] = None, delete: bool = False) -> NoneClear training data, delete all files, or move a specific region to unlabeled.
Parameters:
- region (
Optional[SupportsRender]) – If provided, move this specific region to unlabeled - delete (
bool) – If True, permanently delete all files
info() -> NoneShow configuration and training information for this Judge.
inspect
Section titled “inspect”inspect(preview: bool = True) -> NoneInspect all stored examples, showing their true labels and predicted labels/scores. Useful for debugging classification issues.
Parameters:
- preview (
bool) – If True (default), display images inline in HTML tables (requires IPython/Jupyter). If False, use text-only output.
labels (attribute)
Section titled “labels (attribute)”labels = labelsload (classmethod)
Section titled “load (classmethod)”load(path: Union[str, Path]) -> JudgeLoad a judge from a saved configuration.
Parameters:
- path (
Union[str, Path]) – Path to the saved judge.json file or the judge directory
Returns:
- (
Judge) – Loaded Judge instance
lookup
Section titled “lookup”lookup(region: SupportsRender) -> Optional[Tuple[str, Image.Image]]Look up a region and return its hash and image if found in training data.
Parameters:
- region (
SupportsRender) – Region to look up
Returns:
- (
Optional[Tuple[str, Image.Image]]) – Tuple of (hash, image) if found, None if not found
metrics_info (attribute)
Section titled “metrics_info (attribute)”metrics_info: Dict[str, Dict[str, float]] = {}name (attribute)
Section titled “name (attribute)”name = namepick( target_label: str, regions: Iterable[SupportsRender], labels: Optional[Sequence[str]] = None,) -> PickResultPick which region best matches the target label.
Parameters:
- target_label (
str) – The class label to look for - regions (
Iterable[SupportsRender]) – List of regions to choose from - labels (
Optional[Sequence[str]]) – Optional human-friendly labels for each region
Returns:
- (
PickResult) – PickResult with winning region, index, label (if provided), and score
Raises:
- (
JudgeError) – If target_label not in allowed labels
root_dir (attribute)
Section titled “root_dir (attribute)”root_dir: Path = self.base_dir / namesave(path: Optional[Union[str, Path]] = None) -> NoneSave the judge configuration (auto-retrains first).
Parameters:
- path (
Optional[Union[str, Path]]) – Optional path to save to. Defaults to judge.json in root directory
show(max_per_class: int = 10, size: Tuple[int, int] = (100, 100)) -> NoneDisplay a grid showing examples from each category.
Parameters:
- max_per_class (
int) – Maximum number of examples to show per class - size (
Tuple[int, int]) – Size of each image in pixels (width, height)
target_prior (attribute)
Section titled “target_prior (attribute)”target_prior = float(target_prior) if target_prior is not None else 0.5teach(labels: Optional[List[str]] = None, review: bool = False) -> NoneInteractive teaching interface using IPython widgets.
Parameters:
- labels (
Optional[List[str]]) – Labels to use for teaching. Defaults to self.labels - review (
bool) – If True, review already labeled images for re-classification
thresholds (attribute)
Section titled “thresholds (attribute)”thresholds: Dict[str, Dict[str, Any]] = {}Decision (attribute)
Section titled “Decision (attribute)”Decision = namedtuple('Decision', ['label', 'score'])PickResult (attribute)
Section titled “PickResult (attribute)”PickResult = namedtuple('PickResult', ['region', 'index', 'label', 'score'])JudgeError
Section titled “JudgeError”Bases: NaturalPDFError
class JudgeErrorRaised when Judge operations fail.
set_default_client
Section titled “set_default_client”set_default_client(client: Any, *, model: Optional[str] = None) -> NoneSet a default OpenAI-compatible client (and optionally model) for VLM calls.
Parameters:
- client (
Any) – An OpenAI-compatible client object. - model (
Optional[str]) – Optional model name to use with the client.
configure_logging
Section titled “configure_logging”configure_logging(level=logging.INFO, handler=None)Configure logging for the natural_pdf package.
Parameters:
- level – Logging level (e.g., logging.INFO, logging.DEBUG)
- handler – Optional custom handler. Defaults to a StreamHandler.
options (attribute)
Section titled “options (attribute)”options = Options()set_option
Section titled “set_option”set_option(name: str, value)Set a global Natural PDF option.
Parameters:
- name (
str) – Option name in dot notation (e.g., ‘layout.auto_multipage’) - value – New value for the option
Example:
import natural_pdf as npdfnpdf.set_option('layout.auto_multipage', True)npdf.set_option('ocr.engine', 'rapidocr')NaturalPDFError
Section titled “NaturalPDFError”Bases: Exception
class NaturalPDFErrorBase exception for all Natural PDF errors.
All domain-specific exceptions should inherit from this class. This allows users to catch all Natural PDF errors with a single handler:
try: pdf.apply_ocr()except NaturalPDFError as e: handle_error(e)OCRError
Section titled “OCRError”Bases: NaturalPDFError
class OCRErrorError during OCR processing.
Raised when:
- OCR engine initialization fails
- Image processing fails
- Text recognition fails
- Engine is not available
OCREngineNotAvailableError
Section titled “OCREngineNotAvailableError”Bases: OCRError
class OCREngineNotAvailableErrorRaised when a requested OCR engine is not installed or available.
LayoutError
Section titled “LayoutError”Bases: NaturalPDFError
class LayoutErrorError during layout detection.
Raised when:
- Layout detector initialization fails
- Model loading fails
- Detection processing fails
LayoutEngineNotAvailableError
Section titled “LayoutEngineNotAvailableError”Bases: LayoutError
class LayoutEngineNotAvailableErrorRaised when a requested layout engine is not installed or available.
SelectorError
Section titled “SelectorError”Bases: NaturalPDFError
class SelectorErrorError in selector parsing or matching.
Raised when:
- Selector syntax is invalid
- Selector matching fails
- Referenced elements not found
SelectorParseError
Section titled “SelectorParseError”Bases: SelectorError
class SelectorParseErrorRaised when a selector string cannot be parsed.
SelectorMatchError
Section titled “SelectorMatchError”Bases: SelectorError
class SelectorMatchErrorRaised when selector matching encounters an error.
ContentFilterError
Section titled “ContentFilterError”Bases: NaturalPDFError
class ContentFilterErrorRaised when a content filter cannot be compiled or evaluated safely.
Content filters are commonly used to remove sensitive or unwanted text. Silently ignoring a broken filter would return the unfiltered content, so filter failures are surfaced to the caller instead.
TextExtractionError
Section titled “TextExtractionError”Bases: NaturalPDFError
class TextExtractionErrorRaised when text acquisition or layout reconstruction fails.
The original backend exception is retained as __cause__ so callers can
distinguish an invalid extraction result from an empty one.
ExclusionError
Section titled “ExclusionError”Bases: NaturalPDFError
class ExclusionErrorRaised when an exclusion rule cannot be evaluated safely.
ConfigurationError
Section titled “ConfigurationError”Bases: NaturalPDFError
class ConfigurationErrorError in configuration or options.
Raised when:
- Invalid option values provided
- Required configuration missing
- Incompatible options combination
InvalidOptionError
Section titled “InvalidOptionError”Bases: ConfigurationError
class InvalidOptionErrorRaised when an option value is invalid (wrong type, out of range, etc.).
ExportError
Section titled “ExportError”Bases: NaturalPDFError
class ExportErrorError during export operations.
Raised when:
- Export format not supported
- Export writing fails
- Required data missing for export
SearchError
Section titled “SearchError”Bases: NaturalPDFError
class SearchErrorError during search operations.
ClassificationError
Section titled “ClassificationError”Bases: NaturalPDFError
class ClassificationErrorError during classification operations.
Raised when:
- Classification model loading fails
- Classification inference fails
- Invalid classification configuration
QAError
Section titled “QAError”Bases: NaturalPDFError
class QAErrorError during document Q&A operations.
Raised when:
- Q&A model initialization fails
- Question answering fails
- Context extraction fails
ContentFilter (attribute)
Section titled “ContentFilter (attribute)”ContentFilter: TypeAlias = RegexFilter | Sequence[RegexFilter] | Callable[[str], bool]ExtractedText
Section titled “ExtractedText”ExtractedText(*, text: str, segments: tuple[SourceTextSegment, ...] = ())Immutable text plus exact source spans.
segments (attribute)
Section titled “segments (attribute)”segments: tuple[SourceTextSegment, ...] = ()text (attribute)
Section titled “text (attribute)”text: strSourceTextSegment
Section titled “SourceTextSegment”SourceTextSegment( *, output_start: int, output_end: int, source: object, textmap: Any | None = None, words: tuple[Any, ...] = (), page_number: int | None = None, bbox: BBox | None = None,)A source’s exact half-open span in an :class:ExtractedText value.
bbox (attribute)
Section titled “bbox (attribute)”bbox: BBox | None = Noneoutput_end (attribute)
Section titled “output_end (attribute)”output_end: intoutput_start (attribute)
Section titled “output_start (attribute)”output_start: intpage_number (attribute)
Section titled “page_number (attribute)”page_number: int | None = Nonesource (attribute)
Section titled “source (attribute)”source: objecttextmap (attribute)
Section titled “textmap (attribute)”textmap: Any | None = Nonewords (attribute)
Section titled “words (attribute)”words: tuple[Any, ...] = ()TextLayoutOptions
Section titled “TextLayoutOptions”TextLayoutOptions( *, enabled: bool = True, x_tolerance: float | None = None, y_tolerance: float | None = None, x_tolerance_ratio: float | None = None, y_tolerance_ratio: float | None = None, x_density: float | None = None, y_density: float | None = None, keep_blank_chars: bool | None = None, line_dir: TextDirection | None = None, char_dir: TextDirection | None = None, line_dir_rotated: TextDirection | None = None, char_dir_rotated: TextDirection | None = None, line_dir_render: TextDirection | None = None, char_dir_render: TextDirection | None = None, split_at_punctuation: bool | str | None = None, expand_ligatures: bool | None = None,)Typed pdfplumber text-layout options.
Host geometry (bbox, width/height, and coordinate shifts) belongs to
:class:SpatialTextInput and cannot be overridden here.
char_dir (attribute)
Section titled “char_dir (attribute)”char_dir: TextDirection | None = Nonechar_dir_render (attribute)
Section titled “char_dir_render (attribute)”char_dir_render: TextDirection | None = Nonechar_dir_rotated (attribute)
Section titled “char_dir_rotated (attribute)”char_dir_rotated: TextDirection | None = Noneenabled (attribute)
Section titled “enabled (attribute)”enabled: bool = Trueexpand_ligatures (attribute)
Section titled “expand_ligatures (attribute)”expand_ligatures: bool | None = Nonekeep_blank_chars (attribute)
Section titled “keep_blank_chars (attribute)”keep_blank_chars: bool | None = Noneline_dir (attribute)
Section titled “line_dir (attribute)”line_dir: TextDirection | None = Noneline_dir_render (attribute)
Section titled “line_dir_render (attribute)”line_dir_render: TextDirection | None = Noneline_dir_rotated (attribute)
Section titled “line_dir_rotated (attribute)”line_dir_rotated: TextDirection | None = Nonesplit_at_punctuation (attribute)
Section titled “split_at_punctuation (attribute)”split_at_punctuation: bool | str | None = Nonex_density (attribute)
Section titled “x_density (attribute)”x_density: float | None = Nonex_tolerance (attribute)
Section titled “x_tolerance (attribute)”x_tolerance: float | None = Nonex_tolerance_ratio (attribute)
Section titled “x_tolerance_ratio (attribute)”x_tolerance_ratio: float | None = Noney_density (attribute)
Section titled “y_density (attribute)”y_density: float | None = Noney_tolerance (attribute)
Section titled “y_tolerance (attribute)”y_tolerance: float | None = Noney_tolerance_ratio (attribute)
Section titled “y_tolerance_ratio (attribute)”y_tolerance_ratio: float | None = NoneWhitespaceMode (attribute)
Section titled “WhitespaceMode (attribute)”WhitespaceMode: TypeAlias = Literal['preserve', 'normalize']export_training_data
Section titled “export_training_data”export_training_data( source: Union['PDF', 'PDFCollection', List['PDF']], output_dir: Union[str, os.PathLike], *, selector: Optional[str] = 'text', prompt: str = 'OCR this image. Return only the exact text.', resolution: int = 150, padding: int = 2, output_format: Literal['jsonl', 'csv'] = 'jsonl', overwrite: bool = False, split: Optional[float] = None, random_seed: int = 42, include_metadata: bool = True,) -> dictExport cropped text-element images and labels for OCR model training.
Parameters:
- source (
Union['PDF', 'PDFCollection', List['PDF']]) – One or more PDFs to export from. - output_dir (
Union[str, os.PathLike]) – Destination directory (created if needed). - selector (
Optional[str]) – CSS-like selector for which elements to crop (default"text"). - prompt (
str) – Instruction string used in theconversationsfield. - resolution (
int) – Render DPI for crop images. - padding (
int) – Points of padding around each element bbox. - output_format (
Literal['jsonl', 'csv']) –"jsonl"(ShareGPT + HF ImageFolder) or"csv". - overwrite (
bool) – If False and output_dir already exists, raiseFileExistsError. - split (
Optional[float]) – Train/validation split ratio (e.g.0.9for 90 % train). None means no split. - random_seed (
int) – Seed for reproducible train/val shuffling. - include_metadata (
bool) – Include source PDF path, page number, and bbox in output.
Returns:
- (
dict) – Summary dict:{"images": N, "skipped": M, "output_dir": path}.
Text extraction methods are inherited from the host-specific text contract mixins. The text extraction contract reference documents the four signatures, supported options, return types, and migration rules.
The API build keeps inherited members enabled so each host’s generated page shows the same canonical signature as the corresponding contract family.
Public text contract types
Section titled “Public text contract types”The value objects used by text extraction are also available from
natural_pdf:
from natural_pdf import ( ExtractedText, SourceTextSegment, TextLayoutOptions, WhitespaceMode,)Their complete fields and validation rules are defined in
natural_pdf.text.contracts.
TextLayoutOptions
Section titled “TextLayoutOptions”TextLayoutOptions( *, enabled: bool = True, x_tolerance: float | None = None, y_tolerance: float | None = None, x_tolerance_ratio: float | None = None, y_tolerance_ratio: float | None = None, x_density: float | None = None, y_density: float | None = None, keep_blank_chars: bool | None = None, line_dir: TextDirection | None = None, char_dir: TextDirection | None = None, line_dir_rotated: TextDirection | None = None, char_dir_rotated: TextDirection | None = None, line_dir_render: TextDirection | None = None, char_dir_render: TextDirection | None = None, split_at_punctuation: bool | str | None = None, expand_ligatures: bool | None = None,)Typed pdfplumber text-layout options.
Host geometry (bbox, width/height, and coordinate shifts) belongs to
:class:SpatialTextInput and cannot be overridden here.
char_dir (attribute)
Section titled “char_dir (attribute)”char_dir: TextDirection | None = Nonechar_dir_render (attribute)
Section titled “char_dir_render (attribute)”char_dir_render: TextDirection | None = Nonechar_dir_rotated (attribute)
Section titled “char_dir_rotated (attribute)”char_dir_rotated: TextDirection | None = Noneenabled (attribute)
Section titled “enabled (attribute)”enabled: bool = Trueexpand_ligatures (attribute)
Section titled “expand_ligatures (attribute)”expand_ligatures: bool | None = Nonekeep_blank_chars (attribute)
Section titled “keep_blank_chars (attribute)”keep_blank_chars: bool | None = Noneline_dir (attribute)
Section titled “line_dir (attribute)”line_dir: TextDirection | None = Noneline_dir_render (attribute)
Section titled “line_dir_render (attribute)”line_dir_render: TextDirection | None = Noneline_dir_rotated (attribute)
Section titled “line_dir_rotated (attribute)”line_dir_rotated: TextDirection | None = Nonesplit_at_punctuation (attribute)
Section titled “split_at_punctuation (attribute)”split_at_punctuation: bool | str | None = Nonex_density (attribute)
Section titled “x_density (attribute)”x_density: float | None = Nonex_tolerance (attribute)
Section titled “x_tolerance (attribute)”x_tolerance: float | None = Nonex_tolerance_ratio (attribute)
Section titled “x_tolerance_ratio (attribute)”x_tolerance_ratio: float | None = Noney_density (attribute)
Section titled “y_density (attribute)”y_density: float | None = Noney_tolerance (attribute)
Section titled “y_tolerance (attribute)”y_tolerance: float | None = Noney_tolerance_ratio (attribute)
Section titled “y_tolerance_ratio (attribute)”y_tolerance_ratio: float | None = NoneExtractedText
Section titled “ExtractedText”ExtractedText(*, text: str, segments: tuple[SourceTextSegment, ...] = ())Immutable text plus exact source spans.
segments (attribute)
Section titled “segments (attribute)”segments: tuple[SourceTextSegment, ...] = ()text (attribute)
Section titled “text (attribute)”text: strSourceTextSegment
Section titled “SourceTextSegment”SourceTextSegment( *, output_start: int, output_end: int, source: object, textmap: Any | None = None, words: tuple[Any, ...] = (), page_number: int | None = None, bbox: BBox | None = None,)A source’s exact half-open span in an :class:ExtractedText value.
bbox (attribute)
Section titled “bbox (attribute)”bbox: BBox | None = Noneoutput_end (attribute)
Section titled “output_end (attribute)”output_end: intoutput_start (attribute)
Section titled “output_start (attribute)”output_start: intpage_number (attribute)
Section titled “page_number (attribute)”page_number: int | None = Nonesource (attribute)
Section titled “source (attribute)”source: objecttextmap (attribute)
Section titled “textmap (attribute)”textmap: Any | None = Nonewords (attribute)
Section titled “words (attribute)”words: tuple[Any, ...] = ()The less commonly imported extraction hosts are documented explicitly below; they are not re-exported from the package root, but their signatures are part of the public contract:
RectangleElement
Section titled “RectangleElement”Bases: SpatialTextMixin, Element
RectangleElement(obj: Dict[str, Any], page: Page)Represents a rectangle element in a PDF.
This class is a wrapper around pdfplumber’s rectangle objects, providing additional functionality for analysis and extraction.
Initialize a rectangle element.
Parameters:
- obj (
Dict[str, Any]) – The underlying pdfplumber object - page (
Page) – The parent Page object
above( height: Optional[float] = None, width: str = 'full', include_source: bool = False, until: Optional[str] = None, include_endpoint: bool = True, offset: Optional[float] = None, apply_exclusions: bool = True, multipage: Optional[bool] = None, within: Optional['Region'] = None, anchor: str = 'start', **kwargs,) -> Optional[Union['Region', 'FlowRegion']]Select region above this element/region.
Parameters:
- height (
Optional[float]) – Height of the region above, in points - width (
str) – Width mode - “full” (default) for full page width or “element” for element width - include_source (
bool) – Whether to include this element/region in the result (default: False) - until (
Optional[str]) – Optional selector string to specify an upper boundary element - include_endpoint (
bool) – Whether to include the boundary element in the region (default: True) - offset (
Optional[float]) – Pixel offset when excluding source/endpoint (default: None, uses natural_pdf.options.layout.directional_offset) - apply_exclusions (
bool) – Whether to respect exclusions when using ‘until’ selector (default: True) - multipage (
Optional[bool]) – If True, allows the region to span multiple pages. Returns FlowRegion if the result spans multiple pages, Region otherwise (default: None uses global option) - within (
Optional['Region']) – Optional region to constrain the result to (default: None) - anchor (
str) – Reference point - ‘start’ (default), ‘center’, ‘end’, or explicit edges like ‘top’, ‘bottom’ - **kwargs – Additional parameters
Returns:
- (
Optional[Union['Region', 'FlowRegion']]) – Region object representing the area above, or None if within constraint has no overlap
Examples:
```python# Default: full page widthsignature.above() # Gets everything above across full page width
# Match element widthsignature.above(width='element') # Gets region above matching signature width
# Stop at specific elementsignature.above(until='text:contains("Date")') # Region from date to signature<a id="natural_pdf.elements.rect.RectangleElement.analyses"></a>
#### `analyses` *(attribute)*
```pythonanalyses: Dict[str, Any]Dictionary holding model-generated analysis objects (classification, extraction, …).
attr(name: str) -> AnyGet an attribute value from this element.
This method provides a consistent interface for attribute access that works on both individual elements and collections. When called on a single element, it simply returns the attribute value. When called on collections, it extracts the attribute from all elements.
Parameters:
- name (
str) – The attribute name to retrieve (e.g., ‘text’, ‘size’, ‘width’)
Returns:
- (
Any) – The attribute value, or None if the attribute doesn’t exist
Examples:
# On a single elementelement = page.find('text:contains("Title")')size = element.attr('size') # Same as element.size
# On a collection (defined in ApplyMixin)elements = page.find_all('text')sizes = elements.attr('size') # [12, 10, 14, ...]
# Consistent API for bothresult = obj.attr('text') # Works whether obj is element or collectionbbox (attribute)
Section titled “bbox (attribute)”bbox: Tuple[float, float, float, float]Bounding box (x0, top, x1, bottom).
below( height: Optional[float] = None, width: str = 'full', include_source: bool = False, until: Optional[str] = None, include_endpoint: bool = True, offset: Optional[float] = None, apply_exclusions: bool = True, multipage: Optional[bool] = None, within: Optional['Region'] = None, anchor: str = 'start', **kwargs,) -> Optional[Union['Region', 'FlowRegion']]Select region below this element/region.
Parameters:
- height (
Optional[float]) – Height of the region below, in points - width (
str) – Width mode - “full” (default) for full page width or “element” for element width - include_source (
bool) – Whether to include this element/region in the result (default: False) - until (
Optional[str]) – Optional selector string to specify a lower boundary element - include_endpoint (
bool) – Whether to include the boundary element in the region (default: True) - multipage (
Optional[bool]) – If True, allows the region to span multiple pages. Returns FlowRegion if the result spans multiple pages, Region otherwise (default: None uses global option) - offset (
Optional[float]) – Pixel offset when excluding source/endpoint (default: None, uses natural_pdf.options.layout.directional_offset) - apply_exclusions (
bool) – Whether to respect exclusions when using ‘until’ selector (default: True) - within (
Optional['Region']) – Optional region to constrain the result to (default: None) - anchor (
str) – Reference point - ‘start’ (default), ‘center’, ‘end’, or explicit edges like ‘top’, ‘bottom’ - **kwargs – Additional parameters
Returns:
- (
Optional[Union['Region', 'FlowRegion']]) – Region object representing the area below, or None if within constraint has no overlap
Examples:
```python# Default: full page widthheader.below() # Gets everything below across full page width
# Match element widthheader.below(width='element') # Gets region below matching header width
# Limited heightheader.below(height=200) # Gets 200pt tall region below header<a id="natural_pdf.elements.rect.RectangleElement.bottom"></a>
#### `bottom` *(attribute)*
```pythonbottom: floatBottom y-coordinate.
category (attribute)
Section titled “category (attribute)”category: Optional[str]Top category label for the last classification run.
category_confidence (attribute)
Section titled “category_confidence (attribute)”category_confidence: Optional[float]Confidence score associated with category.
classification_results (attribute)
Section titled “classification_results (attribute)”classification_results: Optional[Dict[str, Any]]Full classification payload converted into a dictionary.
classify
Section titled “classify”classify( labels: List[str], *, model: Optional[str] = None, using: Optional[str] = None, min_confidence: float = 0.0, analysis_key: str = 'classification', multi_label: bool = False, **kwargs: Any,)Delegate classification to the classification service and return the result.
correct_ocr
Section titled “correct_ocr”correct_ocr(*args, **kwargs)create_region
Section titled “create_region”create_region(x0: float, top: float, x1: float, bottom: float) -> 'Region'Create a region on this element’s page using absolute coordinates.
describe
Section titled “describe”describe(*args, **kwargs)exclude
Section titled “exclude”exclude()Exclude this element from text extraction and other operations.
For Region elements, this excludes everything within the region’s bounds. For other elements (like TextElement), this excludes only the specific element, not the entire area it occupies.
expand
Section titled “expand”expand( amount: Optional[float] = None, left: Union[float, bool, str] = 0, right: Union[float, bool, str] = 0, top: Union[float, bool, str] = 0, bottom: Union[float, bool, str] = 0, width_factor: float = 1.0, height_factor: float = 1.0, apply_exclusions: bool = True,) -> Union['Region', 'FlowRegion']Create a new region expanded from this element/region.
Parameters:
- amount (
Optional[float]) – If provided as the first positional argument, expand all edges by this amount - left (
Union[float, bool, str]) – Amount to expand left edge: - float: Fixed pixel expansion - True: Expand to page edge - str: Selector to expand until (excludes target by default, prefix with ’+’ to include) - right (
Union[float, bool, str]) – Amount to expand right edge (same options as left) - top (
Union[float, bool, str]) – Amount to expand top edge (same options as left) - bottom (
Union[float, bool, str]) – Amount to expand bottom edge (same options as left) - width_factor (
float) – Factor to multiply width by (applied after absolute expansion) - height_factor (
float) – Factor to multiply height by (applied after absolute expansion) - apply_exclusions (
bool) – Whether to respect exclusions when using selectors (default: True)
Returns:
- (
Union['Region', 'FlowRegion']) – New expanded Region object
Examples:
# Expand 5 pixels in all directionsexpanded = element.expand(5)
# Expand by different amounts in each directionexpanded = element.expand(left=10, right=5, top=3, bottom=7)
# Expand to page edgesexpanded = element.expand(left=True, right=True) # Full width
# Expand until specific elementsstatute = page.find('text:contains("Statute")')expanded = statute.expand(right='text:contains("Repeat?")') # Excludes "Repeat?"expanded = statute.expand(right='+text:contains("Repeat?")') # Includes "Repeat?"
# Use width/height factorsexpanded = element.expand(width_factor=1.5, height_factor=2.0)export
Section titled “export”export( path: Union[str, Path], *, resolution: Optional[float] = None, width: Optional[int] = None, layout: Literal['stack', 'grid', 'single'] = 'stack', stack_direction: Literal['vertical', 'horizontal'] = 'vertical', gap: int = 5, columns: Optional[int] = None, crop: Union[bool, Literal['content']] = False, crop_bbox: Optional[Tuple[float, float, float, float]] = None, format: Optional[str] = None, **kwargs,) -> NoneExport a clean image to file.
This is a convenience method that renders and saves in one step.
Parameters:
- path (
Union[str, Path]) – Output file path - resolution (
Optional[float]) – DPI for rendering - width (
Optional[int]) – Target width in pixels - layout (
Literal['stack', 'grid', 'single']) – How to arrange multiple pages/regions - stack_direction (
Literal['vertical', 'horizontal']) – Direction for stack layout - gap (
int) – Pixels between stacked images - columns (
Optional[int]) – Number of columns for grid layout - crop (
Union[bool, Literal['content']]) – Cropping mode (False, True, int for padding, ‘wide’, or Region) - crop_bbox (
Optional[Tuple[float, float, float, float]]) – Explicit crop bounds - format (
Optional[str]) – Image format (inferred from path if not specified) - **kwargs – Additional parameters passed to rendering
extract_text
Section titled “extract_text”extract_text( *, layout: bool | TextLayoutOptions = False, apply_exclusions: bool = True, newlines: bool | str = True, whitespace: WhitespaceMode = 'preserve', strip: bool = True, bidi: bool = True, content_filter: ContentFilter | None = None,) -> strExtract spatial text with explicit acquisition and transform options.
layout enables spatial layout reconstruction, while
apply_exclusions controls registered exclusion regions. Newline,
whitespace, bidi, filtering, and stripping transforms are applied in a
stable order after acquisition. Regex filters remove matches; callable
filters are predicates invoked once for each Unicode codepoint.
extract_text_result
Section titled “extract_text_result”extract_text_result( *, layout: bool | TextLayoutOptions = False, apply_exclusions: bool = True,) -> ExtractedTextReturn raw spatial text and provenance using acquisition options only.
fill (attribute)
Section titled “fill (attribute)”fill: TupleGet the fill color of the rectangle (RGB tuple).
find( selector: Optional[str] = None, *, text: Optional[Union[str, Sequence[str]]] = None, overlap: Optional[str] = None, apply_exclusions: bool = True, regex: bool = False, case: bool = True, text_tolerance: Optional[Dict[str, Any]] = None, auto_text_tolerance: Optional[Union[bool, Dict[str, Any]]] = None, reading_order: bool = True, near_threshold: Optional[float] = None, engine: Optional[str] = None,) -> Optional['Element']Resolve a selector/text query against the host using the selector service.
find_all
Section titled “find_all”find_all( selector: Optional[str] = None, *, text: Optional[Union[str, Sequence[str]]] = None, overlap: Optional[str] = None, apply_exclusions: bool = True, regex: bool = False, case: bool = True, text_tolerance: Optional[Dict[str, Any]] = None, auto_text_tolerance: Optional[Union[bool, Dict[str, Any]]] = None, reading_order: bool = True, near_threshold: Optional[float] = None, engine: Optional[str] = None,) -> 'ElementCollection'Return every element that matches the selector/text query.
get_highlight_specs
Section titled “get_highlight_specs”get_highlight_specs() -> List[Dict[str, Any]]Get highlight specifications for this element.
Returns a list of dictionaries, each containing:
- page: The Page object to highlight on
- page_index: The 0-based index of the page
- bbox: The bounding box (x0, y0, x1, y1) to highlight
- polygon: Optional polygon coordinates for non-rectangular highlights
- element: Reference to the element being highlighted
For regular elements, this returns a single spec. For FlowRegions, this returns specs for all constituent regions.
Returns:
- (
List[Dict[str, Any]]) – List of highlight specification dictionaries
get_rendering_service
Section titled “get_rendering_service”get_rendering_service()Public accessor for the rendering service (primarily for tests).
has_polygon (attribute)
Section titled “has_polygon (attribute)”has_polygon: boolCheck if this element has polygon coordinates.
height (attribute)
Section titled “height (attribute)”height: floatElement height.
highlight
Section titled “highlight”highlight( label: str = '', color: Optional[Tuple[float, float, float]] = None, use_color_cycling: bool = True, annotate: Optional[List[str]] = None, existing: str = 'append',) -> NoneHighlight the element with the specified colour.
Highlight the element on the page.
inspect
Section titled “inspect”inspect(*args, **kwargs)is_horizontal (attribute)
Section titled “is_horizontal (attribute)”is_horizontal: boolCheck if this is a horizontal line based on coordinates.
is_point_inside
Section titled “is_point_inside”is_point_inside(x: float, y: float) -> boolCheck if a point is inside this element using ray casting algorithm for polygons.
Parameters:
- x (
float) – X-coordinate to check - y (
float) – Y-coordinate to check
Returns:
- (
bool) – True if the point is inside the element
is_vertical (attribute)
Section titled “is_vertical (attribute)”is_vertical: boolCheck if this is a vertical line based on coordinates.
left( width: Optional[float] = None, height: str = 'element', include_source: bool = False, until: Optional[str] = None, include_endpoint: bool = True, offset: Optional[float] = None, apply_exclusions: bool = True, multipage: Optional[bool] = None, within: Optional['Region'] = None, anchor: str = 'start', **kwargs,) -> Optional[Union['Region', 'FlowRegion']]Select region to the left of this element/region.
Parameters:
- width (
Optional[float]) – Width of the region to the left, in points - height (
str) – Height mode - “element” (default) for element height or “full” for full page height - include_source (
bool) – Whether to include this element/region in the result (default: False) - until (
Optional[str]) – Optional selector string to specify a left boundary element - include_endpoint (
bool) – Whether to include the boundary element in the region (default: True) - offset (
Optional[float]) – Pixel offset when excluding source/endpoint (default: None, uses natural_pdf.options.layout.directional_offset) - apply_exclusions (
bool) – Whether to respect exclusions when using ‘until’ selector (default: True) - multipage (
Optional[bool]) – If True, allows the region to span multiple pages. Returns FlowRegion if the result spans multiple pages, Region otherwise (default: None uses global option) - within (
Optional['Region']) – Optional region to constrain the result to (default: None) - anchor (
str) – Reference point - ‘start’ (default), ‘center’, ‘end’, or explicit edges like ‘left’, ‘right’ - **kwargs – Additional parameters
Returns:
- (
Optional[Union['Region', 'FlowRegion']]) – Region object representing the area to the left, or None if within constraint has no overlap
Examples:
```python# Default: matches element heighttable.left() # Gets region to the left at same height as table
# Full page heighttable.left(height='full') # Gets entire left side of page
# Custom heighttable.left(height=100) # Gets 100pt tall region to the left<a id="natural_pdf.elements.rect.RectangleElement.metadata"></a>
#### `metadata` *(attribute)*
```pythonmetadata: Dict[str, Any] = {}nearest
Section titled “nearest”nearest( selector: str, max_distance: Optional[float] = None, apply_exclusions: bool = True, **kwargs,) -> Optional['Element']Find nearest element matching selector.
Parameters:
- selector (
str) – CSS-like selector string - max_distance (
Optional[float]) – Maximum distance to search (default: None = unlimited) - apply_exclusions (
bool) – Whether to apply exclusion regions (default: True) - **kwargs – Additional parameters
Returns:
- (
Optional['Element']) – Nearest element or None if not found
next( selector: Optional[str] = None, limit: int = 10, apply_exclusions: bool = True, **kwargs,) -> Optional['Element']Find next element in reading order.
Parameters:
- selector (
Optional[str]) – Optional selector to filter by - limit (
int) – Maximum number of elements to search through (default: 10) - apply_exclusions (
bool) – Whether to apply exclusion regions (default: True) - **kwargs – Additional parameters for selector filtering (e.g., regex, case)
Returns:
- (
Optional['Element']) – Next element or None if not found
orientation (attribute)
Section titled “orientation (attribute)”orientation: strGet the orientation of the line (‘horizontal’, ‘vertical’, or ‘diagonal’).
page (attribute)
Section titled “page (attribute)”page: 'Page'Get the parent page.
parent
Section titled “parent”parent(selector: Optional[str] = None, *, mode: str = 'contains') -> Optional['Element']Return the smallest element/region that encloses this one.
The search is purely geometric – no pre-existing hierarchy is assumed.
Parameters
Section titled “Parameters”selector : str, optional CSS-style selector used to filter candidate containers first. mode : str, default “contains” How to decide if a candidate encloses this element.
• ``"contains"`` – candidate bbox fully contains *self* bbox.• ``"center"`` – candidate contains the centroid of *self*.• ``"overlap"`` – any bbox intersection > 0 pt².Returns
Section titled “Returns”Element | Region | None The smallest-area container that matches, or None if none found.
polygon (attribute)
Section titled “polygon (attribute)”polygon: List[Tuple[float, float]]Get polygon coordinates if available, otherwise return rectangle corners.
prev( selector: Optional[str] = None, limit: int = 10, apply_exclusions: bool = True, **kwargs,) -> Optional['Element']Find previous element in reading order.
Parameters:
- selector (
Optional[str]) – Optional selector to filter by - limit (
int) – Maximum number of elements to search through (default: 10) - apply_exclusions (
bool) – Whether to apply exclusion regions (default: True) - **kwargs – Additional parameters for selector filtering (e.g., regex, case)
Returns:
- (
Optional['Element']) – Previous element or None if not found
render
Section titled “render”render( *, resolution: Optional[float] = None, width: Optional[int] = None, highlights: Optional[Union[List[Dict[str, Any]], bool]] = None, labels: bool = False, label_format: Optional[str] = None, render_ocr: bool = False, layout: Literal['stack', 'grid', 'single'] = 'stack', stack_direction: Literal['vertical', 'horizontal'] = 'vertical', gap: int = 5, columns: Optional[int] = None, crop: Union[bool, int, str, 'Region', Literal['wide']] = False, crop_bbox: Optional[Tuple[float, float, float, float]] = None, **kwargs,) -> Optional[PILImage]Generate a clean image, with optional explicit highlights.
This method produces publication-ready images without any debugging annotations or persistent highlights.
Parameters:
- resolution (
Optional[float]) – DPI for rendering (default from global settings) - width (
Optional[int]) – Target width in pixels (overrides resolution) - highlights (
Optional[Union[List[Dict[str, Any]], bool]]) – Optional explicit highlight groups/specs to render - labels (
bool) – Whether to render a legend for explicit highlights - label_format (
Optional[str]) – Format string for generated highlight labels - render_ocr (
bool) – Whether to render OCR text overlay on the image - layout (
Literal['stack', 'grid', 'single']) – How to arrange multiple pages/regions - stack_direction (
Literal['vertical', 'horizontal']) – Direction for stack layout - gap (
int) – Pixels between stacked images - columns (
Optional[int]) – Number of columns for grid layout - crop (
Union[bool, int, str, 'Region', Literal['wide']]) – Cropping mode (False, True, int for padding, ‘wide’, or Region) - crop_bbox (
Optional[Tuple[float, float, float, float]]) – Explicit crop bounds - **kwargs – Additional parameters passed to rendering
Returns:
- (
Optional[PILImage]) – PIL Image object or None if nothing to render
right( width: Optional[float] = None, height: str = 'element', include_source: bool = False, until: Optional[str] = None, include_endpoint: bool = True, offset: Optional[float] = None, apply_exclusions: bool = True, multipage: Optional[bool] = None, within: Optional['Region'] = None, anchor: str = 'start', **kwargs,) -> Optional[Union['Region', 'FlowRegion']]Select region to the right of this element/region.
Parameters:
- width (
Optional[float]) – Width of the region to the right, in points - height (
str) – Height mode - “element” (default) for element height or “full” for full page height - include_source (
bool) – Whether to include this element/region in the result (default: False) - until (
Optional[str]) – Optional selector string to specify a right boundary element - include_endpoint (
bool) – Whether to include the boundary element in the region (default: True) - offset (
Optional[float]) – Pixel offset when excluding source/endpoint (default: None, uses natural_pdf.options.layout.directional_offset) - apply_exclusions (
bool) – Whether to respect exclusions when using ‘until’ selector (default: True) - multipage (
Optional[bool]) – If True, allows the region to span multiple pages. Returns FlowRegion if the result spans multiple pages, Region otherwise (default: None uses global option) - within (
Optional['Region']) – Optional region to constrain the result to (default: None) - anchor (
str) – Reference point - ‘start’ (default), ‘center’, ‘end’, or explicit edges like ‘left’, ‘right’ - **kwargs – Additional parameters
Returns:
- (
Optional[Union['Region', 'FlowRegion']]) – Region object representing the area to the right, or None if within constraint has no overlap
Examples:
```python# Default: matches element heightlabel.right() # Gets region to the right at same height as label
# Full page heightlabel.right(height='full') # Gets entire right side of page
# Custom heightlabel.right(height=50) # Gets 50pt tall region to the right<a id="natural_pdf.elements.rect.RectangleElement.save"></a>
#### `save`
```pythonsave( filename: str, resolution: Optional[float] = None, labels: bool = True, legend_position: str = 'right',) -> 'Element'Save the page with this element highlighted to an image file.
Parameters:
- filename (
str) – Path to save the image to - resolution (
Optional[float]) – Resolution in DPI for rendering (default: uses global options, fallback to 144 DPI) - labels (
bool) – Whether to include a legend for labels - legend_position (
str) – Position of the legend
Returns:
- (
'Element') – Self for method chaining
selector_flow
Section titled “selector_flow”selector_flow() -> Anyselector_page
Section titled “selector_page”selector_page() -> Anyselector_region
Section titled “selector_region”selector_region() -> Anyservices (attribute)
Section titled “services (attribute)”services: ServiceNamespaceshow( *, resolution: Optional[float] = None, width: Optional[int] = None, color: Optional[Union[str, Tuple[int, int, int]]] = None, labels: bool = True, label_format: Optional[str] = None, highlights: Optional[Union[List[Dict[str, Any]], bool]] = None, legend_position: str = 'right', annotate: Optional[Union[str, List[str]]] = None, render_ocr: bool = False, layout: Optional[Literal['stack', 'grid', 'single']] = None, stack_direction: Literal['vertical', 'horizontal'] = 'vertical', gap: int = 5, columns: Optional[int] = 6, limit: Optional[int] = 30, crop: Union[bool, int, str, 'Region', Literal['wide']] = False, crop_bbox: Optional[Tuple[float, float, float, float]] = None, **kwargs,) -> Optional[PILImage]Generate a preview image with highlights.
This method is for interactive debugging and visualization. Elements are highlighted to show what’s selected or being worked with.
Parameters:
- resolution (
Optional[float]) – DPI for rendering (default from global settings) - width (
Optional[int]) – Target width in pixels (overrides resolution) - color (
Optional[Union[str, Tuple[int, int, int]]]) – Default highlight color - labels (
bool) – Whether to show labels for highlights - label_format (
Optional[str]) – Format string for labels (e.g., “Element {index}”) - highlights (
Optional[Union[List[Dict[str, Any]], bool]]) – Additional highlight groups to show, or False to disable all highlights - legend_position (
str) – Position of legend/colorbar (‘right’, ‘left’, ‘top’, ‘bottom’) - annotate (
Optional[Union[str, List[str]]]) – Attribute name(s) to display on highlights (string or list) - render_ocr (
bool) – Whether to render OCR text overlay on the image - layout (
Optional[Literal['stack', 'grid', 'single']]) – How to arrange multiple pages/regions (defaults to ‘grid’ for multi-page, ‘single’ for single page) - stack_direction (
Literal['vertical', 'horizontal']) – Direction for stack layout - gap (
int) – Pixels between stacked images - columns (
Optional[int]) – Number of columns for grid layout (defaults to 6) - limit (
Optional[int]) – Maximum number of pages to display (default 30, None for all) - crop (
Union[bool, int, str, 'Region', Literal['wide']]) – Cropping mode: - False: No cropping (default) - True: Tight crop to element bounds - int: Padding in PDF points around element (crop bounds are computed in PDF coordinate space, then scaled by resolution) - ‘wide’: Full page width, cropped vertically to element - Region: Crop to the bounds of another region - crop_bbox (
Optional[Tuple[float, float, float, float]]) – Explicit crop bounds - **kwargs – Additional parameters passed to rendering
Returns:
- (
Optional[PILImage]) – PIL Image object or None if nothing to render
stroke (attribute)
Section titled “stroke (attribute)”stroke: TupleGet the stroke color of the rectangle (RGB tuple).
stroke_width (attribute)
Section titled “stroke_width (attribute)”stroke_width: floatGet the stroke width of the rectangle.
text (attribute)
Section titled “text (attribute)”text: strGet text content inside this rectangle (delegates to extract_text()).
to_llm
Section titled “to_llm”to_llm(**kwargs) -> strReturn an LLM-optimized text representation of this element.
to_region
Section titled “to_region”to_region()top (attribute)
Section titled “top (attribute)”top: floatTop y-coordinate.
type (attribute)
Section titled “type (attribute)”type: strElement type.
until( selector: str, include_endpoint: bool = True, width: str = 'element', *, text: Optional[Union[str, Sequence[str]]] = None, apply_exclusions: bool = True, regex: bool = False, case: bool = True, text_tolerance: Optional[Dict[str, Any]] = None, auto_text_tolerance: Optional[Dict[str, Any]] = None, reading_order: bool = True,) -> 'Region'Select content from this element until matching selector.
Parameters:
- selector (
str) – CSS-like selector string - include_endpoint (
bool) – Whether to include the endpoint element in the region (default: True) - width (
str) – Width mode - “element” to use element widths or “full” for full page width - text (
Optional[Union[str, Sequence[str]]]) – Optional text shortcut passed topage.find. - apply_exclusions (
bool) – Whether to honour exclusion zones during the lookup. - regex (
bool) – Whether text matching should use regular expressions. - case (
bool) – Whether text matching should be case-sensitive. - text_tolerance (
Optional[Dict[str, Any]]) – Optional tolerance overrides for text matching. - auto_text_tolerance (
Optional[Dict[str, Any]]) – Optional overrides for automatic tolerance. - reading_order (
bool) – Whether matches should be sorted in reading order when relevant.
Returns:
- (
'Region') – Region object representing the selected content
update_ocr
Section titled “update_ocr”update_ocr(*args, **kwargs)update_text
Section titled “update_text”update_text(*args, **kwargs)width (attribute)
Section titled “width (attribute)”width: floatElement width.
x0 (attribute)
Section titled “x0 (attribute)”x0: floatLeft x-coordinate.
x1 (attribute)
Section titled “x1 (attribute)”x1: floatRight x-coordinate.
ElementCollection
Section titled “ElementCollection”Bases: SelectedTextMixin, OCRScopeMixin, Generic[T], ServiceHostMixin, ApplyMixin, ExportMixin, ClassificationBatchMixin, DirectionalCollectionMixin, Visualizable, MutableSequence[T]
ElementCollection(elements: List[T], *, context: Optional[PDFContext] = None)Collection of PDF elements with batch operations.
ElementCollection provides a powerful interface for working with groups of PDF elements (text, rectangles, lines, etc.) with batch processing capabilities. It implements the MutableSequence protocol for list-like behavior while adding specialized functionality for document analysis workflows.
The collection integrates multiple capabilities through mixins:
- Batch processing with .apply() method
- Export functionality for various formats
- AI-powered classification of element groups
- Spatial navigation for creating related regions
- Description and inspection capabilities
- Element filtering and selection
Collections support functional programming patterns and method chaining, making it easy to build complex document processing pipelines.
Attributes:
- elements (
List[T]) – List of Element objects in the collection. - first (
Optional[T]) – First element in the collection (None if empty). - last (
Optional[T]) – Last element in the collection (None if empty).
Example:
Basic usage:```pythonpdf = npdf.PDF("document.pdf")page = pdf.pages[0]
# Get collections of elementsall_text = page.charsheaders = page.find_all('text[size>12]:bold')
# Collection operationsprint(f"Found {len(headers)} headers")header_text = headers.get_text()
# Batch processingresults = headers.apply(lambda el: el.fontname)Advanced workflows:
# Functional programming styleimportant_text = (page.chars .filter('text:contains("IMPORTANT")') .apply(lambda el: el.text.upper()) .classify("urgency_level"))
# Spatial navigation from collectionscontent_region = headers.below(until='rect[height>2]')
# Export functionalityheaders.save_pdf("headers_only.pdf")> **Note:**> Collections are typically created by page methods (page.chars, page.find_all())> or by filtering existing collections. Direct instantiation is less common.
Initialize a collection of elements.
Creates an ElementCollection that wraps a list of PDF elements and providesenhanced functionality for batch operations, filtering, and analysis.
**Parameters:**
- **elements** (`List[T]`) – List of Element objects (TextElement, RectangleElement, etc.) to include in the collection. Can be empty for an empty collection.
**Example:**
```python```python# Collections are usually created by page methodschars = page.chars # ElementCollection[TextElement]rects = page.rects # ElementCollection[RectangleElement]
# Direct creation (advanced usage)selected_elements = ElementCollection([element1, element2, element3])> **Note:**> ElementCollection implements MutableSequence, so it behaves like a list> with additional natural-pdf functionality for document processing.
<a id="natural_pdf.elements.element_collection.ElementCollection.above"></a>
#### `above`
```pythonabove(*args, **kwargs) -> ElementCollectionapply(self: Any, func: Callable[..., Any], *args: Any, **kwargs: Any) -> Anyapply_ocr
Section titled “apply_ocr”apply_ocr( engine: Optional[str] = None, *, options: Optional[Any] = None, languages: Optional[list[str]] = None, min_confidence: Optional[float] = None, device: Optional[str] = None, resolution: Optional[int] = None, detect_only: bool = False, apply_exclusions: bool = True, replace: OCRReplaceMode = 'ocr', use_cache: bool = True, model: Optional[str] = None, client: Optional[Any] = None, prompt: Optional[str] = None, instructions: Optional[str] = None, max_new_tokens: Optional[int] = None, layout: Optional[bool | str] = None, preserve_markup: bool = False, function: Optional[CustomOCRCallable] = None, source_label: str = 'custom-ocr', confidence: Optional[float] = None,) -> SelfApply OCR within this object’s spatial scope and return self.
This method has three validated modes:
- recognition (the default) recognizes text with a registered engine;
detect_only=Truerefreshes persistent text bounding boxes without deleting native or recognized text;function=recognizes text with a callable receiving each physical Region in the scope.
Parameters:
- engine (
Optional[str]) – Registered OCR engine name. When omitted, resolve the context default. Supplyingmodelorclientselects VLM OCR when no engine is named. - options (
Optional[Any]) – Typed engine-specific options object or validated mapping. - languages (
Optional[list[str]]) – Ordered language codes such as["en", "fr"]. - min_confidence (
Optional[float]) – Minimum accepted confidence between 0 and 1. - device (
Optional[str]) – Requested compute device, such as"cpu"or"cuda". - resolution (
Optional[int]) – Render resolution in DPI. - detect_only (
bool) – Refresh detection-only spatial artifacts instead of recognizing text. Detection preserves existing text. - apply_exclusions (
bool) – Mask configured exclusions in pixels sent to OCR. - replace (
OCRReplaceMode) – Recognition/function replacement policy:"ocr","all", or"none". Detection has its own refresh policy. - use_cache (
bool) – Allow the persistent OCR result cache when its identity can be proven safe. - model (
Optional[str]) – VLM model name. - client (
Optional[Any]) – OpenAI-compatible VLM client. - prompt (
Optional[str]) – Complete VLM prompt overriding the generated prompt. - instructions (
Optional[str]) – Additional VLM instructions. - max_new_tokens (
Optional[int]) – VLM generation limit. - layout (
Optional[bool | str]) – VLM layout mode (bool or registered detector name). - preserve_markup (
bool) – Preserve raw VLM markup in text metadata. - function (
Optional[CustomOCRCallable]) – Custom callable receiving a physical Region and returning recognized text orNone. It cannot be combined with engine, VLM, cache, exclusion, or detection controls. - source_label (
str) – Provenance label stored asocr_engineon custom-function output. Its selector-visible source remains"ocr"like every other OCR artifact. - confidence (
Optional[float]) – Confidence assigned to custom-function OCR text.
Returns:
- (
Self) – The receiving object for fluent chaining.
Raises:
- (
TypeError) – An argument has the wrong type orfunctionis not callable. - (
ValueError) – Mode-specific arguments conflict or a value is invalid.
attr(self: Any, name: str, skip_empty: bool = True) -> List[Any]below(*args, **kwargs) -> ElementCollectionclassify_all
Section titled “classify_all”classify_all( labels: List[str], *, model: Optional[str] = None, using: Optional[str] = None, min_confidence: float = 0.0, analysis_key: str = 'classification', multi_label: bool = False, batch_size: int = 8, progress_bar: bool = True, **kwargs,)clip( obj: Optional[Any] = None, left: Optional[float] = None, top: Optional[float] = None, right: Optional[float] = None, bottom: Optional[float] = None,) -> ElementCollectionClip each element in the collection to the specified bounds.
This method applies the clip operation to each individual element, returning a new collection with the clipped elements.
Parameters:
- obj (
Optional[Any]) – Optional object with bbox properties (Region, Element, TextElement, etc.) - left (
Optional[float]) – Optional left boundary (x0) to clip to - top (
Optional[float]) – Optional top boundary to clip to - right (
Optional[float]) – Optional right boundary (x1) to clip to - bottom (
Optional[float]) – Optional bottom boundary to clip to
Returns:
- (
ElementCollection) – New ElementCollection containing the clipped elements
Examples:
# Clip each element to another region's boundsclipped_elements = collection.clip(container_region)
# Clip each element to specific coordinatesclipped_elements = collection.clip(left=100, right=400)
# Mix object bounds with specific overridesclipped_elements = collection.clip(obj=container, bottom=page.height/2)combine
Section titled “combine”combine( padding: float = 2.0, *, vertical_gap: Optional[float] = None, vertical: Optional[bool] = False, geometry: Literal['rect', 'polygon'] = 'rect', group_by: Optional[List[str]] = None,) -> ElementCollectionAlias for :py:meth:dissolve – retained for discoverability.
Many users find the verb combine more intuitive than dissolve when
merging nearby or stacked elements into unified Regions. The parameters
are identical; see :py:meth:dissolve for full documentation.
correct_ocr
Section titled “correct_ocr”correct_ocr(transform: Callable[[Any], Optional[str]]) -> ElementCollection[T]Applies corrections to OCR-generated text elements within this collection
using a user-provided callback function, executed
in parallel if max_workers is specified.
Iterates through elements currently in the collection. If an element’s
‘source’ attribute starts with ‘ocr’, it calls the transform
for that element, passing the element itself.
The transform should contain the logic to:
- Determine if the element needs correction.
- Perform the correction (e.g., call an LLM).
- Return the new text (
str) orNone.
If the callback returns a string, the element’s .text is updated in place.
Metadata updates (source, confidence, etc.) should happen within the callback.
Elements without a source starting with ‘ocr’ are skipped.
Parameters:
- transform (
Callable[[Any], Optional[str]]) – A function accepting an element and returningOptional[str](new text or None).
Returns:
- (
ElementCollection[T]) – Self for method chaining.
describe
Section titled “describe”describe(*args, **kwargs)detect_checkboxes
Section titled “detect_checkboxes”detect_checkboxes(*args, show_progress: bool = False, **kwargs) -> ElementCollectionDetect checkboxes on all applicable elements in the collection.
This method iterates through elements and calls detect_checkboxes on those that support it (Pages and Regions).
Parameters:
- *args – Positional arguments to pass to detect_checkboxes.
- show_progress (
bool) – Whether to show a progress bar during processing. - **kwargs – Keyword arguments to pass to detect_checkboxes.
Returns:
- (
ElementCollection) – A new ElementCollection containing all detected checkbox regions.
dissolve
Section titled “dissolve”dissolve( padding: float = 2.0, *, vertical_gap: Optional[float] = None, vertical: Optional[bool] = False, geometry: Literal['rect', 'polygon'] = 'rect', group_by: Optional[List[str]] = None,) -> ElementCollectionMerge connected elements based on proximity and grouping attributes.
This method groups elements by specified attributes (if any), then finds connected components within each group based on a proximity threshold. Connected elements are merged by creating new Region objects with merged bounding boxes.
Parameters:
- padding (
float) – Maximum chebyshev distance (in any direction) between elements to consider them connected whenvertical_gapis not provided. Default 2.0 pt. - vertical_gap (
Optional[float]) – If given, switches to stack-aware dissolve: two elements are connected when their horizontal projections overlap (any amount) and the vertical distance between them is ≤vertical_gap. This lets you combine multi-line labels that share the same column but have blank space between lines. - vertical (
Optional[bool]) – If given, automatically sets vertical_gap to maximum to allow for easy vertical stacking. - geometry (
Literal['rect', 'polygon']) – Type of geometry to use for merged regions. Currently only “rect” (bounding box) is supported. “polygon” will raise NotImplementedError. - group_by (
Optional[List[str]]) – List of attribute names to group elements by before merging. Elements are grouped by exact attribute values (floats are rounded to 2 decimal places). If None, all elements are considered in the same group. Common attributes include ‘size’ (for TextElements), ‘font_family’, ‘fontname’, etc.
Returns:
- (
ElementCollection) – New ElementCollection containing the dissolved regions. All elements - (
ElementCollection) – with bbox attributes are processed and converted to Region objects.
Example:
```python# Dissolve elements that are close togetherdissolved = elements.dissolve(padding=5.0)
# Group by font size before dissolvingdissolved = elements.dissolve(padding=2.0, group_by=['size'])
# Group by multiple attributesdissolved = elements.dissolve( padding=3.0, group_by=['size', 'font_family'])> **Note:**> - All elements with bbox attributes are processed> - Float attribute values are rounded to 2 decimal places for grouping> - The method uses Chebyshev distance (max of dx, dy) for proximity> - Merged regions inherit the page from the first element in each group> - Output is always Region objects, regardless of input element types
<a id="natural_pdf.elements.element_collection.ElementCollection.elements"></a>
#### `elements` *(attribute)*
```pythonelements: List[T]Get the elements in this collection.
endpoints (attribute)
Section titled “endpoints (attribute)”endpoints: ElementCollectionGet the boundary elements from regions created with ‘until’ selectors.
When a collection contains regions created using directional navigation with an ‘until’ parameter, this property returns a collection of the elements that matched those selectors and defined the boundaries.
Returns:
- (
ElementCollection) – ElementCollection containing the endpoint elements. Elements without - (
ElementCollection) – an endpoint (no ‘until’ was specified or no match was found) are skipped.
Example:
```python# Find headers above multiple price elementsprices = page.find_all('text:contains("$")')regions = prices.above(until='text[size>14]')headers = regions.endpoints # All the header elements<a id="natural_pdf.elements.element_collection.ElementCollection.exclude"></a>
#### `exclude`
```pythonexclude()Excludes all elements in the collection from their respective pages.
Since a collection can span multiple pages, this method iterates through all elements and calls exclude() on each one individually.
Each element type is handled appropriately:
- Region elements exclude everything within their bounds
- Text/other elements exclude only the specific element, not the area
Returns:
- Self for method chaining
exclude_regions
Section titled “exclude_regions”exclude_regions(regions: List[Region]) -> ElementCollection[T]Remove elements that are within any of the specified regions.
Parameters:
- regions (
List[Region]) – List of Region objects to exclude
Returns:
- (
ElementCollection[T]) – New ElementCollection with filtered elements
expand
Section titled “expand”expand(self: _SupportsApply, *args: Any, **kwargs: Any) -> 'ElementCollection'export
Section titled “export”export( path: Union[str, Path], *, resolution: Optional[float] = None, width: Optional[int] = None, layout: Literal['stack', 'grid', 'single'] = 'stack', stack_direction: Literal['vertical', 'horizontal'] = 'vertical', gap: int = 5, columns: Optional[int] = None, crop: Union[bool, Literal['content']] = False, crop_bbox: Optional[Tuple[float, float, float, float]] = None, format: Optional[str] = None, **kwargs,) -> NoneExport a clean image to file.
This is a convenience method that renders and saves in one step.
Parameters:
- path (
Union[str, Path]) – Output file path - resolution (
Optional[float]) – DPI for rendering - width (
Optional[int]) – Target width in pixels - layout (
Literal['stack', 'grid', 'single']) – How to arrange multiple pages/regions - stack_direction (
Literal['vertical', 'horizontal']) – Direction for stack layout - gap (
int) – Pixels between stacked images - columns (
Optional[int]) – Number of columns for grid layout - crop (
Union[bool, Literal['content']]) – Cropping mode (False, True, int for padding, ‘wide’, or Region) - crop_bbox (
Optional[Tuple[float, float, float, float]]) – Explicit crop bounds - format (
Optional[str]) – Image format (inferred from path if not specified) - **kwargs – Additional parameters passed to rendering
export_analyses
Section titled “export_analyses”export_analyses( output_path: Union[str, Path], analysis_keys: Union[str, List[str]], format: str = 'json', include_content: bool = True, include_images: bool = False, image_dir: Optional[Union[str, Path]] = None, image_format: str = 'jpg', image_resolution: int = 72, overwrite: bool = True, **kwargs,) -> strExport analysis results to a file.
Parameters:
- output_path (
Union[str, Path]) – Path to save the export file - analysis_keys (
Union[str, List[str]]) – Key(s) in the analyses dictionary to export - format (
str) – Export format (‘json’, ‘csv’, ‘excel’) - include_content (
bool) – Whether to include extracted text - include_images (
bool) – Whether to export images of elements - image_dir (
Optional[Union[str, Path]]) – Directory to save images (created if doesn’t exist) - image_format (
str) – Format to save images (‘jpg’, ‘png’) - image_resolution (
int) – Resolution for exported images - overwrite (
bool) – Whether to overwrite existing files - **kwargs – Additional format-specific options
Returns:
- (
str) – Path to the exported file
extract_each_text
Section titled “extract_each_text”extract_each_text( order: Optional[Union[str, Callable[[T], Any]]] = None, *, newlines: Union[bool, str] = True, whitespace: WhitespaceMode = 'preserve', strip: bool = True, content_filter: Optional[ContentFilter] = None, default: Optional[str] = None,) -> List[Optional[str]]Return a list with the extracted text for every element.
Parameters
Section titled “Parameters”order Controls the ordering of elements before extraction:
* ``None`` (default) – keep the collection's current order.* ``callable`` – a function that will be used as ``key`` for :pyfunc:`sorted`.* ``"ltr"`` – left-to-right ordering (x0, then y-top).* ``"rtl"`` – right-to-left ordering (−x0, then y-top).* ``"natural"`` – natural reading order (y-top, then x0).default
Value to use when an element is None or has no text. This is useful
when the collection was built with find(..., default=None) and you
want to preserve the list length with placeholder values (e.g., "").
Text options use the same literal-selection semantics as
:meth:extract_text; unsupported host-family options are rejected by
this explicit signature.
extract_text
Section titled “extract_text”extract_text( *, separator: str = ' ', newlines: bool | str = True, whitespace: WhitespaceMode = 'preserve', strip: bool = True, content_filter: ContentFilter | None = None,) -> strJoin selected textual contributions literally in stored order.
Empty and non-text contributions are omitted. Duplicate selections are retained. Each contribution is transformed independently, so filters cannot match across element boundaries and separators are unchanged.
extract_text_result
Section titled “extract_text_result”extract_text_result(*, separator: str = ' ') -> ExtractedTextJoin nonempty selected raw results with exact source offsets.
filter
Section titled “filter”filter(self: Any, predicate: Callable[[Any], bool]) -> Anyfind( selector: Optional[str] = None, *, text: Optional[Union[str, Sequence[str]]] = None, overlap: Optional[str] = None, apply_exclusions: bool = True, regex: bool = False, case: bool = True, text_tolerance: Optional[Dict[str, Any]] = None, auto_text_tolerance: Optional[Union[bool, Dict[str, Any]]] = None, reading_order: bool = True, near_threshold: Optional[float] = None, engine: Optional[str] = None, default: Any = _NO_DEFAULT,) -> ElementCollectionFind the first matching element below each item in the collection.
Parameters:
- selector (
Optional[str]) – CSS-like selector string understood by descendant find methods. - text (
Optional[Union[str, Sequence[str]]]) – Text shortcut equivalent toselector='text:contains(...)'. Accepts a single string or an iterable of strings. - overlap (
Optional[str]) – Optional overlap handling forwarded to region/pagefindhelpers. When the downstream implementation does not accept the argument the call will retry without it. - apply_exclusions (
bool) – Whether exclusion regions should be honoured (default: True). - regex (
bool) – Whether to interpret text filters as regular expressions (default: False). - case (
bool) – Whether text comparisons should be case-sensitive (default: True). - text_tolerance (
Optional[Dict[str, Any]]) – Optional mapping of pdfplumber-style tolerance overrides applied while resolving matches. - auto_text_tolerance (
Optional[Union[bool, Dict[str, Any]]]) – Optional overrides for automatic tolerance behaviour. - reading_order (
bool) – Whether matches are resolved in natural reading order (default: True). - near_threshold (
Optional[float]) – Maximum distance (in points) used by the:nearpseudo-class. - engine (
Optional[str]) – Optional selector engine name registered with the selector provider. - default (
Any) – If provided, include this value in results when no match is found for an element. This preserves the collection length, making it safe to use withextract_each_text(). Common usage:default=None.
Returns:
- (
ElementCollection) – An ElementCollection built from the first match (if any) discovered beneath each element. - (
ElementCollection) – Ifdefaultis provided, the result will have the same length as the input collection.
find_all
Section titled “find_all”find_all( selector: Optional[str] = None, *, text: Optional[Union[str, Sequence[str]]] = None, overlap: Optional[str] = None, apply_exclusions: bool = True, regex: bool = False, case: bool = True, text_tolerance: Optional[Dict[str, Any]] = None, auto_text_tolerance: Optional[Union[bool, Dict[str, Any]]] = None, reading_order: bool = True, near_threshold: Optional[float] = None, engine: Optional[str] = None,) -> ElementCollectionFind all matching elements for every item in the collection and flatten the results.
Provide EITHER selector OR text, but not both.
Parameters:
- selector (
Optional[str]) – CSS-like selector string. - text (
Optional[Union[str, Sequence[str]]]) – Text content to search for (equivalent to ‘text:contains(…)’). Accepts a single string or an iterable of strings (matches any value). - overlap (
Optional[str]) – How to determine if elements overlap: ‘full’ (fully inside), ‘partial’ (any overlap), or ‘center’ (center point inside). Defaults to “full” when omitted. - apply_exclusions (
bool) – Whether to apply exclusion regions (default: True). - regex (
bool) – Whether to use regex for text search (selectorortext) (default: False). - case (
bool) – Whether to do case-sensitive text search (selectorortext) (default: True). - text_tolerance (
Optional[Dict[str, Any]]) – Optional mapping of tolerance overrides applied during selection. - auto_text_tolerance (
Optional[Union[bool, Dict[str, Any]]]) – Optional overrides for automatic tolerance behaviour. - reading_order (
bool) – Whether to order results according to natural reading order (default: True). - near_threshold (
Optional[float]) – Maximum distance (in points) used by the:nearpseudo-class. - engine (
Optional[str]) – Optional selector engine name registered with the selector provider.
Returns:
- (
ElementCollection) – A new ElementCollection containing all matching sub-elements from all elements - (
ElementCollection) – in this collection.
first (attribute)
Section titled “first (attribute)”first: Optional[T]Get the first element in the collection.
get_rendering_service
Section titled “get_rendering_service”get_rendering_service()Public accessor for the rendering service (primarily for tests).
highest
Section titled “highest”highest() -> Optional[T]Get element with the smallest top y-coordinate (highest on page).
Raises:
- (
ValueError) – If elements are on multiple pages or multiple PDFs
Returns:
- (
Optional[T]) – Element with smallest top value or None if empty
highlight
Section titled “highlight”highlight( label: Optional[str] = None, color: Optional[Union[Tuple, str]] = None, group_by: Optional[str] = None, label_format: Optional[str] = None, distinct: bool = False, annotate: Optional[List[str]] = None, replace: bool = False, bins: Optional[Union[int, List[float]]] = None,) -> Optional[Image.Image]Adds persistent highlights for all elements in the collection to the page via the HighlightingService.
By default, this APPENDS highlights to any existing ones on the page.
To replace existing highlights, set replace=True.
Uses grouping logic based on parameters (defaulting to grouping by type).
Note: Elements must be from the same PDF for this operation to work properly, as each PDF has its own highlighting service.
Parameters:
- label (
Optional[str]) – Optional explicit label for the entire collection. If provided, all elements are highlighted as a single group with this label, ignoring ‘group_by’ and the default type-based grouping. - color (
Optional[Union[Tuple, str]]) – Optional explicit color for the highlight (tuple/string), or matplotlib colormap name for quantitative group_by (e.g., ‘viridis’, ‘plasma’, ‘inferno’, ‘coolwarm’, ‘RdBu’). Applied consistently if ‘label’ is provided or if grouping occurs. - group_by (
Optional[str]) – Optional attribute name present on the elements. If provided (and ‘label’ is None), elements will be grouped based on the value of this attribute, and each group will be highlighted with a distinct label and color. Automatically detects quantitative data and uses gradient colormaps when appropriate. - label_format (
Optional[str]) – Optional Python f-string to format the group label when ‘group_by’ is used. Can reference element attributes (e.g., “Type: {region_type}, Conf: {confidence:.2f}”). If None, the attribute value itself is used as the label. - distinct (
bool) – If True, bypasses all grouping and highlights each element individually with cycling colors (the previous default behavior). (default: False) - annotate (
Optional[List[str]]) – List of attribute names from the element to display directly on the highlight itself (distinct from group label). - replace (
bool) – If True, existing highlights on the affected page(s) are cleared before adding these highlights. If False (default), highlights are appended to existing ones. - bins (
Optional[Union[int, List[float]]]) – Optional binning specification for quantitative data when using group_by. Can be an integer (number of equal-width bins) or a list of bin edges. Only used when group_by contains quantitative data.
Raises:
- (
AttributeError) – If ‘group_by’ is provided but the attribute doesn’t exist on some elements. - (
ValueError) – If ‘label_format’ is provided but contains invalid keys for element attributes, or if elements span multiple PDFs.
insert
Section titled “insert”insert(index: int, value: T) -> Noneinspect
Section titled “inspect”inspect(*args, **kwargs)last (attribute)
Section titled “last (attribute)”last: Optional[T]Get the last element in the collection.
left(*args, **kwargs) -> ElementCollectionleftmost
Section titled “leftmost”leftmost() -> Optional[T]Get element with the smallest x0 coordinate (leftmost on page).
Raises:
- (
ValueError) – If elements are on multiple pages or multiple PDFs
Returns:
- (
Optional[T]) – Element with smallest x0 value or None if empty
lowest
Section titled “lowest”lowest() -> Optional[T]Get element with the largest bottom y-coordinate (lowest on page).
Raises:
- (
ValueError) – If elements are on multiple pages or multiple PDFs
Returns:
- (
Optional[T]) – Element with largest bottom value or None if empty
map( self: Any, func: Callable[..., Any], *args: Any, skip_empty: bool = False, **kwargs: Any,) -> Anymerge() -> Union[Region, FlowRegion]Merge all elements into a single region encompassing their bounding box.
Unlike dissolve() which only connects touching elements, merge() creates a single region that spans from the minimum to maximum coordinates of all elements, regardless of whether they touch.
When elements span multiple pages, returns a FlowRegion with one constituent Region per page.
Returns:
- (
Union[Region, FlowRegion]) – A single Region (same page) or FlowRegion (cross-page)
Raises:
- (
ValueError) – If the collection is empty or elements have no valid bounding boxes
Example:
```python# Find scattered form fields and merge into one regionfields = pdf.find_all('text:contains(Name|Date|Phone)')merged_region = fields.merge()
# Extract all text from the merged areatext = merged_region.extract_text()<a id="natural_pdf.elements.element_collection.ElementCollection.merge_connected"></a>
#### `merge_connected`
```pythonmerge_connected( proximity_threshold: float = 5.0, merge_across_pages: bool = False, merge_non_regions: bool = False, text_separator: str = ' ', preserve_order: bool = True,) -> ElementCollectionMerge connected/adjacent regions in the collection into larger regions.
This method identifies regions that are adjacent or overlapping (within a proximity threshold) and merges them into single regions. This is particularly useful for handling text that gets split due to font variations, accented characters, or other PDF rendering quirks.
The method uses a graph-based approach (union-find) to identify connected components of regions and merges each component into a single region.
Parameters:
- proximity_threshold (
float) – Maximum distance in points between regions to consider them connected. Default is 5.0 points. Use 0 for only overlapping regions. - merge_across_pages (
bool) – If True, allow merging regions from different pages. Default is False (only merge within same page). - merge_non_regions (
bool) – If True, attempt to merge non-Region elements by converting them to regions first. Default is False (skip non-Region elements). - text_separator (
str) – String to use when joining text from merged regions. Default is a single space. - preserve_order (
bool) – If True, order merged text by reading order (top-to-bottom, left-to-right). Default is True.
Returns:
- (
ElementCollection) – New ElementCollection containing the merged regions. Non-Region elements - (
ElementCollection) – (if merge_non_regions=False) and elements that couldn’t be merged are - (
ElementCollection) – included unchanged.
Example:
```python# Find all text regions with potential splitstext_regions = page.find_all('region[type=text]')
# Merge adjacent regions (useful for accented characters)merged = text_regions.merge_connected(proximity_threshold=2.0)
# Extract clean text from merged regionsfor region in merged: print(region.extract_text())> **Note:**> - Regions are considered connected if their bounding boxes are within> proximity_threshold distance of each other> - The merged region's bbox encompasses all constituent regions> - Text content is combined in reading order> - Original metadata is preserved from the first region in each group
<a id="natural_pdf.elements.element_collection.ElementCollection.remove_from_pages"></a>
#### `remove_from_pages`
```pythonremove_from_pages() -> intRemove all elements in this collection from their respective pages.
This method removes elements from their respective pages via the public element APIs. It’s particularly useful for removing OCR elements before applying new OCR.
Returns:
- int (
int) – Number of elements successfully removed
render
Section titled “render”render( *, resolution: Optional[float] = None, width: Optional[int] = None, highlights: Optional[Union[List[Dict[str, Any]], bool]] = None, labels: bool = False, label_format: Optional[str] = None, render_ocr: bool = False, layout: Literal['stack', 'grid', 'single'] = 'stack', stack_direction: Literal['vertical', 'horizontal'] = 'vertical', gap: int = 5, columns: Optional[int] = None, crop: Union[bool, int, str, 'Region', Literal['wide']] = False, crop_bbox: Optional[Tuple[float, float, float, float]] = None, **kwargs,) -> Optional[PILImage]Generate a clean image, with optional explicit highlights.
This method produces publication-ready images without any debugging annotations or persistent highlights.
Parameters:
- resolution (
Optional[float]) – DPI for rendering (default from global settings) - width (
Optional[int]) – Target width in pixels (overrides resolution) - highlights (
Optional[Union[List[Dict[str, Any]], bool]]) – Optional explicit highlight groups/specs to render - labels (
bool) – Whether to render a legend for explicit highlights - label_format (
Optional[str]) – Format string for generated highlight labels - render_ocr (
bool) – Whether to render OCR text overlay on the image - layout (
Literal['stack', 'grid', 'single']) – How to arrange multiple pages/regions - stack_direction (
Literal['vertical', 'horizontal']) – Direction for stack layout - gap (
int) – Pixels between stacked images - columns (
Optional[int]) – Number of columns for grid layout - crop (
Union[bool, int, str, 'Region', Literal['wide']]) – Cropping mode (False, True, int for padding, ‘wide’, or Region) - crop_bbox (
Optional[Tuple[float, float, float, float]]) – Explicit crop bounds - **kwargs – Additional parameters passed to rendering
Returns:
- (
Optional[PILImage]) – PIL Image object or None if nothing to render
right(*args, **kwargs) -> ElementCollectionrightmost
Section titled “rightmost”rightmost() -> Optional[T]Get element with the largest x1 coordinate (rightmost on page).
Raises:
- (
ValueError) – If elements are on multiple pages or multiple PDFs
Returns:
- (
Optional[T]) – Element with largest x1 value or None if empty
save( filename: str, resolution: Optional[float] = None, width: Optional[int] = None, labels: bool = True, legend_position: str = 'right', render_ocr: bool = False,) -> ElementCollectionSave the page with this collection’s elements highlighted to an image file.
Parameters:
- filename (
str) – Path to save the image to - resolution (
Optional[float]) – Resolution in DPI for rendering (uses global options if not specified, defaults to 144 DPI) - width (
Optional[int]) – Optional width for the output image in pixels - labels (
bool) – Whether to include a legend for labels - legend_position (
str) – Position of the legend - render_ocr (
bool) – Whether to render OCR text with white background boxes
Returns:
- (
ElementCollection) – Self for method chaining
save_pdf
Section titled “save_pdf”save_pdf(path: str, method: str = 'crop') -> ElementCollectionSave each element in this collection as a page in a PDF file.
Each element’s bounding box on its page becomes one page in the output PDF. Elements without a page or bbox are skipped with a warning.
Parameters:
- path (
str) – Output file path for the PDF. - method (
str) – ‘crop’ (default) sets CropBox to element bounds. ‘whiteout’ keeps full pages but whites out areas outside each element.
Returns:
- (
ElementCollection) – Self for method chaining.
Raises:
- (
ValueError) – If the collection is empty or no valid elements found. - (
ImportError) – If pikepdf is not installed.
Examples:
```pythonheaders = page.find_all('text:bold[size>=14]')headers.save_pdf("headers.pdf")<a id="natural_pdf.elements.element_collection.ElementCollection.services"></a>
#### `services` *(attribute)*
```pythonservices: ServiceNamespaceshow( *, resolution: Optional[float] = None, width: Optional[int] = None, color: Optional[Union[str, Tuple[int, int, int]]] = None, labels: bool = True, label_format: Optional[str] = None, highlights: Optional[Union[List[Dict[str, Any]], bool]] = None, legend_position: str = 'right', annotate: Optional[Union[str, List[str]]] = None, render_ocr: bool = False, layout: Optional[Literal['stack', 'grid', 'single']] = None, stack_direction: Literal['vertical', 'horizontal'] = 'vertical', gap: int = 5, columns: Optional[int] = 6, limit: Optional[int] = 30, crop: Union[bool, int, str, 'Region', Literal['wide']] = False, crop_bbox: Optional[Tuple[float, float, float, float]] = None, **kwargs,) -> Optional[PILImage]Generate a preview image with highlights.
This method is for interactive debugging and visualization. Elements are highlighted to show what’s selected or being worked with.
Parameters:
- resolution (
Optional[float]) – DPI for rendering (default from global settings) - width (
Optional[int]) – Target width in pixels (overrides resolution) - color (
Optional[Union[str, Tuple[int, int, int]]]) – Default highlight color - labels (
bool) – Whether to show labels for highlights - label_format (
Optional[str]) – Format string for labels (e.g., “Element {index}”) - highlights (
Optional[Union[List[Dict[str, Any]], bool]]) – Additional highlight groups to show, or False to disable all highlights - legend_position (
str) – Position of legend/colorbar (‘right’, ‘left’, ‘top’, ‘bottom’) - annotate (
Optional[Union[str, List[str]]]) – Attribute name(s) to display on highlights (string or list) - render_ocr (
bool) – Whether to render OCR text overlay on the image - layout (
Optional[Literal['stack', 'grid', 'single']]) – How to arrange multiple pages/regions (defaults to ‘grid’ for multi-page, ‘single’ for single page) - stack_direction (
Literal['vertical', 'horizontal']) – Direction for stack layout - gap (
int) – Pixels between stacked images - columns (
Optional[int]) – Number of columns for grid layout (defaults to 6) - limit (
Optional[int]) – Maximum number of pages to display (default 30, None for all) - crop (
Union[bool, int, str, 'Region', Literal['wide']]) – Cropping mode: - False: No cropping (default) - True: Tight crop to element bounds - int: Padding in PDF points around element (crop bounds are computed in PDF coordinate space, then scaled by resolution) - ‘wide’: Full page width, cropped vertically to element - Region: Crop to the bounds of another region - crop_bbox (
Optional[Tuple[float, float, float, float]]) – Explicit crop bounds - **kwargs – Additional parameters passed to rendering
Returns:
- (
Optional[PILImage]) – PIL Image object or None if nothing to render
sort( key: Optional[Callable[[T], Any]] = None, reverse: bool = False,) -> ElementCollection[T]Sort elements by the given key function.
Parameters:
- key (
Optional[Callable[[T], Any]]) – Function to generate a key for sorting - reverse (
bool) – Whether to sort in descending order
Returns:
- (
ElementCollection[T]) – Self for method chaining
to_llm
Section titled “to_llm”to_llm(**kwargs) -> strReturn an LLM-optimized text representation of this collection.
to_text_elements
Section titled “to_text_elements”to_text_elements( text_content_func: Optional[Callable[[Region], Optional[str]]] = None, source_label: str = 'derived_from_region', object_type: str = 'word', default_font_size: float = 10.0, default_font_name: str = 'RegionContent', confidence: Optional[float] = None, add_to_page: bool = False,) -> ElementCollection[TextElement]Converts each Region in this collection to a TextElement.
Parameters:
- text_content_func (
Optional[Callable[[Region], Optional[str]]]) – A callable that takes a Region and returns its text (or None). If None, all created TextElements will have text=None. - source_label (
str) – The ‘source’ attribute for the new TextElements. - object_type (
str) – The ‘object_type’ for the TextElement’s data dict. - default_font_size (
float) – Placeholder font size. - default_font_name (
str) – Placeholder font name. - confidence (
Optional[float]) – Confidence score. - add_to_page (
bool) – If True (default is False), also adds the created TextElements to their respective page’s element manager.
Returns:
- (
ElementCollection[TextElement]) – A new ElementCollection containing the created TextElement objects.
trim( padding: int = 1, threshold: float = 0.95, resolution: Optional[float] = None, show_progress: bool = True,) -> ElementCollectionTrim visual whitespace from each region in the collection.
Applies the trim() method to each element in the collection, returning a new collection with the trimmed regions.
Parameters:
- padding (
int) – Number of pixels to keep as padding after trimming (default: 1) - threshold (
float) – Threshold for considering a row/column as whitespace (0.0-1.0, default: 0.95) - resolution (
Optional[float]) – Resolution for image rendering in DPI (default: uses global options, fallback to 144 DPI) - show_progress (
bool) – Whether to show a progress bar for the trimming operation
Returns:
- (
ElementCollection) – New ElementCollection with trimmed regions
unique
Section titled “unique”unique(self: Any, key: Optional[Callable[[Any], Any]] = None) -> Anyviewer
Section titled “viewer”viewer() -> AnyCreates and returns an interactive viewer showing ONLY the elements in this collection on their page background.
Returns:
- (
Any) – An InteractiveViewerWidget instance.
Raises:
- (
ValueError) – If the collection is empty, its elements lack page context, or its elements span multiple pages.
FlowElementCollection
Section titled “FlowElementCollection”Bases: SelectedTextMixin, MutableSequence['FlowElement']
FlowElementCollection(flow_elements: Optional[Sequence[FlowElement]] = None)A collection of FlowElement objects, typically the result of Flow.find_all(). Provides directional methods that operate on its contained FlowElements and return FlowRegionCollection objects.
above( height: Optional[float] = None, width_ratio: Optional[float] = None, width_absolute: Optional[float] = None, width_alignment: str = 'center', until: Optional[str] = None, include_endpoint: bool = True, **kwargs,) -> FlowRegionCollectionbelow( height: Optional[float] = None, width_ratio: Optional[float] = None, width_absolute: Optional[float] = None, width_alignment: str = 'center', until: Optional[str] = None, include_endpoint: bool = True, **kwargs,) -> FlowRegionCollectionelements (attribute)
Section titled “elements (attribute)”elements: List[FlowElement]Expose the underlying FlowElements for service helpers.
extract_text
Section titled “extract_text”extract_text( *, separator: str = ' ', newlines: bool | str = True, whitespace: WhitespaceMode = 'preserve', strip: bool = True, content_filter: ContentFilter | None = None,) -> strJoin selected textual contributions literally in stored order.
Empty and non-text contributions are omitted. Duplicate selections are retained. Each contribution is transformed independently, so filters cannot match across element boundaries and separators are unchanged.
extract_text_result
Section titled “extract_text_result”extract_text_result(*, separator: str = ' ') -> ExtractedTextJoin nonempty selected raw results with exact source offsets.
first (attribute)
Section titled “first (attribute)”first: Optional[FlowElement]flow_elements (attribute)
Section titled “flow_elements (attribute)”flow_elements: List[FlowElement]from_physical (classmethod)
Section titled “from_physical (classmethod)”from_physical(flow: Flow, elements: Sequence[Any]) -> FlowElementCollectioninsert
Section titled “insert”insert(index: int, value: FlowElement) -> Nonelast (attribute)
Section titled “last (attribute)”last: Optional[FlowElement]left( width: Optional[float] = None, height_ratio: Optional[float] = None, height_absolute: Optional[float] = None, height_alignment: str = 'center', until: Optional[str] = None, include_endpoint: bool = True, **kwargs,) -> FlowRegionCollectionright( width: Optional[float] = None, height_ratio: Optional[float] = None, height_absolute: Optional[float] = None, height_alignment: str = 'center', until: Optional[str] = None, include_endpoint: bool = True, **kwargs,) -> FlowRegionCollectionshow( resolution: Optional[float] = None, labels: bool = True, legend_position: str = 'right', default_color: Optional[Union[Tuple, str]] = 'orange', label_prefix: Optional[str] = 'FEC_Element', width: Optional[int] = None, stack_direction: str = 'vertical', stack_gap: int = 5, stack_background_color: Tuple[int, int, int] = (255, 255, 255), **kwargs,) -> Optional[Image.Image]Shows all FlowElements in this collection by highlighting them on their respective pages. If multiple pages are involved, they are stacked into a single image.
FlowRegionCollection
Section titled “FlowRegionCollection”Bases: AggregateTextMixin, ServiceHostMixin, Visualizable, SectionsCollectionMixin, QACollectionMixin, MutableSequence['FlowRegion']
FlowRegionCollection(flow_regions: Optional[Sequence[FlowRegion]] = None)A collection of FlowRegion objects, typically the result of directional operations on a FlowElementCollection. Provides methods for querying and visualizing the aggregated content.
above( height: Optional[float] = None, width: str = 'full', include_source: bool = False, until: Optional[str] = None, include_endpoint: bool = True, offset: Optional[float] = None, apply_exclusions: bool = True, multipage: Optional[bool] = None, within: Optional[Any] = None, anchor: str = 'start', **kwargs,) -> FlowRegionCollectionapply(func: Callable[[FlowRegion], Any]) -> List[Any]ask(*args, **kwargs)below( height: Optional[float] = None, width: str = 'full', include_source: bool = False, until: Optional[str] = None, include_endpoint: bool = True, offset: Optional[float] = None, apply_exclusions: bool = True, multipage: Optional[bool] = None, within: Optional[Any] = None, anchor: str = 'start', **kwargs,) -> FlowRegionCollectionexport
Section titled “export”export( path: Union[str, Path], *, resolution: Optional[float] = None, width: Optional[int] = None, layout: Literal['stack', 'grid', 'single'] = 'stack', stack_direction: Literal['vertical', 'horizontal'] = 'vertical', gap: int = 5, columns: Optional[int] = None, crop: Union[bool, Literal['content']] = False, crop_bbox: Optional[Tuple[float, float, float, float]] = None, format: Optional[str] = None, **kwargs,) -> NoneExport a clean image to file.
This is a convenience method that renders and saves in one step.
Parameters:
- path (
Union[str, Path]) – Output file path - resolution (
Optional[float]) – DPI for rendering - width (
Optional[int]) – Target width in pixels - layout (
Literal['stack', 'grid', 'single']) – How to arrange multiple pages/regions - stack_direction (
Literal['vertical', 'horizontal']) – Direction for stack layout - gap (
int) – Pixels between stacked images - columns (
Optional[int]) – Number of columns for grid layout - crop (
Union[bool, Literal['content']]) – Cropping mode (False, True, int for padding, ‘wide’, or Region) - crop_bbox (
Optional[Tuple[float, float, float, float]]) – Explicit crop bounds - format (
Optional[str]) – Image format (inferred from path if not specified) - **kwargs – Additional parameters passed to rendering
extract_each_text
Section titled “extract_each_text”extract_each_text( *, layout: bool | TextLayoutOptions = False, apply_exclusions: bool = True, newlines: bool | str = True, whitespace: WhitespaceMode = 'preserve', strip: bool = True, bidi: bool = True, content_filter: ContentFilter | None = None,) -> List[str]Extract each section through the common spatial/aggregate leaf contract.
extract_table
Section titled “extract_table”extract_table(*args, **kwargs) -> List[TableResult]extract_tables
Section titled “extract_tables”extract_tables(*args, **kwargs) -> List[TableResult]extract_text
Section titled “extract_text”extract_text( *, separator: str | None = None, layout: bool | TextLayoutOptions = False, apply_exclusions: bool = True, newlines: bool | str = True, whitespace: WhitespaceMode = 'preserve', strip: bool = True, bidi: bool = True, content_filter: ContentFilter | None = None,) -> strExtract members independently, then join them at exact host boundaries.
separator=None uses the host’s natural separator. Empty member
handling is host policy. Transforms run on members only: separators are
never normalized, stripped, bidi-processed, or included in a regex match.
extract_text_result
Section titled “extract_text_result”extract_text_result( *, separator: str | None = None, layout: bool | TextLayoutOptions = False, apply_exclusions: bool = True,) -> ExtractedTextJoin raw member results with exact source offsets.
filter
Section titled “filter”filter(func: Callable[[FlowRegion], bool]) -> FlowRegionCollectionfind( selector: Optional[str] = None, *, text: Optional[Union[str, Sequence[str]]] = None, overlap: Optional[str] = None, apply_exclusions: bool = True, regex: bool = False, case: bool = True, text_tolerance: Optional[Dict[str, Any]] = None, auto_text_tolerance: Optional[Union[bool, Dict[str, Any]]] = None, reading_order: bool = True, near_threshold: Optional[float] = None, engine: Optional[str] = None,)find_all
Section titled “find_all”find_all( selector: Optional[str] = None, *, text: Optional[Union[str, Sequence[str]]] = None, overlap: Optional[str] = None, apply_exclusions: bool = True, regex: bool = False, case: bool = True, text_tolerance: Optional[Dict[str, Any]] = None, auto_text_tolerance: Optional[Union[bool, Dict[str, Any]]] = None, reading_order: bool = True, near_threshold: Optional[float] = None, engine: Optional[str] = None,)first (attribute)
Section titled “first (attribute)”first: Optional[FlowRegion]flow_regions (attribute)
Section titled “flow_regions (attribute)”flow_regions: List[FlowRegion]get_rendering_service
Section titled “get_rendering_service”get_rendering_service()Public accessor for the rendering service (primarily for tests).
highlight
Section titled “highlight”highlight( label_prefix: Optional[str] = 'FRC', color: Optional[Union[Tuple, str]] = None, **kwargs,) -> Optional[Image.Image]insert
Section titled “insert”insert(index: int, value: FlowRegion) -> Noneis_empty (attribute)
Section titled “is_empty (attribute)”is_empty: boollast (attribute)
Section titled “last (attribute)”last: Optional[FlowRegion]left( width: Optional[float] = None, height: str = 'element', include_source: bool = False, until: Optional[str] = None, include_endpoint: bool = True, offset: Optional[float] = None, apply_exclusions: bool = True, multipage: Optional[bool] = None, within: Optional[Any] = None, anchor: str = 'start', **kwargs,) -> FlowRegionCollectionrender
Section titled “render”render( *, resolution: Optional[float] = None, width: Optional[int] = None, highlights: Optional[Union[List[Dict[str, Any]], bool]] = None, labels: bool = False, label_format: Optional[str] = None, render_ocr: bool = False, layout: Literal['stack', 'grid', 'single'] = 'stack', stack_direction: Literal['vertical', 'horizontal'] = 'vertical', gap: int = 5, columns: Optional[int] = None, crop: Union[bool, int, str, 'Region', Literal['wide']] = False, crop_bbox: Optional[Tuple[float, float, float, float]] = None, **kwargs,) -> Optional[PILImage]Generate a clean image, with optional explicit highlights.
This method produces publication-ready images without any debugging annotations or persistent highlights.
Parameters:
- resolution (
Optional[float]) – DPI for rendering (default from global settings) - width (
Optional[int]) – Target width in pixels (overrides resolution) - highlights (
Optional[Union[List[Dict[str, Any]], bool]]) – Optional explicit highlight groups/specs to render - labels (
bool) – Whether to render a legend for explicit highlights - label_format (
Optional[str]) – Format string for generated highlight labels - render_ocr (
bool) – Whether to render OCR text overlay on the image - layout (
Literal['stack', 'grid', 'single']) – How to arrange multiple pages/regions - stack_direction (
Literal['vertical', 'horizontal']) – Direction for stack layout - gap (
int) – Pixels between stacked images - columns (
Optional[int]) – Number of columns for grid layout - crop (
Union[bool, int, str, 'Region', Literal['wide']]) – Cropping mode (False, True, int for padding, ‘wide’, or Region) - crop_bbox (
Optional[Tuple[float, float, float, float]]) – Explicit crop bounds - **kwargs – Additional parameters passed to rendering
Returns:
- (
Optional[PILImage]) – PIL Image object or None if nothing to render
right( width: Optional[float] = None, height: str = 'element', include_source: bool = False, until: Optional[str] = None, include_endpoint: bool = True, offset: Optional[float] = None, apply_exclusions: bool = True, multipage: Optional[bool] = None, within: Optional[Any] = None, anchor: str = 'start', **kwargs,) -> FlowRegionCollectionservices (attribute)
Section titled “services (attribute)”services: ServiceNamespaceshow( resolution: Optional[float] = None, labels: bool = True, legend_position: str = 'right', default_color: Optional[Union[Tuple, str]] = 'darkviolet', label_prefix: Optional[str] = 'FRC_Part', width: Optional[int] = None, stack_direction: Literal['vertical', 'horizontal'] = 'vertical', stack_gap: int = 5, stack_background_color: Tuple[int, int, int] = (255, 255, 255), **kwargs,) -> Optional[Image.Image]sort( key: Optional[Callable[[FlowRegion], Any]] = None, reverse: bool = False,) -> FlowRegionCollectionSorts the collection in-place. Default sort is by flow order if possible.
to_images
Section titled “to_images”to_images(resolution: float = 150, **kwargs) -> List[Image.Image]Returns a flat list of cropped images of all constituent physical regions.
FlowElement
Section titled “FlowElement”FlowElement(physical_object: Union[PhysicalElement, PhysicalRegion], flow: Flow)Represents a physical PDF Element or Region that is anchored within a Flow. This class provides methods for flow-aware directional navigation (e.g., below, above) that operate across the segments defined in its associated Flow.
Initializes a FlowElement.
Parameters:
- physical_object (
Union[PhysicalElement, PhysicalRegion]) – The actual natural_pdf.elements.base.Element or natural_pdf.elements.region.Region object. - flow (
Flow) – The Flow instance this element is part of.
above( height: Optional[float] = None, width_ratio: Optional[float] = None, width_absolute: Optional[float] = None, width_alignment: str = 'center', until: Optional[str] = None, include_source: bool = False, include_endpoint: bool = True, **kwargs,) -> FlowRegionbbox (attribute)
Section titled “bbox (attribute)”bbox: Tuple[float, float, float, float]below( height: Optional[float] = None, width_ratio: Optional[float] = None, width_absolute: Optional[float] = None, width_alignment: str = 'center', until: Optional[str] = None, include_source: bool = False, include_endpoint: bool = True, **kwargs,) -> FlowRegionbottom (attribute)
Section titled “bottom (attribute)”bottom: floatextract_text
Section titled “extract_text”extract_text() -> strReturn the underlying element text through an IDE-visible proxy.
flow (attribute)
Section titled “flow (attribute)”flow: Flow = flowheight (attribute)
Section titled “height (attribute)”height: floatleft( width: Optional[float] = None, height_ratio: Optional[float] = None, height_absolute: Optional[float] = None, height_alignment: str = 'center', until: Optional[str] = None, include_source: bool = False, include_endpoint: bool = True, **kwargs,) -> FlowRegionpage (attribute)
Section titled “page (attribute)”page: Optional[PhysicalPage]Returns the physical page of the underlying element.
physical_object (attribute)
Section titled “physical_object (attribute)”physical_object: Union[PhysicalElement, PhysicalRegion] = physical_objectright( width: Optional[float] = None, height_ratio: Optional[float] = None, height_absolute: Optional[float] = None, height_alignment: str = 'center', until: Optional[str] = None, include_source: bool = False, include_endpoint: bool = True, **kwargs,) -> FlowRegiontext (attribute)
Section titled “text (attribute)”text: Optional[str]top (attribute)
Section titled “top (attribute)”top: floatwidth (attribute)
Section titled “width (attribute)”width: floatx0 (attribute)
Section titled “x0 (attribute)”x0: floatx1 (attribute)
Section titled “x1 (attribute)”x1: float