1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PyPDF2ではなくpypdfを活用しよう。

Posted at

PyPDF2ではなくpypdfを活用しよう

PyPDF2のメンテが止まっている…
pypdfって何が違うの?
既存コードは書き換えが大変そう…

そんな悩みは pypdf への乗り換えで一発解決できます。


1️⃣ pypdf は超アクティブに開発中!

  • PyPDF2 の最終リリースは 3.0.1 (2022‑12‑31)
  • pypdf は 2025‑05‑11 に v5.5.0 が公開されたばかり
  • GitHub の Issues / PR も盛んで、Python 3.12 まで対応

2️⃣ インストールは pip ひとつで OK

# まずは PyPDF2 をアンインストール(入っている場合)
pip uninstall -y PyPDF2

# pypdf を最新バージョンでインストール
pip install -U pypdf

3️⃣ 既存コードを書き換えてみる

🔄 before (PyPDF2)

from PyPDF2 import PdfReader, PdfWriter

reader = PdfReader("input.pdf")
writer = PdfWriter()

for page in reader.pages:
    writer.add_page(page)

with open("merged.pdf", "wb") as f:
    writer.write(f)

✅ after (pypdf)

from pypdf import PdfReader, PdfWriter

reader = PdfReader("input.pdf")
writer = PdfWriter()

for page in reader.pages:
    writer.add_page(page)

with open("merged.pdf", "wb") as f:
    writer.write(f)

from PyPDF2 importfrom pypdf import に置き換えるだけで
ほとんどのコードがそのまま動きます。
さらに pypdf では PdfMergerPdfWriter に統合されるなど、
API が整理され可読性も向上しています。


4️⃣ pypdf だけの便利機能

✂️ 4‑1 画像抽出 (images プロパティ)

from pypdf import PdfReader

reader = PdfReader("brochure.pdf")
images = reader.pages[0].images  # list[Image]

for i, img in enumerate(images):
    with open(f"page0_img{i}.png", "wb") as f:
        f.write(img.data)

🛡️ 4‑2 墨消し (redact)

from pypdf import PdfReader, PdfWriter

reader = PdfReader("secret.pdf")
writer = PdfWriter()

page = reader.pages[0]
page.add_redact_annotation(
    rect=(100, 400, 200, 430),
    fill=(0, 0, 0)  # 黒塗り
)
page.apply_redactions()

writer.add_page(page)
with open("secret_redacted.pdf", "wb") as f:
    writer.write(f)

💬 4‑3 新しい annotations API

注釈を簡単に追加でき、フォーム入力付きの PDF も
Python だけで生成可能です。


5️⃣ 移行チェックリスト

項目 PyPDF2 pypdf
最終リリース 2022‑12‑31 (3.0.1) 2025‑05‑11 (5.5.0)
Python 3.12 対応
AES 暗号化 △ (制限あり)
墨消し API
画像抽出 △ (要別 lib)
開発アクティビティ

📝 まとめ

  • PyPDF2 は実質 EOL、後継は pypdf
  • import のパスを変えるだけで多くのコードが動く
  • pypdf 5 系では画像抽出・墨消しなど強力な新機能が追加
  • 今すぐ pip install -U pypdf で最新版を使ってみましょう! 🚀

参考リンク

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?