独立系ガイド — IBM および Docling プロジェクトとは無関係です。 すべてのコマンドを Docling 2.143.1 で検証済み。
  1. ホーム
  2. Python API
Python API ガイド

Docling の Python API——最初の呼び出しから本番運用まで

Python から Docling を呼び出すために必要なことをまとめました。コンバーター、結果を本当に左右するオプション、壊れたファイルでも止まらない一括処理、そして DoclingDocument から Markdown・JSON・HTML・pandas の表を取り出す方法です。以下のコードはすべて Docling 2.143.1 で実行しました。

Docling で検証済み 2.143.1更新日 2026年10月27日12 分で読めます
要点
  • DocumentConverter().convert(source) はパス・URL・メモリ上のストリームを受け取り ConversionResult を返します。構造化された結果は result.document です。
  • PDF は PdfFormatOption に包んだ PdfPipelineOptions で設定します。既定値:OCR オン(auto)、表オン(accurate)、4 スレッド、デバイス auto。
  • 一括処理は convert_all(..., raises_on_error=False) を使い、result.status を確認します。
  • 出力は export_to_markdown()・save_as_json()・export_to_html()。表は table.export_to_dataframe(doc=doc) で pandas に。

1 つの文書を変換する#

API の出発点は DocumentConverter です。作成は軽く、モデルは最初の変換時に読み込まれて以後は再利用されるので、プロセス全体で 1 つのコンバーターを使い回しましょう。

pythonconvert.py
from docling.document_converter import DocumentConverter

converter = DocumentConverter()
result = converter.convert("https://arxiv.org/pdf/2408.09869")  # パス、URL、DocumentStream

print(result.status)                     # ConversionStatus.SUCCESS
doc = result.document                    # DoclingDocument
print(doc.export_to_markdown()[:300])

convert() は ConversionResult を返します。document のほかに status・errors・pages・timings・confidence(ページごとの品質スコア)を持ち、信頼度の低いページを人の確認に回すのに使えます。

convert() の引数#

引数既定値働き
source—Path、文字列のパスまたは URL、DocumentStream
headersNonesource が URL のときの HTTP ヘッダー(認証トークンなど)
raises_on_errorTrue失敗時に、失敗結果を返す代わりに例外を送出
max_num_pages無制限これより多いページ数の文書をスキップ
max_file_size無制限このバイト数を超えるファイルをスキップ
page_range(1, ∞)このページだけ変換(1 始まり・両端を含む)。例:(1, 10)
progress_callbackNone文書・フェーズ・ページ単位の進捗イベントを受け取る

2.143.1 の DocumentConverter.convert のシグネチャから確認。convert_all() は同じ引数を取り、複数のソースを反復可能オブジェクトで渡します。

メモリ上のデータを変換する#

アップロード、S3 のオブジェクト、メール添付など、ファイルがバイト列で届く場合は DocumentStream で包みます。ファイル名の拡張子でバックエンドが決まります。

python
from io import BytesIO
from docling.datamodel.base_models import DocumentStream
from docling.document_converter import DocumentConverter

data = open("report.pdf", "rb").read()          # S3 や API から得たバイト列など
stream = DocumentStream(name="report.pdf", stream=BytesIO(data))
doc = DocumentConverter().convert(stream).document

PDF パイプラインを設定する#

オプションは入力形式ごとに設定します。PDF(と画像)では、PdfPipelineOptions を PdfFormatOption で包みます。

pythonpipeline_options.py
from docling.datamodel.accelerator_options import AcceleratorOptions
from docling.datamodel.base_models import InputFormat
from docling.datamodel.pipeline_options import (
    PdfPipelineOptions, TableFormerMode, TableStructureOptions,
)
from docling.document_converter import DocumentConverter, PdfFormatOption

opts = PdfPipelineOptions()
opts.do_ocr = False                      # デジタル生成 PDF:当サイトの計測で 3.7 倍速
opts.do_table_structure = True
opts.table_structure_options = TableStructureOptions(mode=TableFormerMode.ACCURATE)
opts.accelerator_options = AcceleratorOptions(num_threads=8, device="auto")
opts.document_timeout = 300              # 秒。超えると途中までの結果を返す

