欢迎光临
我们一直在努力

python 生成pdf 表格文件

# -*- coding=utf-8 -*-
# 使用reportlab,注册中文字体

from reportlab.lib import colors
from reportlab.lib.pagesizes import A4, A3,A2,A1,landscape
from reportlab.platypus import Table, TableStyle
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import Paragraph, SimpleDocTemplate
from reportlab.lib.styles import getSampleStyleSheet


data = [["Title:","","","",""],
    ["Letter", "Number", "Stuff", "Long stuff that should be wrapped", u"备注"],
    ["A", "01", "ABCD", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", ""],
    ["B", "02", "CDEF", "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB", ""],
    ["C", "03", "SDFSDF", "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC", ""],
    ["D", "04", "SDFSDF", "DDDDDDDDDDDDDDDDDDDDDDDD DDDDDDDDDDDDDDDDDDDDDDDDDDDDDD", ""],
    ["E", "05", "GHJGHJGHJ", "EEEEEEEEEEEEEE EEEEEEEEEEEEEEEEE EEEEEEEEEEEEEEEEEEEE", ""],
]


def make_pdf_file(lista, file_name):
    pdfmetrics.registerFont(TTFont('hei', 'simhei.ttf'))
    doc = SimpleDocTemplate(file_name, pagesize=A4, rightMargin=20, leftMargin=20, topMargin=20,
                            bottomMargin=18)
    doc.pagesize = landscape(A4)
    elements = []
    new_data = make_pdf_list(lista)   
    style = TableStyle([
                        ('ALIGN', (0,0), (-1, -1), 'CENTER'), # 所有行左右居中,
                        ('VALIGN', (0,0), (-1, -1), 'MIDDLE'), # 所有行上下居中
                        ('FACE',(0,0),(-1,-1),'hei'), #字体 
                        ('FONTSIZE',(1,1),(-1,-1),12),
                        ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                        ('BOX', (0, 0), (-1, -1), 0.25, colors.black)                   
                      ])
    stylesheet = getSampleStyleSheet()
    body_style = stylesheet["BodyText"]
    body_style.wordWrap = 'CJK'
    body_style.fontName = 'hei'
    body_style.fontSize = 12
    para_data = [[Paragraph(cell, body_style) for cell in row] for row in new_data]
    table = Table(para_data, colWidths=[50, 80, 80, 80,100, 50, 80, 80, 50])
    table.setStyle(style)
    elements.append(table)
    doc.build(elements)
make_pdf_file(data, '喵喵.pdf')

如上,主要是用了reportlab这个库,然后在生成pdf文档时,表格用了格式去组织表格内容,包括自动换行等,注意需要有字体的支持。

赞(0) 打赏
未经允许不得转载:乌西塔 » python 生成pdf 表格文件

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

微信扫一扫打赏