python reportlab 生成table (比较全面,一篇足够)

'''
Table(data, colWidths=None, rowHeights=None, style=None, splitByRow=1,
repeatRows=0, repeatCols=0, rowSplitRange=None, spaceBefore=None,
spaceAfter=None)

'''
'''
Table and Tablestyle
TableStyle user Methods
1.TableStyle(commandSequence)
The creation method initializes the TableStyle with the argument command sequence
eg:
    
     LIST_STYLE = TableStyle(
         [('LINEABOVE', (0,0), (-1,0), 2, colors.green),
         ('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black),
         ('LINEBELOW', (0,-1), (-1,-1), 2, colors.green),
         ('ALIGN', (1,1), (-1,-1), 'RIGHT')]
            
2. TableStyle.add(commandSequence)
This method allows you to add commands to an existing TableStyle, i.e. you can build up
TableStyles in multiple statements.
eg:
LIST_STYLE.add('BACKGROUND', (0,0), (-1,0), colors.Color(0,0.7,0.7))
3.TableStyle.getCommands()
This method returns the sequence of commands of the instance.
cmds = LIST_STYLE.getCommands()

4.TableStyle Commands
TableStyle Cell Formatting Commands

FONT - takes fontname, optional fontsize and optional leading.
FONTNAME (or FACE) - takes fontname.
FONTSIZE (or SIZE)- takes fontsize in points; leading may get out of sync.
LEADING- takes leading in points.
TEXTCOLOR- takes a color name or (R,G,B) tuple.
ALIGNMENT (or ALIGN)- takes one of LEFT, RIGHT and CENTRE (or CENTER) or DECIMAL.
LEFTPADDING- takes an integer, defaults to 6.
RIGHTPADDING- takes an integer, defaults to 6.
BOTTOMPADDING- takes an integer, defaults to 3.
TOPPADDING- takes an integer, defaults to 3.
BACKGROUND- takes a color defined by an object, string name or numeric tuple/list,
  or takes a list/tuple describing a desired gradient fill which should
  contain three elements of the form [DIRECTION, startColor, endColor]
  where DIRECTION is either VERTICAL or HORIZONTAL.
ROWBACKGROUNDS- takes a list of colors to be used cyclically.
COLBACKGROUNDS- takes a list of colors to be used cyclically.
VALIGN- takes one of TOP, MIDDLE or the default BOTTOM


TableStyle Line Commands
Line commands begin with the identifier, the start and stop cell coordinates and always follow this with the thickness 
(in points) and color of the desired lines. Colors can be names, or they can be specified as a (R, G, B) tuple, where
 R, G and B are floats and (0, 0, 0) is black. The line command names are: GRID, BOX, OUT- LINE, INNERGRID, LINEBELOW, 
 LINEABOVE, LINEBEFORE and LINEAFTER. BOX and OUTLINE are equivalent, and GRID is the equivalent of applying both BOX 
 and INNERGRID.

#TableStyle Span Commands
Our Table classes support the concept of spanning, but it isn't specified in the same way as html. The style
specification
       SPAN, (sc,sr), (ec,er)
indicates that the cells in columns sc - ec and rows sr - er should be combined into a super cell with con- tents
 determined by the cell (sc, sr). The other cells should be present, but should contain empty strings or you may 
 get unexpected results.

'''
# example
from reportlab.lib.units import inch
from reportlab.pdfgen.canvas import Canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.cidfonts import UnicodeCIDFont

pdfmetrics.registerFont(UnicodeCIDFont('STSong-Light'))
from reportlab.pdfbase.ttfonts import TTFont

pdfmetrics.registerFont(TTFont('hei', 'SIMHEI.TTF'))
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, Table, TableStyle
import time

elements = []

# TableStyle Commands
#  BACKGROUND, and TEXTCOLOR commands
data = [['00', '01', '02', '03', '04'],
        ['10', '11', '12', '13', '14'],
        ['20', '21', '22', '23', '24'],
        ['30', '31', '32', '33', '34']]
