在不使用flowables的情况下构建reportlab表

时间:2018-12-28 12:27:22

标签: python reportlab

我想以pdf格式绘制reportlab表。有没有办法将表格绘制到特定的(x,y)坐标?我没有使用任何流动物体。我只想指定表的位置。 对于绘制图表,我使用“ renderPDF.draw()”。这不适用于表格。

谢谢!

2 个答案:

答案 0 :(得分:1)

我找到了解决方法:

canv = Canvas("phello.pdf")    

data = [['00', '01', '02', '03', '04'],
        ['10', '11', '12', '13', '14'],
        ['20', '21', '22', '23', '24'],
        ['30', '31', '32', '33', '34'],
        ['20', '21', '22', '23', '24'],
        ['20', '21', '22', '23', '24'],
        ['20', '21', '22', '23', '24'],
        ['20', '21', '22', '23', '24']]
t = Table(data)

t.wrap(0, 0) # not sure why this is necessary
t.drawOn(canv, 72, 200) # parameters specify the location of the table
canv.save()

致谢

答案 1 :(得分:0)

如果其他人回答这个问题。

我正在寻找一种使用来自鸭嘴兽的 Table 并添加到画布的方法,因为 TableWidget() 对我不起作用,并提出了以下代码,该代码是从以下代码重新制作的: https://www.blog.pythonlibrary.org/2010/09/21/reportlab-tables-creating-tables-in-pdfs-with-python/

显示更多说明

from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
from reportlab.lib.units import inch, mm
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle

c = canvas.Canvas('testing.pdf', pagesize=A4)
c.setFont('Helvetica', 12, leading=None)

def add_table(self):
    
    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] #width of 5 cols, size of []
            , 4*[0.4*inch]) #height of 4 rows,  size of []
    
    # below shows which 
    t.setStyle(TableStyle([('ALIGN'    ,(1, 1),(-2,-2),'RIGHT')     #instead of -2,-2 you could do 3,2
                         , ('TEXTCOLOR',(1, 1),(-2,-2),colors.red)  #and again here 
                           
                         , ('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)
    ]))
    t.wrapOn(c, 100*mm, 180*mm) #wrap the table to this width, height in case it spills
    t.drawOn(c, 20*mm, 250*mm) #draw it on our pdf at x,y

# for those like me who didn't know, * by inch or mm is because reportlab uses 
# something else to render and if you look at an A4 it has digits:
#                                   (595.2755905511812, 841.8897637795277) 

    
add_table(c)
c.showPage()
c.save()

生成这样的普通 pdf:

Image of the PDF output