🤦

[Python]PDFを切り出して縦長画像に変換するやつ(PDFium, PIL)

に公開

https://togetter.com/li/2541260

しょうもないAI対策している大学があってキレたので作りました🤦

  • 知らない人間が見て気付けないのが根本原因なので、普段人間が見ている環境でPDFを画像に変換する
    • Google ChromeでPDF表示する時に使っているPDFiumのバインディングを使えば良い
  • ただ画像にしても透明度99の文字を書いた場合、AIが読み取ってしまうかもしれない
    • グレースケールかバイナリイメージで対策できるかもしれない

とりあえずPythonとpipが動く環境でpypdfium2とPillowをインストール。

$ pip install pypdfium2 pillow

全ページ分割して画像にできるか確認。

script.py
import os

import pypdfium2 as pdfium

pdf = pdfium.PdfDocument("input.pdf")
os.makedirs("output", exist_ok=True)
os.makedirs("output_grayscale", exist_ok=True)
os.makedirs("output_bilevel", exist_ok=True)

for i in range(len(pdf)):
    image = pdf[i].render().to_pil()
    image.save(f"output/{i:02d}.png")
    image_grayscale = image.convert("L")
    image_grayscale.save(f"output_grayscale/{i:02d}.png")
    image_bilevel = image.convert("1")
    image_bilevel.save(f"output_bilevel/{i:02d}.png")

適当にPDF取ってきて実行。

$ curl -sLo input.pdf https://www.ipa.go.jp/shiken/mondai-kaiotu/nl10bi0000009lh8-att/2025r07h_ap_pm_qs.pdf
$ python script.py

ただこれだと画像が大量にできて1回で生成AIに渡せない🤷

縦長画像にしてみる。

script.py
import pypdfium2 as pdfium
from PIL import Image

pdf = pdfium.PdfDocument("input.pdf")
images = [page.render().to_pil() for page in pdf]
x = max(image.width for image in images)
y = sum(image.height for image in images)
concatenated_image = Image.new("RGB", (x, y))

y_offset = 0
for image in images:
    concatenated_image.paste(image, (0, y_offset))
    y_offset += image.height

concatenated_image.save("output.png")
concatenated_image_grayscale = concatenated_image.convert("L")
concatenated_image_grayscale.save("output_grayscale.png")
concatenated_image_bilevel = concatenated_image.convert("1")
concatenated_image_bilevel.save("output_bilevel.png")

同じPDF取ってきて実行。

$ curl -sLo input.pdf https://www.ipa.go.jp/shiken/mondai-kaiotu/nl10bi0000009lh8-att/2025r07h_ap_pm_qs.pdf
$ python script.py

ページ数が多く縦に長過ぎると生成AIに渡してもエラー出る🙅

ちゃんとしたCLIツールにする。

script.py
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.12"
# dependencies = [
#     "pypdfium2==4.30.1",
#     "pillow==11.2.1",
# ]
# ///

# SPDX-License-Identifier: Unlicense
# /// license
# This is free and unencumbered software released into the public domain.
# 
# Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means.
# 
# In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# 
# For more information, please refer to <https://unlicense.org>
# ///

import sys

import pypdfium2 as pdfium
from PIL import Image

if len(sys.argv) == 1:
    pdf_path = "input.pdf"
    range_str = None
elif len(sys.argv) == 2:
    if ":" in sys.argv[1]:
        pdf_path = "input.pdf"
        range_str = sys.argv[1]
    else:
        pdf_path = sys.argv[1]
        range_str = None
elif len(sys.argv) >= 3:
    pdf_path = sys.argv[1]
    range_str = sys.argv[2]
else:
    print("Usage: python script.py [pdf_path] [start:end]")
    sys.exit(1)

try:
    pdf = pdfium.PdfDocument(pdf_path)
except Exception as e:
    print(f"Failed to load PDF file '{pdf_path}': {e}")
    sys.exit(1)

if range_str:
    try:
        start_str, end_str = range_str.split(":")
        start = max(0, int(start_str) - 1)
        end = min(len(pdf), int(end_str))
    except Exception:
        print("Invalid page range format. Use 'start:end' (e.g., 2:7).")
        sys.exit(1)
else:
    start = 0
    end = len(pdf)

pages = [pdf[i] for i in range(start, end)]
images = [page.render().to_pil() for page in pages]
x = max(image.width for image in images)
y = sum(image.height for image in images)
concatenated_image = Image.new("RGB", (x, y))

y_offset = 0
for image in images:
    concatenated_image.paste(image, (0, y_offset))
    y_offset += image.height

concatenated_image.save("output.png")
concatenated_image_grayscale = concatenated_image.convert("L")
concatenated_image_grayscale.save("output_grayscale.png")
concatenated_image_bilevel = concatenated_image.convert("1")
concatenated_image_bilevel.save("output_bilevel.png")

実行して期待通りに動くか確認。

$ curl -sLO https://www.ipa.go.jp/shiken/mondai-kaiotu/nl10bi0000009lh8-att/2025r07h_ap_pm_qs.pdf
$ python script.py 2025r07h_ap_pm_qs.pdf 6:10

PDFを切り出して縦長画像に変換できました🙆

著作権と用法用量を守って生成AIに渡しましょう💁

2025/05/02更新:リファクタリングした最新のコードを反映しました。解説内容は変わっていません。

Discussion