DEV Community

drake
drake

Posted on

将中文txt文档转为PDF

pip install fpdf

Enter fullscreen mode Exit fullscreen mode
  • 代码

from fpdf import FPDF

class PDF(FPDF):
    def __init__(self):
        super().__init__()
        # 添加中文字体(以苹方为例,macOS默认字体)
        self.add_font('kaiti', '', './kaiti.ttf', uni=True)

    def footer(self):
        self.set_y(-15)
        self.set_font('kaiti', '', 8)  # 设置中文字体
        self.cell(0, 10, f'{self.page_no()}', 0, 0, 'C')  # 页脚


class Topdf:
    def __init__(self, pdf_source_path, txt_file_path):
        # PDF文件路径
        self.pdf_file = pdf_source_path
        # 输出的TXT文件路径
        self.txt_file = txt_file_path

    def to_pdf(self):
        # 创建PDF对象
        pdf = PDF()
        pdf.set_left_margin(10)
        pdf.set_right_margin(10)
        pdf.add_page()

        pdf.set_auto_page_break(auto=True, margin=15)
        pdf.set_font('kaiti', '', 12)

        # 读取TXT文件并优化文本内容
        with open(self.txt_file, 'r', encoding='utf-8') as file:
            text = file.read()

        # 将优化后的文本添加到PDF
        pdf.multi_cell(0, 10, text)
        # 保存PDF文件
        pdf.output(self.pdf_file)
        print(f"TXT内容已成功保存到 {self.pdf_file}")


Enter fullscreen mode Exit fullscreen mode

Top comments (0)