How to Load a PDF Document from a File Path in pdf‑inspector
Use the process_pdf function in pdf‑inspector, which accepts any path‑like argument and returns structured Markdown output with metadata.
The pdf‑inspector library (firecrawl/pdf‑inspector) provides a streamlined API for loading and processing PDF files from the local filesystem. Whether you're working in Rust or Python, the entry point automatically handles file opening, PDF parsing, and content extraction without requiring manual byte handling.
The Core API for Loading PDFs from Paths
In src/lib.rs, the primary public function for loading PDFs is process_pdf. Its signature demonstrates the library's flexible path handling:
pub fn process_pdf<P: AsRef<Path>>(path: P) -> Result<PdfProcessResult, PdfError>
This generic implementation accepts &str, String, PathBuf, or any other type implementing AsRef<Path>. The function performs four operations internally:
- Opens the file at the provided path
- Reads the raw PDF bytes
- Runs the detection pipeline (
src/detector.rs) to determine PDF type - Executes extraction and returns
PdfProcessResultcontaining Markdown output, page count, and processing metadata
For callers requiring customization, process_pdf_with_options at src/lib.rs#L284 exposes additional parameters including OCR toggles, page selection, and detection‑only mode.
Rust Example: Loading a PDF from a File Path
use pdf_inspector::{process_pdf, PdfError};
fn main() -> Result<(), PdfError> {
// Absolute or relative path to the target PDF
let pdf_path = "documents/annual_report.pdf";
// Load and process the PDF in one call
let result = process_pdf(pdf_path)?;
// Access the extracted Markdown content
println!("{}", result.markdown);
// Inspect processing metadata
println!("Total pages: {}", result.page_count);
println!("Processing time: {}ms", result.processing_time_ms);
Ok(())
}
The PdfProcessResult struct returned by process_pdf contains:
markdown—Stringwith the extracted content formatted as Markdownpage_count—usizeindicating total pages processedprocessing_time_ms—f64tracking execution durationtitle—Option<String>with detected document title if available
Python Bindings for Path‑Based PDF Loading
The Python interface exposed in src/python.rs mirrors the Rust API for loading PDFs from file paths:
import pdf_inspector
# Load and process a PDF from filesystem path
pdf_path = "documents/annual_report.pdf"
result = pdf_inspector.process_pdf(pdf_path)
# Access extracted content
print(result["markdown"])
# Access metadata
print(f"Pages: {result['page_count']}")
The Python binding signature at src/python.rs#L683 accepts an optional pages parameter for selective processing:
def process_pdf(path: str, pages: Optional[list[int]] = None) -> PyPdfResult
This allows loading specific pages without processing the entire document:
# Load only pages 1, 5, and 6
result = pdf_inspector.process_pdf(
"documents/large_document.pdf",
pages=[1, 5, 6]
)
How Path Loading Works Internally
The file path loading mechanism flows through these components:
src/lib.rs— Public API entry points (process_pdf,process_pdf_with_options)src/detector.rs— Determines PDF classification (text‑based, scanned, hybrid)src/extractor/mod.rs— Orchestrates content extraction based on detection resultssrc/bin/pdf2md.rs— CLI implementation demonstrating production usage of path‑based loading with OCR integration
The pdf2md.rs binary at src/bin/pdf2md.rs illustrates advanced path‑loading patterns, calling process_pdf_with_ocr when optical character recognition is required. This implementation path handles scanned documents by integrating image‑based text extraction after the initial file load.
Error Handling for Invalid Paths
The PdfError type returned by process_pdf encapsulates common failure modes:
- File not found — Path does not exist or insufficient permissions
- Invalid PDF — File exists but lacks valid PDF structure
- IO errors — System‑level read failures
- Processing errors — Extraction pipeline failures (corrupted content, unsupported features)
use pdf_inspector::{process_pdf, PdfError};
match process_pdf("potentially_missing.pdf") {
Ok(result) => println!("Success: {} pages", result.page_count),
Err(PdfError::Io(e)) => eprintln!("File access failed: {}", e),
Err(PdfError::InvalidPdf(e)) => eprintln!("Corrupted or invalid PDF: {}", e),
Err(e) => eprintln!("Processing failed: {}", e),
}
Summary
- Primary function —
process_pdfinsrc/lib.rsloads PDFs from anyAsRef<Path>type - Flexible input — Accepts string literals,
PathBuf, or custom path types in Rust; simple strings in Python - Complete pipeline — File opening, detection, and extraction execute automatically
- Extension point —
process_pdf_with_optionsenables OCR, page selection, and detection‑only workflows - Cross‑language — Identical capabilities available via Rust crate or Python module with
pagesfiltering
Frequently Asked Questions
What path formats does pdf‑inspector accept?
pdf‑inspector accepts relative paths ("docs/file.pdf"), absolute paths ("/home/user/docs/file.pdf"), and platform‑appropriate PathBuf instances. The Rust API uses the standard library's AsRef<Path> trait, enabling seamless integration with std::path::Path ecosystem types.
Can I load PDFs from URLs instead of local paths?
The core process_pdf function requires a filesystem path. For URL‑based loading, download the PDF first using a HTTP client, then pass the temporary file path to pdf‑inspector. The library focuses on processing rather than transport.
How do I enable OCR when loading scanned PDFs?
Use process_pdf_with_options and set the ocr flag, or call process_pdf_with_ocr directly as implemented in src/bin/pdf2md.rs. This activates the image‑based extraction pipeline for documents lacking embedded text.
Does pdf‑inspector support password‑protected PDFs?
Password‑protected PDFs require preprocessing. The current implementation in src/lib.rs does not expose password parameters in the public API. Remove encryption using external tools before loading the file path into pdf‑inspector.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →