概要
-
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)