"""Native pdfplumber PDF loader with optional table extraction."""
from __future__ import annotations
from langchain_core.documents import Document
from .base import BasePDFLoader
[docs]
class PDFPlumberLoader(BasePDFLoader):
"""Extract page text and optionally structured table data with pdfplumber.
This implementation uses pdfplumber directly and does not require
``langchain-community``. Use ``pdfplumber-layout`` for element-level
reading order, headings and bounding boxes.
"""
[docs]
def load(self) -> list[Document]:
"""Load one document per page, preserving page and table metadata."""
try:
import pdfplumber
except ImportError as exc:
raise ImportError(
"PDFPlumber requires pdfplumber. "
"Install with: pip install 'automated-document-parser[pdf-tables]'"
) from exc
source = str(self.file_path)
extract_tables = self.kwargs.get("extract_tables", True)
table_settings = self.kwargs.get("table_settings")
documents: list[Document] = []
try:
with pdfplumber.open(source, password=self.kwargs.get("password")) as pdf:
pdf_metadata = dict(pdf.metadata or {})
total_pages = len(pdf.pages)
for page_number, page in enumerate(pdf.pages):
text = (
page.extract_text(layout=self.kwargs.get("layout", False)) or ""
)
tables = []
if extract_tables:
for raw_table in page.extract_tables(
table_settings=table_settings
):
rows = [
["" if cell is None else str(cell) for cell in row]
for row in (raw_table or [])
]
if any(any(cell.strip() for cell in row) for row in rows):
tables.append(rows)
table_text = [_table_to_markdown(rows) for rows in tables]
content = "\n\n".join(
part for part in [text.strip(), *table_text] if part
)
documents.append(
Document(
page_content=content,
metadata={
"source": source,
"page": page_number,
"page_number": page_number,
"total_pages": total_pages,
"page_width": float(page.width),
"page_height": float(page.height),
"pdf_metadata": pdf_metadata,
"table_count": len(tables),
"table_rows": tables,
"extraction_method": "pdfplumber",
},
)
)
except (OSError, ValueError) as exc:
raise RuntimeError(f"Failed to load PDF with pdfplumber: {exc}") from exc
return documents
[docs]
def get_install_command(self) -> str:
"""Return the installation command for pdfplumber support."""
return "pip install 'automated-document-parser[pdf-tables]'"
def _table_to_markdown(rows: list[list[str]]) -> str:
"""Render extracted table rows as a readable Markdown table."""
if not rows:
return ""
escaped = [
[cell.replace("|", "\\|").replace("\n", " ").strip() for cell in row]
for row in rows
]
width = max(len(row) for row in escaped)
padded = [row + [""] * (width - len(row)) for row in escaped]
lines = [
"| " + " | ".join(padded[0]) + " |",
"| " + " | ".join(["---"] * width) + " |",
]
lines.extend("| " + " | ".join(row) + " |" for row in padded[1:])
return "\n".join(lines)