Python

Two functions: extract for text, extract_document for structure.

Terminal
pip install khmerpdf
Python
import khpdf

text = khpdf.extract("report.pdf")                        # plain text
md = khpdf.extract("report.pdf", format="markdown")       # headings, lists, tables
doc = khpdf.extract_document("report.pdf")                # dict

extract

Signature
khpdf.extract(source, *, format="text", pages=None, page_markers=False) -> str
Argument
sourceA file path (str or pathlib.Path) or the PDF's bytes.
format"text" (default), "markdown" or "json".
pages1-based page numbers to keep, e.g. [1, 2] or range(1, 4). All pages by default.
page_markersMark where each page starts.

extract_document

Signature
khpdf.extract_document(source, *, pages=None, words=False) -> dict

Returns the JSON output as a Python dict: pages with their blocks, fonts, OCR flag and warnings. With words=True, each page also lists every word with its box (Word positions). See The output for the fields.

Python
doc = khpdf.extract_document("report.pdf")
for page in doc["pages"]:
    if page["needs_ocr"]:
        print("page", page["number"], "is a scan")
    for block in page["blocks"]:
        if block["type"] == "table":
            print(block["headers"])

Errors

A folder of PDFs

Python
from pathlib import Path
import khpdf

for pdf in Path("documents").glob("*.pdf"):
    Path("converted", pdf.stem + ".txt").write_text(khpdf.extract(pdf), encoding="utf-8")

khpdf releases Python's interpreter lock while it works, so a thread pool converts several PDFs in parallel.

The command

The package also installs the khpdf command, the same tool described in Command line. python -m khpdf runs it too.

With Neam

To find people, organizations and places in the text, pass it to Neam:

Python
import khpdf
from neam import Neam

ner = Neam.from_pretrained("MoriartyPuth/neam")
text = khpdf.extract("report.pdf")
for entity in ner.predict(text)["entities"]:
    print(entity["label"], entity["text"])