PyPDF2を使ってPythonでPDFを操作する

PyPDF2を使うと、てPythonでPDFの内容を確認したり、保存が行えます。

インストール

pip install PyPDF2

PDFの読み取り

PdfReader Classを使って、読み込んだPDFファイルを操作します。

from PyPDF2 import PdfReader

READ_FILE_PATH = "C:\\Python3\\Work\\sample.pdf"
reader = PdfReader(READ_FILE_PATH)

ページ数を取得する

page_number = reader.getNumPages()

指定ページのテキストを抽出する

getPage()でページオブジェクトを取得し、ページのテキストを抽出します。getPage()のパラメータは0から始まるページインデックスです。

page = reader.getPage(0)
text = page.extractText()

全ページを走査する

ループを使って、各ページオブジェクトを取得できます。

for page in reader.pages:
    # 処理...
#;

サンプル

from PyPDF2 import PdfReader

READ_FILE_PATH = "C:\\Python3\\Work\\sample.pdf"
reader = PdfReader(READ_FILE_PATH)

# ページ数を取得する.
page_number = reader.getNumPages()
print(page_number)

# ページオブジェクトを取得し、ページのテキストを抽出する.
page = reader.getPage(0) # 0..n index.
text = page.extractText()
print(text)

# 全ページを処理する.
for page in reader.pages:
    text = page.extractText()
    print(text)
#;

アノテーション情報の取得

ページ内にアノテーション情報(注釈)がある場合、page["/Annots"]でアノテーション情報を参照できます。

# ページにアノテーションがある場合にページ内のアノテーションを出力.
if "/Annots" in page:
    for annot in page["/Annots"]:
        annot_obj = annot.get_object()
        subtype = annot_obj["/Subtype"]
        print(subtype)
        # Text か FreeText のみ文字データと矩形を出力.
        if (subtype == "/Text") or (subtype == "/FreeText"):
            print(annot_obj["/Contents"], annot_obj["/Rect"])
    #;
#;

アノテーションの要素数はlen(page["/Annots"])で取得できます。

アノテーション情報の削除

page.pop("/Annots")でアノテーション情報を削除できます。戻り値は削除したアノテーション情報です。アノテーション情報が無い場合はエラーになります。

annots = page.pop("/Annots")

popした値を使う場合は次のようにします。for annot in annots:だとエラーになります。

annots = page.pop("/Annots")
for annot in annots.get_object():
    annot_obj = annot.get_object()
#;

PDFの保存

PdfWriter Classを使って、PDFファイルの保存が行えます。

from PyPDF2 import PdfWriter

WRITE_FILE_PATH = "C:\\Python3\\Work\\page1.pdf"
writer = PdfWriter()

writer.addPage(page)

with open(WRITE_FILE_PATH, "wb") as f:
    writer.write(f)
#;

writer.addPage()でページオブジェクトを追加し、ファイルに書き出します。パラメータのpagePdfReader Classを使って、既存のPDFファイルから取得します。
この操作により、PDFの分割や結合などが簡単に行えます。

サンプル

PDFファイルの1ページ目だけを別のPDFファイルとして保存するだけのサンプルです。

from PyPDF2 import PdfReader
from PyPDF2 import PdfWriter

READ_FILE_PATH = "C:\\Python3\\Work\\sample.pdf"
WRITE_FILE_PATH = "C:\\Python3\\Work\\page1.pdf"

reader = PdfReader(READ_FILE_PATH)
writer = PdfWriter()

# 1ページ目のページオブジェクトを取得する.
page = reader.getPage(0)
# PDFWriterに設定.
writer.addPage(page)

with open(WRITE_FILE_PATH, "wb") as f:
    writer.write(f)
#;
このエントリーをはてなブックマークに追加
にほんブログ村 IT技術ブログへ

スポンサードリンク

関連コンテンツ

コメント

メールアドレスが公開されることはありません。 が付いている欄は必須項目です