見出し画像

フォルダの画像を一括でPDF化する

こんにちは、ぬるぽです。もう年度末ですね。

今回、画像が格納されているフォルダ単位で、PDFに変換するPythonコードを日曜大工ならぬ、日曜コーディングしてましたので、noteに公開します。

経緯

個人的な画像書籍や、いわゆる"戦利品"をため込んでいるフォルダがあり、iPadや各種デバイスで読書できるように、画像データをPDF化したかった。

しかし、いちいちフリーソフトにドラッグアンドドロップをするのは非常に手間でアホらしい。腱鞘炎まっしぐら+n日以上かかる。

そこで・・・

以下のフォルダ条件で、自動化するコードを作成した。

IMPORTフォルダの構成想定

入力フォルダの「フォルダZ」を指定して、出力先のフォルダを別途指定すると、PDF化して吐き出すスクリプトを作成した。

Python未インストール環境でも、pyinstallerでパッケージ化することにより、動作することを確認済み。

Pythonコードサンプル

import os
import img2pdf
from PIL import Image

def get_folder_lists(path):
    files = os.listdir(path)
    dir = [f for f in files if os.path.isdir(os.path.join(path, f))]
    return dir

def convert_image_to_pdf(strOutFilePath,strFolderPath,strTitle):

    filelist_jpg = [i for i in os.listdir(strFolderPath)if i.endswith('.jpg')]
    filelist_png = [i for i in os.listdir(strFolderPath)if i.endswith('.png')]

    # 【参考】https://qiita.com/daikan_murata/items/e1c38db8b41d141f12d8
    if(len(filelist_jpg) > 1):
        ext = '.jpg'
        img_count = str(len(filelist_jpg))
    elif(len(filelist_png) > 1):
        ext = '.png'
        img_count = str(len(filelist_png))

    print('処理中(' + img_count + '枚)>> ' ,strTitle)

    with open(strOutFilePath,"wb") as f:
        f.write(img2pdf.convert([Image.open(strFolderPath+j).filename for j in os.listdir(strFolderPath)if j.endswith(ext)]))

def main():

    strTargetPath = input('変換対象の親フォルダを入力してください >> ') + "\\"
    strTargetPath = strTargetPath.replace("\\","/")

    strOutputPath = input('出力先のフォルダを入力してください >> ') + "\\"
    strOutputPath = strOutputPath.replace("\\","/")

    print(strTargetPath)
    print(strOutputPath)

    dir_list = get_folder_lists(strTargetPath)

    for strDirName in dir_list:
        strOutFilePath = strOutputPath + strDirName + ".pdf"
        strFolderPath = strTargetPath + strDirName + "/"
        
        convert_image_to_pdf(strOutFilePath,strFolderPath,strDirName)

if(__name__ == '__main__'):
    main()

お約束(こぴぺ)

  • コードに関するクレームは受け付けません。
    (建設的なアドバイスは大大大歓迎)

  • このスクリプトは煮るなり焼くなりお好きにどうぞ。

  • このスクリプトによって発生した、いかなる損害や不具合に関して、一切のサポートや保証はいたしません。

  • 豆腐メンタルなので、暴言や中小はやめてね。。。

紳士淑女の皆様の戦利品整理にお役立ていただければ幸いです。
では、おやすみなさいませ。