converter = DocumentConverter(
    format_options={InputFormat.PDF: PdfFormatOption(pipeline_options=opts)}
)

特に重要な既定値です(2.143.1 の PdfPipelineOptions のフィールドから取得)。

オプション既定値メモ
do_ocrTrue既定モードでは PDF のテキスト層がない領域だけ OCR
ocr_optionsOcrAutoOptions()インストール済みエンジンを自動選択(標準構成では RapidOCR)
do_table_structureTrueTableFormer が行・列・結合セルを再構成
table_structure_options.modeACCURATEFAST は当サイトの計測で全体 11% 高速
accelerator_options4 スレッド、device="auto"auto は CUDA → Apple MPS → Intel XPU → CPU の順に選択
images_scale1.0出力するページ画像・図の解像度
generate_page_images / generate_picture_imagesFalse画像を出力する場合に必要
do_formula_enrichment / do_code_enrichmentFalse数式 → LaTeX、コードブロックの認識
do_picture_description / do_picture_classificationFalse追加モデルで図の説明文・種類を付与
do_chart_extractionFalse棒・円・折れ線グラフ → 表
document_timeoutNoneN 秒で文書の処理を打ち切る
enable_remote_servicesFalseAPI ベースのモデルを使うには True が必要
artifacts_pathNoneオフライン用のローカルモデルフォルダ

OCR エンジンと言語は OCR ガイド、視覚言語パイプラインは VLM と Granite-Docling を参照してください。設定ビルダーでこのコードを自動生成できます。

壊れたファイルで止まらない一括変換#

convert_all() は結果を順に返すため、大きなフォルダでもメモリ使用量が増え続けません。raises_on_error=False にすると、壊れたファイルは例外ではなく失敗結果になります。

pythonbatch.py
from pathlib import Path
from docling.datamodel.base_models import ConversionStatus
from docling.document_converter import DocumentConverter

converter = DocumentConverter()
files = sorted(Path("inbox").glob("*.pdf"))
out = Path("out"); out.mkdir(exist_ok=True)

for res in converter.convert_all(files, raises_on_error=False):
    name = res.input.file.stem
    if res.status in (ConversionStatus.SUCCESS, ConversionStatus.PARTIAL_SUCCESS):
        res.document.save_as_markdown(out / f"{name}.md")
        res.document.save_as_json(out / f"{name}.json")
    else:
        print(f"{name}: {res.status.value}", [e.error_message for e in res.errors])

2.143.1 のステータスは pending・started・failure・success・partial_success・skipped です。partial_success は通常タイムアウトや一部ページの失敗を意味し、成功したページは文書に含まれます。

受け付ける形式を制限する#

python
from docling.datamodel.base_models import InputFormat
from docling.document_converter import DocumentConverter

converter = DocumentConverter(
    allowed_formats=[InputFormat.PDF, InputFormat.DOCX, InputFormat.PPTX]
)

それ以外の形式は変換されずに拒否されます。アップロード用のエンドポイントに便利です。36 種類の InputFormat の一覧は対応形式のページにあります。

DoclingDocument の中身#

DoclingDocument は木構造と、いくつかのフラットなリストでできています。各要素は label、テキストまたはデータ、prov(出典:ページ番号とバウンディングボックス)を持つので、回答をページ上の位置までたどれます。

フィールド内容
texts段落、タイトル、見出し(level 付き)、リスト項目、キャプション、脚注、数式、コード
tablesセルのグリッド(data.num_rows・data.num_cols・結合)を持つ TableItem
pictures図。任意で分類と説明文
groupsリストや章などのコンテナ
body / furniture本文の読み順ツリー / ヘッダー・フッター
pagesページサイズと(生成した場合)ページ画像

Docling 技術レポートを変換して得た実際の要素です。

