iT邦幫忙

0

詢問將txt檔轉pdf的問題

  • 分享至 

  • xImage
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檔案中不會新增第二頁顯示內容

iT邦新手 4 級 ‧ 2023-08-08 14:59:40 檢舉
怎麼不用</>這個,截圖沒有比較好吧(?
淺水員 iT邦大師 6 級 ‧ 2023-08-09 01:06:28 檢舉
貼程式碼可參考:https://ithelp.ithome.com.tw/markdown#mk_fenced
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
淺水員
iT邦大師 6 級 ‧ 2023-08-09 12:30:03
最佳解答

參考官方文件

The showPage method causes the canvas to stop drawing on the current page and any further operations will draw on a subsequent page

所以要換頁要自己手動處理

    current_page = 1
    for line in lines:
        if y < page_bottom + line_height:
            c.showPage()
            current_page += 1
            y = 350

        c.drawString(20, y, line)
        y -= line_height

        if current_page >= 1:  # 顯示頁碼
            c.setFont("kaiu", 10)

    c.save()

    print(f"將CSEQ為{cseq}的項目保存到檔案:{pdf_name}")

我要發表回答

立即登入回答