PDF Processing について
PDF Processing は、PDF を扱う開発者向けのスキルです。Python パッケージによるテキストや表の抽出、フォーム処理、結合・分割、画像変換、OCR を扱います。
主な機能
- 01複数ページのテキスト抽出
- 02表の検出と抽出
- 03フォームの入力と検証
- 04PDF の結合と分割
- 05ページ画像への変換と OCR
活用シーン
- 01レポート本文を後続処理用に抽出
- 02PDF の表を CSV に出力
- 03PDF 文書の結合または分割
- 04スキャンページを OCR で処理
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ davila7/ claude-code-templates --skill pdf-processingインストール後、Claude Code で/pdf-processingを入力して読み込まれたか確認します。
同梱ファイルFORMS.md
詳細
PDF処理
クイックスタート
pdfplumber を使用して PDF からテキストを抽出します:
import pdfplumber
with pdfplumber.open("document.pdf") as pdf:
text = pdf.pages[0].extract_text()
print(text)
表の抽出
自動検出機能を使用して PDF から表を抽出します:
import pdfplumber
with pdfplumber.open("report.pdf") as pdf:
page = pdf.pages[0]
tables = page.extract_tables()
for table in tables:
for row in table:
print(row)
すべてのページの抽出
複数ページのドキュメントを効率的に処理します:
import pdfplumber
with pdfplumber.open("document.pdf") as pdf:
full_text = ""
for page in pdf.pages:
full_text += page.extract_text() + "\n\n"
print(full_text)
フォーム入力
PDF フォーム入力については、フィールドの分析と検証を含む完全なガイドである FORMS.md を参照してください。
PDF の結合
複数の PDF ファイルを結合します:
from pypdf import PdfMerger
merger = PdfMerger()
for pdf in ["file1.pdf", "file2.pdf", "file3.pdf"]:
merger.append(pdf)
merger.write("merged.pdf")
merger.close()
PDF の分割
特定のページや範囲を抽出します:
from pypdf import PdfReader, PdfWriter
reader = PdfReader("input.pdf")
writer = PdfWriter()
# Extract pages 2-5
for page_num in range(1, 5):
writer.add_page(reader.pages[page_num])
with open("output.pdf", "wb") as output:
writer.write(output)
利用可能なパッケージ
- pdfplumber - テキストと表の抽出(推奨)
- pypdf - PDF の操作、結合、分割
- pdf2image - PDF を画像に変換(poppler が必要)
- pytesseract - スキャンされた PDF 向けの OCR(tesseract が必要)
よくあるパターン
テキストを抽出して保存:
import pdfplumber
with pdfplumber.open("input.pdf") as pdf:
text = "\n\n".join(page.extract_text() for page in pdf.pages)
with open("output.txt", "w") as f:
f.write(text)
表を CSV に抽出:
import pdfplumber
import csv
with pdfplumber.open("tables.pdf") as pdf:
tables = pdf.pages[0].extract_tables()
with open("output.csv", "w", newline="") as f:
writer = csv.writer(f)
for table in tables:
writer.writerows(table)
エラー処理
PDF でよくある問題に対処します:
import pdfplumber
try:
with pdfplumber.open("document.pdf") as pdf:
if len(pdf.pages) == 0:
print("PDF has no pages")
else:
text = pdf.pages[0].extract_text()
if text is None or text.strip() == "":
print("Page contains no extractable text (might be scanned)")
else:
print(text)
except Exception as e:
print(f"Error processing PDF: {e}")
パフォーマンスのヒント
- 大きな PDF はページをバッチ単位で処理する
- 複数のファイルには multiprocessing を使用する
- ドキュメント全体ではなく、必要なページだけを抽出する
- 使用後は PDF オブジェクトを閉じる
コメント
Markdown 対応