Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a Table on a canvas in python using Report Lab

I have a table that i want to display on a canvas in python, i have displayed text in the canvas and i am returning the buffer to return a new FileResponse in another function. My code :

     def Report(dict):
          from reportlab.lib.utils import ImageReader
          buffer = io.BytesIO()
          p = canvas.Canvas(buffer)
          textobject = p.beginText()
          textobject.setTextOrigin(200, 680)
          textobject.textLine('Title')
          p.drawText(textobject)
          logo = ImageReader('static/img/logo.png')
          p.drawImage(logo, 100, 700,width = 400,height=100,mask = None)
          data = [['00', '01', '02', '03', '04'],
        ['10', '11', '12', '13', '14'],
        ['20', '21', '22', '23', '24'],
        ['30', '31', '32', '33', '34']]
          f = Table(data)
          f.setStyle(TableStyle([('BACKGROUND', (1, 1), (-2, -2), 
          colors.green),
                       ('TEXTCOLOR', (0, 0), (1, -1), colors.red)]))

          p.showPage()
          p.save()

          buffer.seek(0)
          return buffer
like image 941
Boutros Avatar asked Nov 28 '18 22:11

Boutros


1 Answers

Table inherits Flowable, in which has a method called drawOn.

width = 400
height = 100
x = 100
y = 800
f = Table(data)
f.wrapOn(p, width, height)
f.drawOn(p, x, y)

Hope this helps.

like image 128
Ryan Lee Avatar answered Nov 01 '22 10:11

Ryan Lee