LoginSignup
79
88

More than 3 years have passed since last update.

Pythonを使って複数画像をPDFに変換する

Last updated at Posted at 2018-05-18

この記事は、Pythonを使って複数の画像を一つのPDFにまとめたいと考えているユーザーに向けたものです。
以前の公開コードをPython3で試したら動作しなくなっていたので、Python3ユーザー向けに更新しています。

前提

macOS Catalina (10.15.6)
python 3.7.5

事前準備

img2pdfをインストールします。
https://pypi.org/project/img2pdf/

pip3 install img2pdf

インストールに成功したことを確認

Installing collected packages: Pillow, img2pdf
    Running setup.py install for img2pdf ... done
Successfully installed Pillow-7.2.0 img2pdf-0.4.0

画像をPDFに変換する

以下のスクリプトを記述します。ここではファイル名を convert2pdf.py とします。

convert2pdf.py
import os
import img2pdf
from PIL import Image # img2pdfと一緒にインストールされたPillowを使います

if __name__ == '__main__':
    pdf_FileName = "/tmp/png/output.pdf" # 出力するPDFの名前
    png_Folder = "/tmp/png/" # 画像フォルダ
    extension  = ".png" # 拡張子がPNGのものを対象

    with open(pdf_FileName,"wb") as f:
        # 画像フォルダの中にあるPNGファイルを取得し配列に追加、バイナリ形式でファイルに書き込む
        f.write(img2pdf.convert([Image.open(png_Folder+j).filename for j in os.listdir(png_Folder)if j.endswith(extension)]))

python3で上記コードを実行します。output.pdfが生成されます。

python3 convert2pdf.py

最後までお読みいただきましてありがとうございました。

参考

https://pillow.readthedocs.io/en/stable/
https://www.geeksforgeeks.org/python-convert-image-to-pdf-using-img2pdf-module/

以前の記事

以下の内容は Windows7, Python2.xで確認した内容です。

複数の画像を一つのPDFに変換する方法を説明します。

pip install img2pdf

次に以下のスクリプトを記述します。このスクリプトは、特定のフォルダ(例 c:\python\pdf)にある png ファイルを output.pdf に追加します。

import os
import img2pdf

if __name__ == '__main__':
    pdfFileName = "output.pdf"
    path = "C:\\python\\pdf"
    ext  = ".png"

    with open(pdfFileName, "wb") as f:
        f.write(img2pdf.convert([i for i in os.listdir(path)if i.endswith(ext)]))
79
88
4

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
79
88