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?

PythonでPDFをマージする Part2

Last updated at Posted at 2025-11-22

PDFをマージするPythonプログラム

以前にも紹介したプログラムをファイルでPDFファイルを指定してマージするように改修したものです。

以前の記事はこちら
PythonでPDFをマージする

前回のプログラムとの差

前回のプログラムはListに直書きしてもらっていましたが、ファイルからマージするファイル名を読むように改修したものです。

必要なライブラリ

pip install pypdf

最近のLinuxだと

sudo apt install python3-pypdf

マージプログラム

pmerg.py
from pypdf import PdfReader, PdfWriter

def load_filenames_from_txt(txt_path, encoding='utf-8'):
    """
    指定されたテキストファイルを読み込み、各行をファイル名のリストとして返す関数。
    
    Args:
        txt_path (str): テキストファイルのパス
        encoding (str): ファイルのエンコーディング(デフォルトはutf-8)
        
    Returns:
        list: ファイル名のリスト(空行は除外)
    """
    try:
        with open(txt_path, 'r', encoding=encoding) as f:
            # 1. fをループすることで1行ずつ読み込む
            # 2. line.strip() で前後の空白と改行文字を削除
            # 3. if line.strip() で空行(長さ0の文字列)を除外
            file_list = [line.strip() for line in f if line.strip()]
            
        return file_list

    except FileNotFoundError:
        print(f"エラー: {txt_path} が見つかりませんでした。")
        return []
    except Exception as e:
        print(f"予期せぬエラーが発生しました: {e}")
        return []

# マージするファイル名はmgfile.txtに指定、いくつあってもいいですよー
pdf_files = load_filenames_from_txt('mgfile.txt')
output_filename = 'output.pdf'

# PdfWriterオブジェクトを作成
writer = PdfWriter()

try:
    # 各ファイルをReaderで読み込む
    for pdf_file in pdf_files:
        reader = PdfReader(pdf_file)
        
        # 読み込んだファイルの全ページをWriterに追加
        for page in reader.pages:
            writer.add_page(page)
            
    # 結合した内容をファイルに書き出す
    with open(output_filename, 'wb') as f:
        writer.write(f)
        
    print(f"成功: ファイルを '{output_filename}' として保存しました。")

finally:
    # Writerを閉じる
    writer.close()

でこんなファイルをmgfile.txtという名前で作ります。

Test1.pdf
Test2.pdf

Linuxのシェルだと

ls *.pdf > mgfile.txt

とすればokです。
あとはプログラムを起動!!

python pmerg.py

でoutput.pdfが出来上がります。

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?