JPEGをPDFにまとめる 複数冊対応

2022/5/3更新

#!/usr/bin/python
#-*- coding:utf-8 -*-
import os
import pdb

current_dir = os.getcwd()
booknames =  [f for f in os.listdir(current_dir) if not os.path.isfile(f)]

#QUALITY = 100 
QUALITY = 92

# ビルドフォルダを作成(すでにあればスキップ)
buildfolder_name = 'build'
cmd = 'mkdir -p ../'+buildfolder_name
print(cmd)
os.system(cmd)

for book in booknames:
    booktitle = book+".pdf"

    # フォルダ内に移動
    dest_dir = current_dir+'/'+book
    print('os.chdir() to '+dest_dir)
    os.chdir(dest_dir)
    # フォルダ内のJPEGをすべてPDFに変換
    cmd = 'ls -1 *.jpeg | sort -V | xargs -I% convert % -quality '+str(QUALITY)+ ' %.pdf'
    print(cmd)
    os.system(cmd)
    # 変換PDFリスト作成
    cmd = 'ls -1 *.pdf | sort -V | xargs  -I{} echo  \"{}\" >> list.dat'
    print(cmd)
    os.system(cmd)
    # 複数PDFを1つのPDFにマージ
    cmd = 'cat list.dat | tr "\r\n" " " | xargs gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=merged.pdf'
    print(cmd)
    os.system(cmd)
    # 中間生成物(不要なPDFとリスト)の削除
    cmd = 'mv merged.pdf merged_pdf.bak; rm *.pdf; rm list.dat'
    print(cmd)
    os.system(cmd)

    # 拡張子をPDFに戻す
    cmd = "mv merged_pdf.bak "+'"'+booktitle +'"'
    print(cmd)
    os.system(cmd)

    # ビルドフォルダに移動
    #cmd = "mv "+'"'+booktitle +'" "'+current_dir+'../'+buildfolder_name+'"'
    cmd = "mv "+'"'+booktitle +'" ' +os.path.join(current_dir, '../'+buildfolder_name)
    print(buildfolder_name)
    print(cmd)
    os.system(cmd)

動作動画
youtu.be