import re
import os
from reportlab.lib.pagesizes import landscape, A4
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
# 註冊 "kaiu" 字型
pdfmetrics.registerFont(TTFont('kaiu', 'C:/Windows/Fonts/kaiu.ttf'))
# 讀取TXT文件的內容
with open('D:/txt/C318.txt', 'r') as file:
    content = file.readlines()
# 根據分隔符'CSEQ='對內容進行拆分
entries = re.split(r'(CSEQ=)', ''.join(content))
# 處理每個項目
for i in range(1, len(entries), 2):
    cseq = entries[i].strip()
    entry = entries[i + 1]
    if 'MAIL=' in entry:
        mail = entry.split('MAIL=')[1].split('\n')[0].strip()
    else:
        mail = 'NoMail'
    # 根據MAIL的值創建新的文件名
    file_name = f"D:/txt/mail/{mail}.txt"
    if os.path.exists(file_name):
        os.remove(file_name)
    # 將項目寫入新文件
    with open(file_name, 'w') as new_file:
        new_file.write(entry)
    # 將TXT轉換為PDF
    pdf_name = file_name.replace('.txt', '.pdf')
    c = canvas.Canvas(pdf_name, pagesize=landscape(A4))
    c.setFont("kaiu", 10)  # 設定字型
    # 顯示後續內容
    lines = entry.split('\n')
    y = 530  # 設定文字起始位置
    for line in lines:
        c.drawString(20, y, line)
        y -= 20  # 設定每行文字之間的間距
    c.showPage()
    c.save()
    print(f"將CSEQ為{cseq}的項目保存到檔案:{pdf_name}")
想詢問將txt檔轉pdf的問題,目前的問題是檔案有成功轉過來,但PDF檔案中不會新增第二頁顯示內容
參考官方文件
The showPage method causes the canvas to stop drawing on the current page and any further operations will draw on a subsequent page
所以要換頁要自己手動處理