t = Table(data,colWidths=[100, 100,100,100,100])
t.setStyle(TableStyle([('BACKGROUND', (1, 1), (-2, -2), colors.green),
                       ('TEXTCOLOR', (0, 0), (1, -1), colors.red)]))

elements.append(t)

data = [['00', '01', '02', '03', '04'],
        ['10', '11', '12', '13', '14'],
        ['20', '21', '22', '23', '24'],
        ['30', '31', '32', '33', '34']]
t = Table(data,colWidths=[100, 100,100,100,100],
          style=[('GRID', (1, 1), (-2, -2), 1, colors.green),
                       ('BOX', (0, 0), (1, -1), 2, colors.red),
                       ('LINEABOVE', (1, 2), (-2, 2), 1, colors.blue),
                       ('LINEBEFORE', (2, 1), (2, -2), 1, colors.pink),
                       ])

elements.append(t)

data = [['00', '01', '02', '03', '04'],
        ['10', '11', '12', '13', '14'],
        ['20', '21', '22', '23', '24'],
        ['30', '31', '32', '33', '34']]
t = Table(data, 5 * [0.4 * inch], 4 * [0.4 * inch])
t.setStyle(TableStyle([('ALIGN', (1, 1), (-2, -2), 'RIGHT'),
                       ('TEXTCOLOR', (1, 1), (-2, -2), colors.red),
                       ('VALIGN', (0, 0), (0, -1), 'TOP'),
                       ('TEXTCOLOR', (0, 0), (0, -1), colors.blue),
                       ('ALIGN', (0, -1), (-1, -1), 'CENTER'),
                       ('VALIGN', (0, -1), (-1, -1), 'MIDDLE'),
                       ('TEXTCOLOR', (0, -1), (-1, -1), colors.green),
                       ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                       ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                       ]))

elements.append(t)
# print(elements)

# TableStyle Line Commands

data = [['00', '01', '02', '03', '04'],
        ['10', '11', '12', '13', '14'],
        ['20', '21', '22', '23', '24'],
        ['30', '31', '32', '33', '34']]
t = Table(data, style=[('GRID', (1, 1), (-2, -2), 1, colors.green),
                       ('BOX', (0, 0), (1, -1), 2, colors.red),
                       ('LINEABOVE', (1, 2), (-2, 2), 1, colors.blue),
                       ('LINEBEFORE', (2, 1), (2, -2), 1, colors.pink),
                       ])

elements.append(t)

data = [['00', '01', '闪电', '03', '04'],
        ['10', '11', '12', '13', '14'],
        ['20', '21', '22', '23', '24'],
        ['30', '31', '32', '33', '34']]
t = Table(data, style=[
    ('FONTNAME', (0, 0), (-1, -1), 'hei'),
    ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
    ('GRID', (1, 1), (-2, -2), 1, colors.green),
    ('BOX', (0, 0), (1, -1), 2, colors.red),
    ('BOX', (0, 0), (-1, -1), 2, colors.black),
    ('LINEABOVE', (1, 2), (-2, 2), 1, colors.blue),
    ('LINEBEFORE', (2, 1), (2, -2), 1, colors.pink),
    ('BACKGROUND', (0, 0), (0, 1), colors.pink),
    ('BACKGROUND', (1, 1), (1, 2), colors.lavender),
    ('BACKGROUND', (2, 2), (2, 3), colors.orange),
])

elements.append(t)

# TableStyle Span Commands

data = [['Top\nLeft', '', '02', '03', '04'],
        ['', '', '12', '13', '14'],
        ['20', '21', '22', 'Bottom\nRight', ''],
        ['30', '31', '32', '', '']]
T = Table(data, style=[
    ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
    ('BACKGROUND', (0, 0), (1, 1), colors.palegreen),
    ('SPAN', (0, 0), (1, 1)),
    ('BACKGROUND', (-2, -2), (-1, -1), colors.pink),
    ('SPAN', (-2, -2), (-1, -1)),
])

