1
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?

Pythonで2つのPDFファイルを1つに結合する

1
Posted at

2つのPDFファイルを1つに結合

近年,公的な手続き・申請において,PDFファイルを提出することがめっきり多くなりました.そんな時,複数のPDFファイルを1つのファイルにまとめたい.

PDFファイルを結合するだけで,そんなにがっつりとPDFファイルを編集する予定もないので,PDF編集アプリを購入するほどでもない.

無料でPDFファイルを結合してくれるWebサイトもありますが,
プライベートなPDFファイルを無闇にアップロードするのはちょっと抵抗がある...

そんな時は,Pythonを用いて自身のPCの中で結合すればいいじゃない.

<手順>
① 下記のPythonプログラムを実行すると,ダイアログボックスが現れるので2つのPDFファイルを選択する.
② その後,再びダイアログボックスが現れるので,結合したファイル名を入力すると,そのファイル名のPDFが生成される.

merge_pdf.py
import tkinter as tk
from tkinter import filedialog
from PyPDF2 import PdfMerger

def select_pdf_files():
    root = tk.Tk()
    root.withdraw()

    file_paths = filedialog.askopenfilenames(
        title="結合する2つのPDFを選択してください",
        filetypes=[("PDF files", "*.pdf")]
    )
    return list(file_paths)

def save_merged_pdf():
    root = tk.Tk()
    root.withdraw()

    save_path = filedialog.asksaveasfilename(
        title="結合後のPDFファイル名を指定してください",
        defaultextension=".pdf",
        filetypes=[("PDF files", "*.pdf")]
    )
    return save_path

def merge_pdfs(pdf_list, output_path):
    merger = PdfMerger()

    for pdf in pdf_list:
        merger.append(pdf)

    merger.write(output_path)
    merger.close()

def main():
    print("PDF を2つ選択してください")
    pdf_files = select_pdf_files()

    if len(pdf_files) != 2:
        print("PDF は必ず2つ選択してください")
        return

    print("保存先を選択してください")
    output_path = save_merged_pdf()

    if not output_path:
        print("保存先が選択されませんでした")
        return

    merge_pdfs(pdf_files, output_path)
    print(f"PDF を結合しました → {output_path}")

if __name__ == "__main__":
    main()
1
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
1
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?