jsondoc.texts[2](抜粋)
{
  "self_ref": "#/texts/2",
  "label": "section_header",
  "level": 1,
  "text": "Version 1.0",
  "prov": [{ "page_no": 1,
             "bbox": { "l": 283.31, "t": 511.98, "r": 328.69, "b": 503.43,
                       "coord_origin": "BOTTOMLEFT" } }]
}
python文書をたどる
for item, level in doc.iterate_items():
    page = item.prov[0].page_no if item.prov else None
    print(level, item.label, page, getattr(item, "text", "")[:60])

表を pandas に#

python
for i, table in enumerate(doc.tables):
    df = table.export_to_dataframe(doc=doc)
    print(f"table {i}: {df.shape}")
    df.to_csv(f"table_{i}.csv", index=False)

doc=doc を渡すと、表がキャプションや参照を解決できます。テスト文書では Docling が 3 つの表を検出し、1 つ目は 4 × 8 のグリッドになりました。

出力形式#

欲しいもの呼び出し
Markdown 文字列 / ファイルdoc.export_to_markdown() / doc.save_as_markdown(path)
ロスレス JSON(再読み込み可)doc.save_as_json(path) · 読み込みは DoclingDocument.load_from_json(path)
HTMLdoc.export_to_html() / doc.save_as_html(path)
プレーンテキストdoc.export_to_text()
Python の dictdoc.export_to_dict()
YAMLdoc.save_as_yaml(path)
DocTags(VLM の学習・評価用)doc.export_to_doctags() / doc.save_as_doctags(path)
WebVTT(音声・動画の字幕)doc.export_to_vtt() / doc.save_as_vtt(path)
RAG 用チャンクHybridChunker().chunk(doc)——RAG とチャンク化を参照

出力に画像を含める

Markdown・HTML・JSON は image_mode で画像の扱いを 3 通りから選べます。PLACEHOLDER(コメントで位置を示す・既定)、EMBEDDED(base64 で埋め込み)、REFERENCED(文書の隣に PNG を保存)です。画像は変換時に生成しておく必要があります。

python
from docling_core.types.doc import ImageRefMode

opts.generate_picture_images = True      # 変換前に PdfPipelineOptions で設定
opts.images_scale = 2.0
...
doc.save_as_markdown("report.md", image_mode=ImageRefMode.REFERENCED)

その他の入力形式#

Office・HTML・Markdown・多くの XML 形式は PDF パイプラインを通りません。ファイル自体の構造から直接解析されるため 1 秒もかからず、OCR やレイアウトモデルも不要です。画像は PDF と同じパイプライン、音声・動画は ASR パイプラインで処理されます。形式ごとの詳細は対応形式をご覧ください。

効果の大きい高速化のコツ#

  • デジタル生成 PDF では OCR をオフに——当サイトの計測で最大の効果(1 ページ 8.5 → 2.3 秒)。
  • コンバーターを使い回す。最初の変換にはモデルの読み込みが含まれます(同じ 9 ページでコールド 27.5 秒、ウォーム 20.8 秒)。
  • page_range を使う——分類などで最初の数ページだけ必要な場合。
  • document_timeout を設定して、1 つの異常なファイルがバッチ全体を止めないようにする。

詳しい数値はパフォーマンスガイドにあります。

よくある質問

Python で PDF を Markdown に変換するには?

DocumentConverter を作り、ファイルパスまたは URL で convert() を呼び、result.document.export_to_markdown() を呼びます。デジタル生成の PDF なら pipeline_options.do_ocr = False で大幅に高速化できます。

エラーで止まらずに多数のファイルを変換するには?

converter.convert_all(paths, raises_on_error=False) を使い、各 result.status(success・partial_success・failure・skipped)を確認します。

Docling で表を DataFrame として取り出すには?

result.document.tables をループし、table.export_to_dataframe(doc=result.document) を呼びます。pandas は標準の docling パッケージと一緒に入ります。

ディスクではなくメモリ上のファイルを変換できますか?

できます。DocumentStream(name='file.pdf', stream=BytesIO(data)) でバイト列を包み、convert() に渡します。ファイル名の拡張子で形式が決まります。

変換するページ数を制限するには?

convert() に page_range=(1, 10) を渡すか、max_num_pages で上限を超える文書をスキップします。

出典