サンプル集  >  Python  >  pdfをMarkdownへ変換② Docling
pdfをMarkdownへ変換② Docling
2025/12/06

pdfをMarkdownへDoclingを使って変換してみます。

◆環境
OS Windows 10 Home 22H2 64bit OS x64 プロセッサ
Python 3.13.1
VS Code 1.106.0
  1. Doclingをインストール
  2. pdfをMarkdownへ変換

Doclingをインストール

Doclingは以下のコマンドでインストールします。

pip install docling

コマンドプロンプトで実行してみます。

:
Successfully installed Sha... docling-2.64.0 docling-core-2.54.0 docl
ing-ibm-models-3.10.3 docling-parse-4.7.2 et-xm...

色々なモジュールがインストールされました。

pdfをMarkdownへ変換

Doclingのconvert()でpdfをMarkdownに変換してみます。

pdf2md2.py
 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
from datetime import datetime, timezone, timedelta
from docling.document_converter import DocumentConverter
import sys

JST = timezone(timedelta(hours=9))

inpt_file = sys.argv[1]

converter = DocumentConverter()

start = datetime.now(JST)
result = converter.convert(inpt_file)
md = result.document.export_to_markdown()
end = datetime.now(JST)

with open(inpt_file+".md""w", encoding="utf-8") as f:
    f.write(md)

proc_time = end - start
print(f"変換時間: {proc_time} ms")

pdfをMarkdownへ変換 MarkItDownで作成したPDFを指定して実行してみます。

> py .\pdf2md2.py .\test-word.pdf 
2025-12-06 11:27:18,854 - INFO - detected formats: [  'pdf'>]
2025-12-06 11:27:20,275 - INFO - Going to convert document batch...
2025-12-06 11:27:20,277 - INFO - Initializing pipeline for StandardPd
fPipeline with options hash 
e15bc6f248154cc62f8db15ef18a8ab7
:
2025-12-06 11:28:04,111 - INFO - Accelerator device: 'cpu'
2025-12-06 11:28:04,440 - INFO - Processing document test-word.pdf
2025-12-06 11:28:06,082 - INFO - Finished converting document test-wo
rd.pdf in 47.24 sec.
変換時間: 0:00:47.420413 ms

変換されたMarkdownファイルを確認したところ、少しレイアウトがおかしいですが文字の大きさや表も再現されていました。

## テスト用 PDF の見出し1です。 テスト用 PDF の見出し2です。

テスト用 PDF の見出し3です。

テスト用 PDF の本文です。

|       | 入社年            | 住所   |
|-------|----------------|------|
| 山田 太郎 | 2020 年 1 月 6 日 | 静岡県  |
| Alex  | 2022 年 3 月 1 日 | US   |

VSCodeでプレビューしてみます。


64ページあるpdfを変換してみます。

> py .\pdf2md.py .\RLJ012A020.pdf
:
変換時間: 0:01:48.315801 ms

1分48秒程度かかりました。

▲ PageTop  ■ Home


Copyright (C) 2025 ymlib.com