概要
pdf2image(Poppler)を使ってPDFの1ページ目をもとにサムネイルを生成するプログラムを作りました。
実行環境
- Python 3.7.2 64bit
- MacOS Mojave 64bit
必要ライブラリ、アプリケーション
pdf2image を使っているので、pdf2imageとPopplerをインストールする必要がある。
ただし、Popplerのインストールには、Qtが必要ですが、CUIのみのLinux環境などではQtをインストールするのに一苦労します。なので、CUIのみのLinux環境の場合は、ImageMagickを使う方法をお勧めします。
$ brew install poppler
# pip install Pillow
# pip install pdf2image
コード
from PIL import Image
from io import BytesIO
from pdf2image import convert_from_bytes
def genThumb(response, thumb_width, thumb_height):
# 高速化するために先頭ページのみ読み込む(最終ページを1ページ目にする)
images = convert_from_bytes(response.read(), last_page=1)
temp = BytesIO()
# 解像度を落とし、ファイル形式をpngに変更する
images[0].resize((thumb_width, thumb_height)).save(temp, format="png")
return temp.getvalue()