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 3 years have passed since last update.

画像ファイルをPDFに変換する

Posted at

##PYTHON で画像ファイルをPDFに変換する

python3.7.9で実装。
pyinstaler で exe 化すれば、ドラッグ&ドロップで変換するツールになります。

import sys
import os
import img2pdf
from PIL import Image, ImageSequence
from pikepdf import _cpphelpers
import tkinter as tk
from tkinter import messagebox

#透過処理を外す、jpegに変換する
def RemoveAlpha(src):
    dstPath = os.path.dirname(src)
    dstImg = []
    img = Image.open(src)

    # マルチページ対応
    for i, page in enumerate(ImageSequence.Iterator(img)):
        page = page.convert("RGB")
        basename_without_ext = os.path.splitext(os.path.basename(src))[0]
        dstImg.append(os.path.join(dstPath, '{}_{}.jpeg'.format(basename_without_ext,i)))
        page.save(dstImg[-1], format='jpeg')
#       page.save(dstImg[-1], quality=95)

    return dstImg

try:
    target_ext  = ['.JPG','.JPEG','.PNG','.GIF','.BMP','.TIFF','.TIF']  # PDFにするファイルの拡張子
    alpha_ext   = ['.PNG','.GIF','.BMP','.TIFF','.TIF']                 # JPEGに変換するファイルの拡張子
    output_ext  = '.pdf'

    root = tk.Tk()
    root.withdraw()

    for argv_idx in range(1,len(sys.argv)):
        filename = sys.argv[argv_idx]
        root, ext = os.path.splitext(filename)
        for ext_idx in range(len(target_ext)):
            if ext.upper() == target_ext[ext_idx]:
                srcImages = [filename]

                # 透過処理を外す、またはサイズ縮小するファイルかチェック
                for ae in alpha_ext:
                    if ae == ext.upper():
                        srcImages = RemoveAlpha(filename)

                # PDF 変換処理
                with open(root + output_ext,'wb') as f:
                    f.write(img2pdf.convert(srcImages))

                # 一時ファイルを削除
                for srcImage in srcImages:
                    if srcImage != filename:
                        os.remove(srcImage)
    
    if len(sys.argv) <= 1:
        output_ext_mes = ''
        for ext_idx in range(len(target_ext)):
            if output_ext_mes != '':
                output_ext_mes += ' | '
            output_ext_mes += target_ext[ext_idx].lower()

        messagebox.showinfo('確認', 'PDFに変換する画像ファイルをドラッグ&ドロップしてください\n※拡張子は [ {} ] のみ'.format(output_ext_mes))
    else:
        messagebox.showinfo('確認', '処理が完了しました\n画像ファイルと同じ場所にPDFが作成されています。')

except Exception as e:
    messagebox.showerror('エラー', e)
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?