萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

使用 Python ReportLab 批量將目錄下文本檔案轉換為 PDF

前言

在日常開發中,經常需要將大量純文字檔(如日誌、報表、原始碼)統一轉換為 PDF 格式,以便歸檔或列印。Python 的 reportlab 庫提供了強大的 PDF 生成功能,結合檔案系統操作,即可實現批量自動化轉換。

核心實現步驟

  1. 掃描指定目錄,篩選出所有 .txt 檔案。
  2. 對每個文字檔建立對應的 PDF 輸出路徑。
  3. 使用 reportlab.pdfgen.canvas 建立畫布,設定字型與頁邊距。
  4. 逐行讀取文字內容,寫入 PDF 文字物件,並自動處理分頁。
  5. 儲存並關閉畫布。

完整程式碼範例

# -*- coding: utf-8 -*-
import os
from reportlab.lib.units import inch
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

# 註冊中文字型(請根據實際路徑調整)
pdfmetrics.registerFont(TTFont('MicrosoftJhengHei', 'C:/Windows/Fonts/msjh.ttc'))

def text_file_to_pdf(txt_path, pdf_path):
    """將單一文字檔轉換為 PDF"""
    c = canvas.Canvas(pdf_path)
    c.setFont('MicrosoftJhengHei', 10)
    text_obj = c.beginText()
    text_obj.setTextOrigin(inch, 11 * inch)  # 左上角起始位置

    with open(txt_path, 'r', encoding='utf-8') as f:
        for idx, line in enumerate(f, 1):
            line = line.rstrip('\n')
            # 加上行號,方便閱讀
            text_obj.textLine(f'{idx:03d}: {line}')

    c.drawText(text_obj)
    c.showPage()
    c.save()

def batch_convert(directory='.'):
    """批量轉換目錄下所有 .txt 檔案"""
    for fname in os.listdir(directory):
        if fname.lower().endswith('.txt'):
            txt_full = os.path.join(directory, fname)
            pdf_full = os.path.splitext(txt_full)[0] + '.pdf'
            text_file_to_pdf(txt_full, pdf_full)
            print(f'已轉換: {fname} -> {os.path.basename(pdf_full)}')

if __name__ == '__main__':
    batch_convert('.')

關鍵點說明

  • 字型註冊:ReportLab 內建字型不支援中文,必須註冊 TrueType 字型(如微軟正黑體),否則中文會顯示為亂碼或方塊。
  • 編碼處理:讀取文字檔時指定 encoding='utf-8',避免中文解碼錯誤。
  • 分頁邏輯:範例為簡化未實作自動分頁;實際專案中需監測 text_obj.getY(),超過頁底時呼叫 c.showPage() 並重新 beginText()。
  • 效能考量:大量檔案時可搭配 multiprocessing 平行處理,顯著縮短轉換時間。

常見問題與解決方案

問題原因解決方法
中文顯示方塊未註冊中文字型使用 pdfmetrics.registerFont(TTFont(...)) 註冊系統字型
長行文字超出頁面未設定換行寬度使用 text_obj.setTextWidth() 或改用 Paragraph 流式排版
大檔案記憶體不足一次性讀取整個檔案改用逐行迭代 for line in f: 流式處理

延伸應用

此腳本可進一步整合為命令列工具(使用 argparse),支援指定輸入/輸出目錄、自訂字型大小、頁碼樣式等參數,甚至結合 watchdog 監控目錄變化,實現「存檔即自動生成 PDF」的自動化工作流。

copyright © 萬盛學電腦網 all rights reserved