1
1

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】TXTファイルを一括PDF化!FPDFで簡単に文字出力する方法

Last updated at Posted at 2025-01-22

PythonでTXTファイルをまとめてPDF化する方法

自分が書いたテキストやログファイルをPDFにしたいとき、皆さんはどのように処理していますか?手作業でコピペするのは手間がかかりますし、複数ファイルを一括で変換したい場合はPythonの自動化が便利です。
この記事では、FPDFというPythonライブラリを使って、特定ディレクトリ内の.txtファイルをまとめてPDFに変換する方法を紹介します。

1. やりたいこと

  • テキストファイル(.txt)をPDFに自動変換したい
  • 複数のテキストファイルがあるとき、まとめて処理したい
  • カスタムフォントを使って文字化けを防ぎたい(日本語対応)

2. 必要なもの

  1. Python3
  2. FPDF ライブラリ
    • pip install fpdf などでインストール可能
  3. 日本語フォント(ここでは NotoSansCJKjp-Regular.ttf を例に解説)

ここからダウンロードできます↑

3. サンプルコード

以下のコードでは、backend/txt_data ディレクトリにあるすべての .txt ファイルを、backend/pdf_output ディレクトリ内にPDFとして出力しています。
※フォントファイルは backend/fonts/NotoSansCJKjp-Regular.ttf に置いている想定です。

import os
from fpdf import FPDF

# PDF作成関数
def txt_to_pdf(txt_file_path, output_pdf_path, font_path):
    pdf = FPDF()
    pdf.set_auto_page_break(auto=True, margin=15)
    pdf.add_page()

    # フォント登録
    pdf.add_font("NotoSans", fname=font_path, uni=True)
    pdf.set_font("NotoSans", size=12)
    
    # テキストファイルの内容をPDFに書き込む
    with open(txt_file_path, "r", encoding="utf-8") as file:
        for line in file:
            pdf.multi_cell(0, 10, line)
    
    pdf.output(output_pdf_path)

# ディレクトリ設定
txt_dir = "backend/txt_data"
pdf_output_dir = "backend/pdf_output"  # PDFを保存するフォルダ
font_path = "backend/fonts/NotoSansCJKjp-Regular.ttf"  # フォントファイルのパス

# PDF出力フォルダが存在しない場合は作成
if not os.path.exists(pdf_output_dir):
    os.makedirs(pdf_output_dir)

# ディレクトリ内のtxtファイルを処理
for filename in os.listdir(txt_dir):
    if filename.endswith(".txt"):
        txt_file_path = os.path.join(txt_dir, filename)
        pdf_file_name = os.path.splitext(filename)[0] + ".pdf"
        output_pdf_path = os.path.join(pdf_output_dir, pdf_file_name)
        
        print(f"Converting {filename} to {pdf_file_name}...")
        txt_to_pdf(txt_file_path, output_pdf_path, font_path)

print(f"PDF conversion completed! Check {pdf_output_dir} for the generated files.")

4. ポイント解説

  1. 日本語フォントの登録
    pdf.add_font("NotoSans", fname=font_path, uni=True)
    pdf.set_font("NotoSans", size=12)
    
    • FPDF はデフォルトで日本語フォントに対応していないので、ここでカスタムフォントを登録します。
    • uni=True でUnicodeを有効にし、日本語文字を扱えるようにしています。
       
  2. 複数の .txt ファイルを一括処理
    for filename in os.listdir(txt_dir):
        if filename.endswith(".txt"):
            # ...
    
    • os.listdir() で指定フォルダ内のファイル一覧を取得し、.txt 拡張子のものだけをPDF化しています。
       
  3. ファイル名変換
    pdf_file_name = os.path.splitext(filename)[0] + ".pdf"
    
    • 元のファイル名(拡張子を除いた部分)に .pdf を付けて出力ファイル名を作成しています。
       
  4. multi_cell を使ってテキストを出力
    pdf.multi_cell(0, 10, line)
    
    • multi_cell は行に収まらない場合の折り返し処理が行われるため、段落の長さに応じて自動的に改行してくれます。

5. 実行方法

  1. ディレクトリ構成例(一例です)
    backend/
    ┣ txt_data/
    ┣ pdf_output/
    ┗ fonts/
        ┗ NotoSansCJKjp-Regular.ttf
    
     
  2. コードを配置
    上記のコードを convert.py などのファイルに書き込みます。
     
  3. ライブラリインストール
    pip install fpdf
    
     
  4. 実行
    python convert.py
    
    pdf_output フォルダに PDF ファイルが出力されれば成功です。

おわりに

この方法を使えば、手動でコピペせずに .txt ファイルを一括で PDF に変換できます。特に大量のテキストデータをPDFとして保管したい場合に有効です。エラーが出ればGPTに聞いてみてください。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?