サンプル: 検索可能 PDF の生成 ¶
このサンプルでは YomiToku の create_searchable_pdf() を用いて、
スキャン画像から テキストを埋め込んだ検索可能 PDF を作成する手順を示します。
PDF 内のテキストはコピー & 検索が可能になるため、
社内共有や電子帳簿保存法対応の前処理として便利です。
from yomitoku import DocumentAnalyzer
from yomitoku.data.functions import load_image
from yomitoku.utils import correct_rotation, create_searchable_pdf
images = load_image("demo/samples/demo.jpg")
analyzer = DocumentAnalyzer(visualize=True, device="cuda", enable_preprocess=True)
pdf_images = []
results = []
for img in images:
result, ocr_vis, layout_vis = analyzer(img)
# With rotation correction, result coordinates refer to the corrected
# image. Pass the corrected image to create_searchable_pdf.
pdf_images.append(correct_rotation(img, result))
results.append(result)
create_searchable_pdf(
pdf_images,
results,
output_path="demo_searchable_pdf.pdf",
)
analyzer.close()
回転補正を使う場合の注意¶
enable_preprocess=True で回転補正を行うと、解析結果の座標は補正後の画像を基準にします。create_searchable_pdf() には、元の入力画像ではなく correct_rotation(img, result) で補正した画像を渡してください(上のサンプルコードを参照)。元画像を渡すと、回転していたページでテキストの位置がずれ、検索や選択の位置が画像と一致しません。
correct_rotation() は回転補正を行っていない結果に対しては画像をそのまま返すため、常に通しておいて問題ありません。詳しくは 回転補正を有効にしたときの画像の扱い を参照してください。
create_searchable_pdf() パラメータ¶
| 引数 | 型 | 必須 | 説明 |
|---|---|---|---|
images |
list[np.ndarray] |
✔ | ページ画像のリスト(BGR)。回転補正を有効にした場合は correct_rotation() で補正した画像を渡します。 |
results |
list[DocumentAnalyzerSchema] |
✔ | 各ページの解析結果。len(results) は len(images) と一致する必要があります。 |
output_path |
str |
✔ | 生成する PDF の保存先パス。 |
font_path |
str |
埋め込みに使用するTrueTypeフォントデータのパス(.ttf) |
よくある質問¶
| 質問 | 回答 |
|---|---|
解析結果が 1 ページでも results をリストにする必要は? |
はい。[single_result] のように 必ずリスト で渡してください。 |
実行結果¶
-
demo_searchable_pdf.pdf -
画像はそのままの見た目
Ctrl/Cmd + Fで文字列検索可Ctrl/Cmd + Cでテキストコピー可