gpt4 book ai didi

Python ReportLab——表格对于页面来说太宽

转载 作者:行者123 更新时间:2023-12-01 05:01:04 51 4
gpt4 key购买 nike

我正在使用 Python 的 ReportLab 包在 PDF 文件中创建一个表格,但该表格对于页面来说太宽,并且第一列和最后一列被截断。这是我正在使用的代码示例。

    t = Table(data, style=[("INNERGRID", (0,0), (-1,-1), 0.25, colors.black),("BOX", (0,0), (-1,-1), 0.25, colors.black)])

我尝试过使用 splitbyRow 和类似的参数,但似乎都不起作用。如何轻松地使表格适合页面?

最佳答案

您可以使用该页面的框架获取页面宽度。当您使用 colWidths 关键字时,您应该知道有多少可用空间:

table = ar.Table(data, colWidths=columnWidths)#there is also rowHeights=
table.setStyle(tableStyle)

当表格在构建时自行绘制时,您必须配置表格,以便它使用将要绘制的框架的可用宽度。

可以计算这些 colWidths,以便它们使用可用空间。为了展示这一点,我必须使用一个扩展示例,我将尝试不使用:

首先,您应该定义自己的文档类,该类继承自 BaseDocTemplate:

class MyDocTemplate(BaseDocTemplate):
def __init__(self, filename):
BaseDocTemplate.__init__(self, filename)
#there are more keyword
#arguments you can pass
#pagesize=A4,
#leftMargin=leftMargin,
#rightMargin=rightMargin,
#topMargin=topMargin,
#bottomMargin=bottomMargin,
#title=title,
#author=author,
#subject=subject,
#creator=creator)

然后,如果您创建文档:

doc = MyDocTemplate(fileName)

您可以通过文档类中的自定义函数获取框架的宽度:

frame = doc.getFrame('FirstL')
width = frame._aW

这个函数看起来像:

def getFrame(self,framename,orientation="Portrait"):
"""
returns frame
frame._x1,frame._y1
frame._width,frame._height
frame._leftPadding,frame._bottomPadding
frame._rightPadding,frame._topPadding
"""

f = attrgetter("id")
frame = None

for temp in self.pageTemplates[::-1]:
if f(temp) == framename:
#print( temp.id )
for frame in temp.frames:
print( frame.id )
if f(frame) == orientation:

return frame

reportlab 相当复杂,我尝试解释,但没有详细解释如何将页面模板注册为文档类上的列表

pageTemplates 是一个可以添加页面模板的列表:

templates.append( PageTemplate(id='FirstL',frames=frameL,onPage=onFirstPage,pagesize=pagesize) )

onFirstPage 是一个函数,它使用以下方案:

def drawFirstPage(canv,doc):
"""
This is the Title Page Template (Portrait Oriented)
"""
canv.saveState()
#set Page Size or do some other things on the canvas
frame = doc.getFrame('FirstP')

canv.setPageSize( frame.pagesize )
canv.setFont(_baseFontName,doc.fontSize)

canv.restoreState()

当您添加这样的页面模板时,建议的功能应该可以工作:

doc.addPageTemplates(templates)

关于Python ReportLab——表格对于页面来说太宽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26207804/

51 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com