0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

複数のjpgファイルを一つのPDFファイルに変換する

Last updated at Posted at 2020-02-23

やりたいこと

scannerなどで取り入れた明細の画像ファイル(jpg or JPEG or JPG)をPDFファイルにまとめたい
明細はディレクトリ毎に区分けしてあり、区分け毎にPDFファイルにまとめる
ディレクトリの中には日付ごとにまとめらている

ls ~/scan/meisai/
   自動車保険明細
  自動車保険明細/2017/
  自動車保険明細/2018/
  自動車保険明細/2019/
  自動車保険明細/2020/
  クレジッドカードA/2017/
  クレジッドカードA/2018/
  クレジッドカードA/2019/
  クレジッドカードA/2020/
   医療明細2020_01_20.jpg
  .DS_store

このようなディレクトリ構成のなかに複数の画像ファイルが存在している。
それを以下のようにまとめる

ls ~/scan/meisai_pdf/
   自動車保険明細.pdf
  クレジッドカードA.pdf
  .DS_store

使用した画像ファイルは手動で削除する。

使用したもの

python3
import os
import img2pdf

コード

import os
import img2pdf

EXP_DIR = "/Users/myname/scan/meisai"
OUT_DIR = "/Users/myname/scan/meisai_pdf"


def extract_image_file_list(folder_path):
    ret = []
    if os.path.isdir(folder_path) == False:
        return ret 
    for t in sorted(os.listdir(path=folder_path)):
        if os.path.isdir(folder_path + "/" + t):
            # 再起的にディレクトリを辿っていく
            ret += extract_image_file_list(folder_path + "/" + t)
        else:
            ret.append(folder_path + "/" + t)
    return ret

def image_to_pdf(pdf_name,image_list):
    convert_target = []
    for i in image_list:
        if i.endswith(".jpg") or i.endswith(".JPG") or i.endswith(".jpeg"):  
            convert_target.append(i)
    if len(convert_target) == 0:
        return
    with open(pdf_name + ".pdf", "wb") as f:
        f.write(img2pdf.convert(convert_target))

# os.chdir(EXP_DIR)  # ディレクトリに移動して相対パスで処理したい場合。
for path in os.listdir(path=EXP_DIR):
    print(path)
    files = extract_image_file_list(EXP_DIR + "/" + path)
    image_to_pdf(OUT_DIR + "/" + path,files)

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?