1
1

More than 3 years have passed since last update.

PythonでPDF結合GUIを作る その2

Posted at

今回はその2です

 その1 TkinterでUI作成
 その2 PyPDF2でPDF操作
 その3 pyinstallerでexe化+アイコンを付ける

ログインユーザー名を取得

保存先をデスクトップに指定するためにログインユーザー名を取得

merger = PyPDF2.PdfFileMerger()
user = os.getlogin()
username= str(user) 

ボタン「Open」のアクション

以下の流れで結合するPDFファイルを確認します
 
 ファイルパス確認
    ↓
 PDFファイルをリストにappend
    ↓
 テキストボックスに結合するPDFファイルを表示

# Open
def clicked():
    txt3.delete(1.0, tkinter.END)
    filePath = txt1.get()

    if os.path.exists(filePath):
        pass
    else:
        txt3.insert('1.0','パスが見つかりません')

    drawings = []
    allFiles = os.listdir(filePath)

    for f in os.listdir(filePath):
        if os.path.join(filePath, f)[-4:] == '.pdf':
            drawings.append(f)

    count = int(len(drawings))
    txt3.insert('1.0','以下のPDFファイルを結合します\n\n')
    for i in range(count):
        txt3.insert(1.0 * i + 3.0, drawings[i] + '\n')

ボタン「Merge」のアクション

PDFファイルを結合して "ファイル名.pdf" をデスクトップに保存します

# Merge
def merge():
    filePath = txt1.get()
    #filePath = str(txt1.get())
    savePath = 'C:\\Users\\' + username + '\\Desktop' 
    savedName = txt2.get()

    drawings = []
    allFiles = os.listdir(filePath)
    for f in os.listdir(filePath):
        if os.path.join(filePath, f)[-4:] == '.pdf':
            merger.append(os.path.join(filePath, f))

    merger.write(os.path.join(savePath, savedName + '.pdf'))
    merger.close()

    txt3.insert(tkinter.END, '\n\n**************************\n\n')
    txt3.insert(tkinter.END, savedName + '.pdf として保存しました')

ボタンにcommandを追加

その1でコメントアウトしていた箇所です

# Openボタン
button = tkinter.Button(root, text="Open", command=clicked, width=8, height=2, font=(u'Meiryo', 8), bg='#add8e6', fg='#000000')
button.place(x=80, y=120)

# Mergeボタン
button = tkinter.Button(root, text="Merge", command=merge, width=8, height=2, font=(u'Meiryo', 8), bg='#4169e1', fg='#ffffff')
button.place(x=200, y=120)

できました!
image.png

参考

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