LoginSignup
20
24

More than 5 years have passed since last update.

pythonで複数画像をPDFファイルに変換する

Last updated at Posted at 2018-11-03

はじめに

画像ファイルからpdfの作成方法といえばオンラインのフリー変換サイト(smallpdfとか)が有名ですが、アップロードサイズとか変換速度がネックです。ローカルでやれるならローカルで変換したいですね。今回使うのはimg2pdfというモジュールです。

参考サイト: Pythonを使って画像をPDFに変換する

準備

pip install img2pdf
pip install Pathlib

コード

ImgToPdf.py
import img2pdf
from pathlib import Path

#単処理
def ImageToPdf(outputpath, imagepath):
    '''
    outputpath: pathlib.Path()
    imagepath: pathlib.Path()
    '''
    lists = list(imagepath.glob("**/*"))#単フォルダ内を検索
    #pdfを作成
    with open(outputpath,"wb") as f:
        #jpg,pngファイルだけpdfに結合
        #Pathlib.WindowsPath()をstring型に変換しないとエラー
        f.write(img2pdf.convert([str(i) for i in lists if i.match("*.jpg") or i.match("*.png")]))
    print(outputpath.name + " :Done")

#複数フォルダをループ処理する
def main():
    #作業フォルダ
    base_path = r"your work folder path"
    #作業フォルダ内のディレクトリだけを抽出する
    glob = Path(base_path).glob("*")
    imagefolderlist = list([item for item in list(glob) if item.is_dir()])
    #outputpathに指定ディレクトリと同名を指定する
    outputpathlist = list([item.with_name(item.name + ".pdf") for item in imagefolderlist])
    #ループ処理を行う
    for outputpath,imagepath in zip(outputpathlist,imagefolderlist):
        try:
            ImageToPdf(outputpath,imagepath)
        except:
            pass

ありがちな罠

パスの入力が必要な箇所にPathlib.Path()を突っ込むとエラー吐くモジュールもよくあるので,
str(Pathlib.Path())でパスをstring型に直す必要があります。

20
24
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
20
24