LoginSignup
1
1

More than 1 year has passed since last update.

Pythonで指定したフォルダ内にあるJPGファイルをPDFファイルにまとめるプログラム

Last updated at Posted at 2023-03-26

プログラム全体

from PIL import Image
import os
import logging

# まとめたい jpg ファイルが入っているフォルダを指定します
input_folder = r"xx:/xxx/xxx"

# 出力する pdf ファイルの名前を指定します
output_file = r"xx:/xxx/xxx\output_file.pdf"

# 1ページあたりの解像度を指定します(デフォルトは 72dpi)
dpi = 300

# ログファイルのパスとログレベルを設定
logging.basicConfig(filename='example.log', level=logging.ERROR)

# jpg ファイルを読み込み、PDF ファイルに変換します
def convert_to_pdf(input_folder, output_file, dpi):
    try:
        images = []
        for filename in sorted(os.listdir(input_folder)):
            if filename.endswith(".JPG"):
                filepath = os.path.join(input_folder, filename)
                img = Image.open(filepath)
                images.append(img)

        # 画像をPDFにまとめます
        if images:
            images[0].save(output_file, save_all=True, append_images=images[1:], dpi=(dpi,dpi))
    except Exception as e:
        logging.error(e)

try:
    convert_to_pdf(input_folder, output_file, dpi)
except Exception as e:
    print(e)
    logging.error(e)

各コードの解説

このコードは、指定されたフォルダにあるjpgファイルを読み込み、それらを1つのPDFファイルにまとめるプログラムです。
また、ログファイルを作成して、エラーが発生した場合にログを残します。

PILライブラリとosライブラリをインポートします。

from PIL import Image
import os

まとめたい jpg ファイルが入っているフォルダのパスを指定します。

input_folder = r"xx:/xxx/xxx"

出力する PDF ファイルの名前と保存先を指定します。

output_file = r"xx:/xxx/xxx\output_file.pdf"

1ページあたりの解像度を指定します(デフォルトは 72dpi)。

dpi = 300

loggingライブラリを使って、ログファイルのパスとログレベルを設定します。

import logging
logging.basicConfig(filename='example.log', level=logging.ERROR)

jpg ファイルを読み込み、PDF ファイルに変換するconvert_to_pdf()関数を定義します。最初にtry-except文で例外処理を行っています。
この関数内の処理は以下の通りです。

5~11行目: まとめたいjpgファイルが入っているフォルダ内のすべてのファイルをリスト化し、拡張子が「.JPG」のものだけを画像ファイルとして読み込み、画像オブジェクトのリストimagesに格納します。
14~16行目: 画像をPDFにまとめて保存します。

def convert_to_pdf(input_folder, output_file, dpi):
    try:
        images = []
        for filename in sorted(os.listdir(input_folder)):
            if filename.endswith(".JPG"):
                filepath = os.path.join(input_folder, filename)
                img = Image.open(filepath)
                images.append(img)

        # 画像をPDFにまとめます
        if images:
            images[0].save(output_file, save_all=True, append_images=images[1:], dpi=(dpi,dpi))
    except Exception as e:
        logging.error(e)

最後に、convert_to_pdf()関数を実行します。
try-except文を使って例外処理を行い、例外が発生した場合にはprint()関数とloggingライブラリを使ってエラーログを出力します。

try:
    convert_to_pdf(input_folder, output_file, dpi)
except Exception as e:
    print(e)
    logging.error(e)
1
1
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
1
1