在日常開發中,經常需要將大量純文字檔(如日誌、報表、原始碼)統一轉換為 PDF 格式,以便歸檔或列印。Python 的 reportlab 庫提供了強大的 PDF 生成功能,結合檔案系統操作,即可實現批量自動化轉換。
.txt 檔案。reportlab.pdfgen.canvas 建立畫布,設定字型與頁邊距。# -*- 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('.')
encoding='utf-8',避免中文解碼錯誤。text_obj.getY(),超過頁底時呼叫 c.showPage() 並重新 beginText()。multiprocessing 平行處理,顯著縮短轉換時間。| 問題 | 原因 | 解決方法 |
|---|---|---|
| 中文顯示方塊 | 未註冊中文字型 | 使用 pdfmetrics.registerFont(TTFont(...)) 註冊系統字型 |
| 長行文字超出頁面 | 未設定換行寬度 | 使用 text_obj.setTextWidth() 或改用 Paragraph 流式排版 |
| 大檔案記憶體不足 | 一次性讀取整個檔案 | 改用逐行迭代 for line in f: 流式處理 |
此腳本可進一步整合為命令列工具(使用 argparse),支援指定輸入/輸出目錄、自訂字型大小、頁碼樣式等參數,甚至結合 watchdog 監控目錄變化,實現「存檔即自動生成 PDF」的自動化工作流。