1
1

PDFをWebP形式の画像に変換

Last updated at Posted at 2024-06-14

PDFをWebP形式の画像に変換

GhostScriptを使用した場合

> gswin64c -dSAFER -dBATCH -dNOPAUSE -dUseCropBox -dPDFSETTINGS=/prepress -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -dMaxStripSize=8192 -sDEVICE=jpeg -r200 -sOutputFile=output.jpg input.pdf

一見よさそうだが、PDF内のテキストフォントに問題があると、画像時に文字位置が変な場所にでてきてしまった。

Pythonを使ってPDFの画像化をする

pdf2imageを使用するが、popplerが必要とのことで、popplerをダウンロードする

  • 最新版のpoppler(poppler-24.06.1.tar.xz)をダウンロードしてきて、展開する
    https://github.com/oschwartz10612/poppler-windows/releases
  • C:\poppler-24.02.0に配置して、「C:\poppler-24.02.0\Library\bin」にPATHを通す(環境変数のPATHに追加→再起動)

Pythonにpdf2imageを追加

> pip install pdf2image

PDFからJPEGを生成

input.pdfをページごとの0.jpeg,1.jpeg・・・と出力
解像度は、dpi=300を指定
size=(1200, None)などして、画像サイズでの指定も可能

pdf2jpg.py
from pdf2image import convert_from_path

def convert_pdf_to_images(pdf_path):
    images = convert_from_path(pdf_path, fmt='jpeg', dpi=300)

    for i, image in enumerate(images):
        image.save(f'{i}.jpeg', 'JPEG')

convert_pdf_to_images('input.pdf')

JPEGからWebPに変換

input.jpegをoutput.webpに変換

jpeg2webp.py
from PIL import Image

def convert_jpeg_to_webp(jpeg_path, webp_path):
    image = Image.open(jpeg_path)
    image.save(webp_path, 'WEBP')

convert_jpeg_to_webp(f'input.jpeg', f'output.webp')

PDFからWebP形式の画像を生成

input.pdfをページごとの0.webp,1.webp・・・と出力
解像度は、dpi=300を指定

pdf2webp.py
from pdf2image import convert_from_path
from PIL import Image

images = convert_from_path('./input.pdf', dpi=300)

def convert_pdf_to_webp():
    for i, image in enumerate(images):
        image.save(f'{i}.webp', 'WEBP')

convert_pdf_to_webp()
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