5
6

More than 3 years have passed since last update.

PythonでPDFからPNGに変換する + α

Last updated at Posted at 2019-10-31

概要

  • PDF => PNG(画像)に変換するAPIを作りたかったのでPython3でやってみました
  • pdf2imageを使えばサクッとできます
  • ソースはこちらにあるので試したい方はどうぞ

Packages

パッケージ以外にOS側にpopplerが入ってないと動かないと思うのでこちらからインストールしておいてください

requirements.txt
pdf2image
Pillow
wheel

以下のコマンドで一気にインストールできます

pip install -r requirements.txt

実装

PDF => PNGと 必要になったのでPDF => PNG => Base64もやってみました

PDF => PNG

import base64
from pdf2image import convert_from_path, convert_from_bytes


images = convert_from_path('sample.pdf')

for index, image in enumerate(images):
    name = str(index) + '.png'
    image.save(name, 'png')

PDF => PNG => Base64

import base64
from io import BytesIO
from pdf2image import convert_from_path, convert_from_bytes


images = convert_from_path('sample.pdf')


def base64pdf_to_base64png(image):
    buffer = BytesIO()
    image.save(buffer, format="PNG")
    return base64.b64encode(buffer.getvalue()).decode().replace("'", "")


base64Pngs = list(map(base64pdf_to_base64png, images))
print(base64Pngs)
5
6
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
5
6