from reportlab.platypus import Table, KeepTogether
from reportlab.lib import colors
from reportlab.lib.units import mm
import datetime, decimal
import moneta, dtutil
class pdftable (object):
aleft = 0
aright = 1
acenter = 2
def __init__( self, titolo=None, hastotal=False, cname=False, vclean=False ):
self.titolo = titolo
self.hastotal = hastotal
self.cname = cname
self.vclean = vclean
self.rrows = 1
def getdata( self, crs ): return list()
def getlcol( self ): return list()
def hsize( self ): return sum( self.lsize() )
def lnames( self ): return [ c[0] for c in self.lcol ]
def lsize( self ): return [ c[1] for c in self.lcol ]
def getstyle( self ):
lst = list()
lst.append( ['TOPPADDING', (0,0), (-1,-1), 2 ] )
lst.append( ['BOTTOMPADDING', (0,0), (-1,-1), 2] )
lst.append( ['GRID', (0,0), (-1,-1), 0.25, colors.black] )
if self.titolo: lst.append( ['SPAN', (0,0), (-1,0) ] )
return lst
def getcolstyle( self ):
st = list()
ir = (0,1)[self.titolo != None]
for i, c in enumerate( self.lcol ):
if c[2] & self.aright:
st.append( ['ALIGN', (i,ir), (i,-1), 'RIGHT'] )
if c[2] & self.acenter:
st.append( ['ALIGN', (i,ir), (i,-1), 'CENTER'] )
return st
def calc_totali( self, data ):
'riga totale'
rtot = list()
for ic, col in enumerate( self.lcol ):
if col[3] == None: rtot += [None]
elif col[3] == 'S':
lv = [ riga[ic] for riga in data ]
rtot += [ sum( lv ) ]
else: rtot += [ col[3] ]
return rtot
def clean( self, ldata ):
''' pulisci i dati (es. None == '') '''
return [ [ self.cleanvalue( val ) for val in riga ] for riga in ldata ]
def cleanvalue( self, val ):
if val == None: rval = ''
elif isinstance( val, datetime.date ):
rval = dtutil.date_serializer( val )
elif isinstance( val, decimal.Decimal ):
rval = moneta.ocurrency( val )
else: rval = val
return rval
def make( self, crs=None ):
self.lcol = self.getlcol()
nc = len( self.lcol )
ldata = list()
if self.titolo:
ltit = [ self.titolo ] + ([''] * (len( self.lcol ) - 1))
ldata += [ ltit ]
if self.cname: ldata += [ self.lnames() ]
mdata = self.getdata( crs )
if self.hastotal: mdata += [ self.calc_totali( mdata ) ]
if self.vclean: mdata = self.clean( mdata )
ldata += mdata
rrows = (self.rrows,self.rrows + 1)[self.titolo != None]
lst = self.getstyle() + self.getcolstyle()
return Table( ldata, self.lsize(), None, lst, rrows, 0, 1 )