Skip to content
    HAQQ
    Log in
    Contact sales
    Try HAQQ
    Try HAQQ
    1. Home
    2. Blog
    3. Docling Python: A Practical Guide to Processing Files in 2026
    Guides & How-To

    Docling Python: A Practical Guide to Processing Files in 2026

    Install Docling 2.140, convert PDFs and scans to Markdown in five lines, OCR a scanned Arabic contract with tables, and chunk it for RAG. Code checked Oct 2026.

    Jad JabbourJad Jabbour|
    May 20, 2026
    7 min read
    Docling Python: A Practical Guide to Processing Files in 2026

    In short: Docling is an MIT-licensed Python library, started at IBM Research and now hosted by LF AI & Data, that converts PDFs, Word files, scans and 30+ other formats into Markdown or JSON for AI pipelines. Version 2.140.0 (16 October 2026) installs with one pip command and converts a file in five lines of Python.

    bash
    pip install docling
    python
    from docling.document_converter import DocumentConverter
    
    converter = DocumentConverter()
    result = converter.convert("contract.pdf")  # a local path or a URL
    print(result.document.export_to_markdown())

    Version note: every snippet in this guide was checked against Docling 2.140.0 (PyPI, released 16 October 2026) and the docling-project/docling repository on 20 October 2026. Docling ships releases every few days, so pin the version in production and re-check option names when you upgrade.

    Key facts

    • Latest release: Docling 2.140.0, published to PyPI on 16 October 2026 (PyPI, read 20 Oct 2026).
    • Python: 3.10 or newer; 3.9 support was dropped in 2.70.0 (Docling README, read 20 Oct 2026).
    • License and home: MIT, repository github.com/docling-project/docling, a project of LF AI & Data, about 69,000 GitHub stars (GitHub, 20 Oct 2026).
    • OCR engines: an automatic selector (the default), RapidOCR (installed by default), EasyOCR, Tesseract (CLI or tesserocr), macOS Vision, Nemotron OCR and a remote KServe engine (pipeline_options.py, 2.140.0).
    • Arabic: supported through EasyOCR (`ar`), Tesseract (`ara`) and RapidOCR's Arabic-script recognizer; mixed Arabic and English pages still have open issues, for example #3462 and #3929 (GitHub, read 20 Oct 2026).
    • Formats: PDF, DOCX, DOC, RTF, PPTX, XLSX, CSV, HTML, Markdown, AsciiDoc, LaTeX, EPUB, email (EML, MSG), ODF, images, audio and video, among others (InputFormat enum, 2.140.0).

    Try HAQQ AI Free

    Experience AI-powered legal drafting and research

    What is Docling used for?

    Docling sits at the front of a retrieval or document-analysis pipeline. It reads a file, runs layout detection, reading-order reconstruction, table structure recovery and OCR where the page has no text layer, and returns a single `DoclingDocument` object. From that object you export Markdown, HTML, plain text or lossless JSON, or hand it to a chunker that prepares pieces for an embedding model.

    We care about it for legal work because contracts are full of the structures that naive PDF text extraction destroys: numbered clauses, schedules, payment tables, signature blocks, and pages that are only a scan of a stamped original. Docling runs locally, so client documents never have to leave your infrastructure to be parsed.

    Which file formats does Docling support?

    The 2.140.0 release accepts PDF (text and scanned), Word (.docx, .doc), RTF, PowerPoint (.pptx, .ppt), Excel (.xlsx, .xls), CSV, HTML and MHTML, Markdown, AsciiDoc, LaTeX, EPUB, email files (.eml, .msg), OpenDocument (.odt, .ods, .odp), Apple Pages, Numbers and Keynote, images (PNG, JPEG, TIFF and others), WebVTT, and audio and video through speech recognition. `DocumentConverter` detects the format itself, so you pass a path or URL and nothing else.

    Does Docling do OCR?

    Yes. `PdfPipelineOptions.do_ocr` is `True` by default, and the default `OcrAutoOptions` picks an available engine at start-up. By default OCR runs only on regions without a usable text layer (`OcrMode.DEFAULT`, which currently maps to `PDF_AWARE_LAYOUT_REGIONS`). For a fully scanned file, set `mode=OcrMode.FULL_PAGE`. The older `force_full_page_ocr=True` flag still works but is deprecated.

    EngineOptions classInstallArabic code
    RapidOCRRapidOcrOptionsincluded in pip install doclingArabic-script recognizer (one language per run)
    EasyOCREasyOcrOptionspip install "docling[easyocr]"ar (can be combined with en)
    Tesseract CLITesseractCliOcrOptionssystem Tesseract plus ara.traineddataara (combine as ["ara", "eng"])
    Tesseract (tesserocr)TesseractOcrOptionspip install "docling[tesserocr]" plus system Tesseractara
    macOS VisionOcrMacOptionspip install "docling[ocrmac]", macOS onlydepends on the macOS version
    AutoOcrAutoOptionsdefaultforwards iso: tags to the chosen engine

    Language codes are passed to the engine as written (`ara` for Tesseract, `ar` for EasyOCR), or as a BCP-47 tag behind an `iso:` prefix, for example `iso:ar`, which Docling maps to the right engine code. A language the engine has no model for raises an error instead of silently falling back, which is what you want in a legal pipeline.

    How do I OCR a scanned Arabic contract with tables?

    Take a typical case: a 14-page scanned lease from Dubai, Arabic body text with English defined terms, a rent schedule as a table on page 3, and a stamped signature page. There is no text layer, so every page goes through OCR, and the rent table needs TableFormer in accurate mode. We use Tesseract here because it handles Arabic and English on the same page in one pass.

    python
    from docling.datamodel.base_models import InputFormat
    from docling.datamodel.pipeline_options import (
        OcrMode,
        PdfPipelineOptions,
        TableFormerMode,
        TableStructureOptions,
        TesseractCliOcrOptions,
    )
    from docling.document_converter import DocumentConverter, PdfFormatOption
    
    pipeline_options = PdfPipelineOptions()
    pipeline_options.do_ocr = True
    pipeline_options.ocr_options = TesseractCliOcrOptions(
        lang=["ara", "eng"],          # Arabic first, English defined terms second
        mode=OcrMode.FULL_PAGE,       # the scan has no text layer
    )
    pipeline_options.do_table_structure = True
    pipeline_options.table_structure_options = TableStructureOptions(
        mode=TableFormerMode.ACCURATE,
        do_cell_matching=False,       # let the model define cells on a scan
    )
    
    converter = DocumentConverter(
        format_options={InputFormat.PDF: PdfFormatOption(pipeline_options=pipeline_options)}
    )
    result = converter.convert("lease_dubai_scanned.pdf")
    doc = result.document
    
    # Tables come back as structured objects, not flattened text
    for table in doc.tables:
        df = table.export_to_dataframe(doc=doc)
        print(df.head())
    
    with open("lease.md", "w", encoding="utf-8") as f:
        f.write(doc.export_to_markdown())

    Install Tesseract and its Arabic data first (`apt install tesseract-ocr tesseract-ocr-ara` on Debian or Ubuntu, or the `ara.traineddata` file from the tessdata repository on other systems). The same job from the command line:

    bash
    docling --ocr-engine tesseract --ocr-lang ara,eng --ocr-mode full_page --table-mode accurate lease_dubai_scanned.pdf

    To use EasyOCR instead, install `docling[easyocr]` and swap in `EasyOcrOptions(lang=["ar", "en"], mode=OcrMode.FULL_PAGE)`. EasyOCR uses a GPU when one is present, which helps on long bundles.

    What to check in the output of an Arabic contract

    • Word order on mixed lines. When an English defined term sits inside an Arabic sentence, the run order can come back reversed. This is tracked in issue #3462 (Mixed Arabic-English PDFs produce incorrect OCR/output text), open as of 20 Oct 2026.
    • Presentation forms on digital PDFs. Some Arabic PDFs store glyphs as Unicode presentation forms, which breaks search and embeddings. A normalization fix is proposed in pull request #3929, still open; until it merges, run `unicodedata.normalize("NFKC", text)` on the exported text.
    • Table cells. Compare two or three rows of the rent schedule against the scan by eye. Amounts in Eastern Arabic numerals (٠١٢٣) should be kept as written and converted only in a later, logged step.
    • Stamps and signatures. These are detected as pictures. They are not text, so do not expect the stamp wording in the Markdown.

    None of this replaces a lawyer reading the original. It gets the text, clause numbering and tables into a form where review tools can work on them, and it tells you which pages need a human second look.

    How do I chunk documents with HybridChunker?

    `HybridChunker` splits along the document's own structure (sections, clauses, table rows) and then fits the pieces to a token budget. In current releases the token budget lives on a tokenizer wrapper from `docling-core`, and you pass that wrapper to the chunker. Older tutorials, including the first version of this one, passed a raw `transformers` tokenizer and `max_tokens` straight to `HybridChunker`. That still runs, but it now raises a `DeprecationWarning`, so use the wrapper.

    python
    from docling.chunking import HybridChunker
    from docling_core.transforms.chunker.tokenizer.huggingface import HuggingFaceTokenizer
    from transformers import AutoTokenizer
    
    EMBED_MODEL_ID = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
    
    tokenizer = HuggingFaceTokenizer(
        tokenizer=AutoTokenizer.from_pretrained(EMBED_MODEL_ID),
        max_tokens=512,      # match your embedding model's limit
    )
    chunker = HybridChunker(
        tokenizer=tokenizer,
        merge_peers=True,    # merge small neighbouring chunks under the same heading (default)
    )
    
    for chunk in chunker.chunk(dl_doc=doc):
        text_for_embedding = chunker.contextualize(chunk=chunk)  # prepends the heading path
        print(chunk.meta.headings, len(text_for_embedding))

    Embed the output of `contextualize()`, not `chunk.text`. For a contract it prefixes each chunk with its heading path, so a chunk that only says "the Tenant shall pay within 30 days" arrives at the embedding model as part of "Article 5, Rent and Payment". Pick a multilingual embedding model for Arabic contracts; an English-only model such as all-MiniLM-L6-v2 will tokenize Arabic poorly. For OpenAI-style models, `docling_core.transforms.chunker.tokenizer.openai.OpenAITokenizer` wraps a tiktoken encoding the same way.

    Where does each chunk come from?

    Every chunk carries `chunk.meta`, with `headings` (the section path), `doc_items` (the source paragraphs or table cells, each with page number and bounding box in its `prov` field) and `origin` (the source file name and hash). Keep these. A legal answer that cites "page 3, rent schedule" is checkable; one that cites "chunk 41" is not.

    python
    for chunk in chunker.chunk(dl_doc=doc):
        pages = sorted({prov.page_no for item in chunk.meta.doc_items for prov in item.prov})
        print({
            "source": chunk.meta.origin.filename,
            "headings": chunk.meta.headings,
            "pages": pages,
            "text": chunker.contextualize(chunk=chunk)[:80],
        })

    How do I process a folder of contracts?

    Build the converter once and reuse it, because model loading is the slow part. `convert_all` takes an iterable of paths and, with `raises_on_error=False`, keeps going past a corrupt file and reports its status.

    python
    from pathlib import Path
    from docling.datamodel.base_models import ConversionStatus
    
    files = sorted(Path("contracts/").glob("*.pdf"))
    for res in converter.convert_all(files, raises_on_error=False):
        name = res.input.file.name
        if res.status == ConversionStatus.SUCCESS:
            Path("out", name).with_suffix(".md").write_text(
                res.document.export_to_markdown(), encoding="utf-8"
            )
        else:
            print(f"{name}: {res.status}")

    For long bundles, set `pipeline_options.document_timeout` (the Docling docstring suggests 90 to 120 seconds) so one bad scan cannot stall a batch, and turn off features you do not need: `do_table_structure=False` on correspondence, `do_ocr=False` on born-digital Word exports converted to PDF.

    Which export formats does Docling support?

    From a `DoclingDocument` you can call `export_to_markdown()`, `export_to_html()`, `export_to_text()` and `export_to_dict()` (lossless JSON, which you can reload later without re-running OCR). Save the JSON for anything you OCR'd: re-running full-page OCR on a 200-page bundle is the expensive step, and the JSON keeps page and bounding-box provenance that Markdown drops.

    Docling vs Unstructured: which should I use?

    Both are open source and both run locally. Docling's strengths are layout analysis, table structure recovery with TableFormer, a single typed document model with page-level provenance, and a structure-aware chunker. Unstructured (Apache 2.0, `partition()` functions) has a wider set of source and destination connectors and a hosted commercial platform. For a contract pipeline where tables and citations to the page matter, we start with Docling; if your problem is pulling files out of many SaaS systems, Unstructured's connectors may save more time. Run both on ten of your own worst scans before deciding, because results on Arabic scans vary more by file than by library.

    How does this connect to legal AI review?

    Parsing is the first step, and the one that decides how good everything after it can be. A clause the parser split in half cannot be reviewed as a clause, and a table flattened into a line of numbers cannot be checked row by row. HAQQ ingests client files into private workspaces with the same goals (structure, tables and page citations kept intact) before contract review runs on them, with hosting in the EU, US or Middle East, or on your own infrastructure.

    What to do next

    • Pin `docling==2.140.0` (or whichever release you test) and record it next to your outputs.
    • Pick three representative files: a born-digital contract, a scanned Arabic one, and one with a dense table. Convert each and read the Markdown against the original.
    • Choose the OCR engine per document type, not globally. Tesseract with `["ara", "eng"]` is a sound default for mixed MENA contracts.
    • Chunk with a tokenizer that matches your embedding model and keep `chunk.meta` for citations.

    Sources

    • Docling on PyPI (release history)
    • docling-project/docling on GitHub
    • Docling releases
    • Docling documentation
    • Docling full-page OCR example
    • Docling hybrid chunking example
    • Issue #3462: Mixed Arabic-English PDFs
    • Pull request #3929: normalize Arabic presentation forms
    • Tesseract language data (tessdata)

    Related reading

    • context engineering for reliable legal AI
    • tabular document review for legal AI
    • the legal engineering guide to AI-powered workflows

    Written by

    Jad Jabbour
    Jad Jabbour

    Technology Leader & AI Lead

    Jad leads technology and AI at HAQQ. He writes about the engineering behind the platform, such as document processing.

    All articles by this authorLinkedIn

    Related Resources

    What happens before a legal AI answers your questionTabular document review for legal AIContext engineering for reliable legal AIAI legal translation, Arabic to English

    Related Posts

    AI Legal Translation Arabic to English: A Practical Guide
    Guide

    AI Legal Translation Arabic to English

    AI Legal Translation Arabic to English: A Practical Guide

    Arabic Legal AI: The Gap Is Retrieval, Not Content
    MENA

    Arabic Legal AI

    Arabic Legal AI: The Gap Is Retrieval, Not Content

    Stop Writing [CLIENT]: How to Anonymize a Document Before You Give It to AI
    Guide

    Stop Writing [CLIENT]

    Stop Writing [CLIENT]: How to Anonymize a Document Before You Give It to AI

    Frequently asked questions

    What is Docling in Python?

    Docling is an MIT-licensed open-source Python library, started at IBM Research and now hosted by LF AI & Data, that converts PDFs, Word, PowerPoint, Excel, HTML, scans and other formats into Markdown, HTML or lossless JSON for AI and RAG pipelines. The current release as of 20 October 2026 is 2.140.0.

    How do I install Docling?

    Run 'pip install docling' on Python 3.10 or newer. The default install includes RapidOCR. For EasyOCR use 'pip install "docling[easyocr]"'; for Tesseract install the system package and its language data (for Arabic, ara.traineddata), plus 'docling[tesserocr]' if you want the Python binding instead of the CLI.

    Does Docling do OCR?

    Yes. OCR is on by default (PdfPipelineOptions.do_ocr is True) and runs on regions without a text layer. Supported engines are RapidOCR, EasyOCR, Tesseract (CLI or tesserocr), macOS Vision and Nemotron OCR, chosen automatically unless you set ocr_options. For a fully scanned file set mode=OcrMode.FULL_PAGE; the older force_full_page_ocr flag is deprecated.

    Can Docling read scanned Arabic documents?

    Yes, with Tesseract (lang ["ara", "eng"]), EasyOCR (lang ["ar", "en"]) or RapidOCR's Arabic-script recognizer. Check mixed Arabic and English lines by hand: word-order problems on mixed lines are tracked in Docling issue #3462, and an Arabic presentation-form fix (pull request #3929) was still open on 20 October 2026.

    Docling vs Unstructured: which is better?

    Both are open source and run locally. Docling is stronger on layout, table structure (TableFormer), page-level provenance and structure-aware chunking, which suits contracts. Unstructured has more source and destination connectors and a hosted platform. Test both on your own hardest scans before choosing.

    How do I set the chunk size in Docling's HybridChunker?

    Wrap your embedding model's tokenizer in HuggingFaceTokenizer (or OpenAITokenizer) from docling_core with max_tokens set, then pass it as HybridChunker(tokenizer=...). Passing max_tokens directly to HybridChunker still works but raises a DeprecationWarning. Embed chunker.contextualize(chunk) so each chunk carries its heading path.

    What's Next?

    Try HAQQ AI Free

    Experience AI-powered legal drafting and research

    Calculate Your ROI

    See how much time and money HAQQ saves your firm

    Browse 600+ Legal Prompts

    Ready-to-use prompts for every legal task

    Back to Blog

    Previous article

    Legora Review 2026: Pricing, Alternatives and Legora vs HAQQ

    Next article

    Legal Tech in the Middle East: The 2026 Field Guide

    On this page

    7 min read

    1. 01Key facts
    2. 02What is Docling used for?
    3. 03Which file formats does Docling support?
    4. 04Does Docling do OCR?
    5. 05How do I OCR a scanned Arabic contract with tables?
    6. What to check in the output of an Arabic contract
    7. 06How do I chunk documents with HybridChunker?
    8. 07Where does each chunk come from?
    9. 08How do I process a folder of contracts?
    10. 09Which export formats does Docling support?
    11. 10Docling vs Unstructured: which should I use?
    12. 11How does this connect to legal AI review?
    13. 12What to do next
    14. 13Sources
    15. 14Related reading

    Share this article

    Put this to work

    Ask HAQQ the question this article raised for you.

    HAQQ across all devices
    HAQQ Legal AI Platform Logo

    Your Legal AI Twin & Practice Management System for drafting, billing, and winning.

    Download on theApp StoreGet it onGoogle Play

    Documentations

    • Docs opens in a new tab
    • Getting Started opens in a new tab
    • Newsroom opens in a new tab
    • Product Updates opens in a new tab
    • Status opens in a new tab
    • Trust opens in a new tab
    • Security
    • FAQ opens in a new tab
    • Community opens in a new tab
    • Support opens in a new tab

    Academy

    • Partner opens in a new tab
    • Course opens in a new tab
    • Prompt opens in a new tab
    • Labs opens in a new tab

    Website

    • eFirm
    • Legal AI Chat
    • Mobile App
    • Justinian AI Engine
    • HAQQ eBar
    • HAQQ eWallet
    • Pricing
    • Compare Us
    • Solutions
    • Blog
    • Meet Team
    • Join Us opens in a new tab
    Open App
    • Localesenarfresitdeptrohics
    • Contactinfo@haqq.ai
    • Statusoperational·grounded
    • Terms of Service
    • Privacy Policy
    • Cookie Policy
    • Data Processing
    • Humans opens in a new tab
    • Lawyers opens in a new tab
    • Security opens in a new tab
    © 2026 HAQQ Inc. All rights reserved.Product engineered in-house by HAQQ. Website built with modern web tools.
    PDF
    DOCX
    HTML
    PPTX

    Markdown

    Clean, structured text

    📄

    PDF

    Including OCR

    📝

    Word

    .docx files

    📊

    PowerPoint

    .pptx slides

    🌐

    HTML

    Web pages

    📃

    Markdown

    .md files

    🖼️

    Images

    OCR support

    ❌ Arbitrary Split

    Context lost between chunks

    ✓ HybridChunker

    Section 1128 tokens
    Section 2256 tokens
    Section 3192 tokens
    Section 4384 tokens

    Preserves semantic meaning

    Extracting...

    Extracted Metadata

    title:Legal Agreement 2024
    author:John Smith
    pages:12
    created:2024-01-15
    Input Folder
    contract.pdf
    memo.docx
    brief.pdf
    report.html

    4

    Files Processed

    ~2.3 seconds

    📝

    Markdown

    📄

    Plain Text

    { }

    JSON

    Export to the format that fits your workflow

    Document
    Docling
    Chunks
    AI Ready

    From raw document to AI-ready embeddings in seconds