使用fpdf2生成PDF文件

312 阅读2分钟

有文件需要转换成PDF文件的情况,网上有很多csv转pdf的免费网站,但是使用效果并不好,于是想着使用python包,自己转换。 python版本为3.11.9 1,安装包

pip install fpdf2

2,代码实现

import csv
from fpdf import FPDF

def csv_to_pdf(csv_file, pdf_file):
    pdf = FPDF(orientation='L', unit="mm", format="A4")  #横屏打印,如果想竖屏,orientation参数设定为P
    pdf.add_page()
    pdf.set_title('')  #设定文档属性,并不是第一页的标题
    # 加载Deng 字体
    pdf.add_font('Deng', '', 'Deng.ttf')
    pdf.set_font("Deng", size=13)  # 对标题设定大字体
    pdf.cell(0, 10, '文件标题', 0, 1, 'C')  # 文件标题+居中显示
    pdf.ln(5)  # 标题显示后留空


    # 设置 Deng 字体
    pdf.set_font("Deng", size=4)  # 设置字体大小为4

    # 读取 CSV 文件
    with open(csv_file, newline='', encoding='utf-8') as f:
        reader = csv.reader(f)
        headers = next(reader)

        # 固定列宽,根据栏位的多少,自动计算分配栏位宽度
        total_columns = len(headers)
        column_width = (297 - 20) / total_columns  # A4 纸宽度,左右边距各留 10mm

        
        pdf.set_font("Deng", size=3)  # 设置字体大小为4

        # 输出表头
        for header in headers:
            pdf.cell(column_width, 5, header, 1, 0, 'C')
        pdf.ln()

        # 添加数据行
        for row in reader:
            max_height = 0
            cell_heights = []

            # 计算每个单元格的高度
            for item in row:
                # 计算文本高度
                height = pdf.get_string_width(item) / column_width *1.8
                cell_heights.append(height)
                max_height = max(max_height, height)

            # 如果行超出页面高度,则添加新页
            if pdf.get_y() + max_height > 190:  # 200 = 210 - 10(上边距) - 10(下边距)
                pdf.add_page(same=True)
                pdf.set_font("Deng", size=3)  # 重新设置字体
                for header in headers:
                    pdf.cell(column_width, 5, header, 1, 0, 'C')
                pdf.ln()

            # 输出每个单元格
            for item in row:
                # 创建一个临时单元格以显示边框
                x = pdf.get_x()
                y = pdf.get_y()
                pdf.cell(column_width, max_height, '', 1)  # 边框
                pdf.set_xy(x, y+0.5)
                pdf.multi_cell(column_width, None, item, 0, 'C')
                pdf.set_xy(x + column_width, y)

            pdf.ln(max_height)  # 以最大高度调整行间距

    # 输出为 PDF 文件
    pdf.output(pdf_file)

# 使用函数及设定文件路径
csv_to_pdf('./data/文件名称.csv', './data/文件名称.pdf')

以上是实现的代码,有几个需要注意的地方: 1,字体选择,要和csv的文件字体保持一致,查询到csv文件的字体选择后,将字体的ttf放到python文件的同一目录下; 字体大小可根据文件内栏位的多少自行调节,找到最佳的展示效果。2,代码是第一页有标题和每一页都有表头,可根据具体情况及注释进行删改。3,数据行里的multi_cell函数是内容自动换行输出。

实际打印效果如下:

打印效果图.jpg