print(elements)
doc = SimpleDocTemplate('demo5.pdf')
doc.build(elements)

 

res:

  • 7
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
### 回答1: reportlab是一个Python的PDF生成库,可以用来生成PDF文件,下面是一个简单的示例代码: ```python from reportlab.pdfgen import canvas # 创建一个PDF文档对象 pdf = canvas.Canvas("example.pdf") # 设置字体 pdf.setFont("Helvetica", 12) # 写入文本 pdf.drawString(100, 750, "Welcome to Reportlab!") # 画一个矩形 pdf.rect(50, 50, 200, 100) # 保存PDF文件 pdf.save() ``` 这个示例代码创建了一个PDF文档对象,设置了字体,写入了文本并画了一个矩形,最后保存PDF文件。 你可以根据自己的需求,修改文本内容、字体、位置、颜色等等。更多的使用方法可以查看reportlab的官方文档。 ### 回答2: Python中的reportlab库可以用于生成PDF文件。reportlab是一个强大的工具,可以帮助开发者在Python中创建和定制各种类型的PDF文档。 首先,需要安装reportlab库。可以通过使用pip命令在命令行中运行以下命令来安装reportlab: ```python pip install reportlab ``` 安装完毕后,可以在Python代码中导入reportlab库: ```python from reportlab.pdfgen import canvas ``` 接下来,可以创建一个canvas对象来构建PDF文件。Canvas是reportlab库中最基本的对象之一,它允许开发者在PDF页面上进行各种操作。通过调用canvas对象的方法,可以绘制文本、图片、图形等。 例如,以下代码演示了如何创建一个PDF文件并在其中添加一些文本: ```python from reportlab.pdfgen import canvas # 创建一个canvas对象,指定PDF文件路径和名称 pdf = canvas.Canvas("example.pdf") # 在(100, 750)位置添加一段文本 pdf.setFont('Helvetica', 12) pdf.drawString(100, 750, "Hello, World!") # 关闭canvas对象,保存PDF文件 pdf.save() ``` 运行以上代码后,将在当前目录下生成一个名为example.pdf的PDF文件。在该文件中,将添加一个位置在(100, 750)的文本“Hello, World!”。 总结:使用reportlab库中的canvas对象和相应的方法,可以轻松地在Python生成并定制各种类型的PDF文件。以上是一个简单的示例,你可以根据自己的需求进一步扩展和定制PDF文档。 ### 回答3: 使用python中的第三方库ReportLab可以很方便地生成PDF文件。ReportLab是一个用于创建PDF文档的强大工具,可以在Python中使用它来生成报告、统计图表、标签等。 首先,在使用ReportLab之前,需通过pip安装ReportLab库。 ``` pip install reportlab ``` 然后,我们需要创建一个画布对象来绘制我们的PDF文件。 ```python from reportlab.pdfgen import canvas # 创建一个PDF文件 pdf = canvas.Canvas("output.pdf") # 绘制文本 pdf.drawString(100, 750, "Hello World!") # 保存PDF文件 pdf.save() ``` 以上示例代码创建了一个名为output.pdf的PDF文件,并在画布上绘制了一个"Hello World!"的文本。使用`drawString`方法,可以设置文本的位置和内容。在绘制完所需内容后,通过`save`方法可以保存生成的PDF文件。 除了绘制文本,ReportLab还提供了许多其他功能,如绘制图像、绘制表格、设置页面布局等。可以通过查阅ReportLab的官方文档来学习更多相关的用法,进一步定制生成自己需要的PDF文件。 使用ReportLab生成PDF文件是一种简单而强大的方法,可以应用于许多场景,如生成报告、生成标签、生成图表等。无论是个人使用还是商业应用,ReportLab提供了丰富且灵活的功能来满足不同的需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值