def callFunction(self, functionName, value=None, parameter=None): """ Call a function by its functionName """ value = value or '' parameter = parameter or '' if functionName == 'trunc': if value == '' or parameter == '': return '' else: return Sla2pdfUtils.truncValue(value, int(parameter)) elif functionName == 'approx': if value == '' or parameter == '': return '' else: return Sla2pdfUtils.approxValue(value, int(parameter)) elif functionName == 'itformat' or functionName == 'itformatdataora': if value == '': return '' else: return Sla2pdfUtils.itformatValue(value) elif functionName == 'itformatdata': if value == '': return '' else: return Sla2pdfUtils.itformatValue(value,tronca=True) elif functionName == 'bcview': if value == '': return '' else: #bcvalueTag= Sla2pdfUtils.bcviewValue(value, parameter) #return bcvalueTag return value else: return ''
def translate(self): self.pageProperties = Sla2pdfUtils.pageProFunc(self.document) self.canvas = Canvas(filename = self.pdfFolder + self.pdfFileName + '.pdf', pagesize=(self.pageProperties[0][8],self.pageProperties[0][7])) # Page's table reiter = False self.pdfPage = 0 for e in xrange(0, self.numPages): self.pdfPage = e for group in self.tablesProperties: self.group = group.keys()[0] self.tablesPropertie = group.values()[0] try: self.group= self.group.strip().split('%%%')[0] except: self.group= self.group.strip() if self.group in self.iteratableGroups: colu = int(self.tablesPropertie['columns']) self.tablesPropertie['iterproper'] = self.tablesPropertie['parasobj'][colu:(colu*2)] reiter = True cells = int(self.tablesPropertie['cells']) # Closing pages (elements of the same page must be near) if "noGroup" in self.group and self.tablesPropertie["pfile"] != "" : #print "IMMAGINEEEEEEEEEEEEEEE", self.group, self.tablesPropertie["isTableItem"] self.drawImage(group=self.group) # IMMAGINE elif "noGroup" in self.group and self.tablesPropertie["pfile"] == "": #print "MONOCELLAAAAAAA", self.group, self.tablesPropertie self.drawTable(group =self.group, monocell=True)# MONOCELLA else: # print "TABELLAAAAAAAA", self.group, self.tablesPropertie["isTableItem"] self.drawTable(group =self.group, reiter = reiter) # TABELLA self.canvas.saveState() self.canvas.showPage() self.canvas.save()
def labelSla(self): """ FIXME: Grave bug , non lascia il testo semplice nella cella in cui è presente anche un tag ... """ self.labelObj = self.slaPageObjects() index = -1 gr = [] for pageObject in self.labelObj: itexts = pageObject.findall('ITEXT') group = pageObject.get('GROUPS') if group in gr: for itext in itexts: attributes = itext.items() dictionary = {} for kk in range(0, len(attributes)): dictionary[attributes[kk][0]] = attributes[kk][1] ch = dictionary['CH'] tags = Sla2pdfUtils.findTags(ch) #print "tagsssss", ch, tags if tags: tagsKeys = tags.keys()[0] or [] function = tags[tagsKeys]['function'] parameter = tags[tagsKeys]['parameter'] if function == "bcview": bc = str(self.objects[index][tagsKeys]) if bc == "None": bc = "0000000000000" value = "bcview;%s;%s;%s" %(bc, str(tags[tagsKeys]['parameter'].split('X')[0]), str(tags[tagsKeys]['parameter'].split('X')[1])) or "" elif tagsKeys in self.timeTags: value = Sla2pdfUtils.getNowValue(tagsKeys) else: value = self.objects[index][tagsKeys] or "" if function in self.formatFunctions and "X" not in parameter: resolvedTag = self.callFunction(function, str(value), int(parameter)) value = ch.replace(tags[tagsKeys]['completeTag'], resolvedTag) else: value = str(value) else: value = ch #print "valueeeeeeeeeeeeee", value itext.set('CH', str(value)) else: gr.append(group) index += 1
def alignmentFunc(self,paras, v, monocell=False, reiter=False): if monocell==True: slaAlignment = paras[0].get('ALIGN') elif reiter ==True: slaAlignment = paras[0].get('ALIGN') else: slaAlignment = paras[v][0].get('ALIGN') if slaAlignment == None: slaAlignment = self.slaStyleDefault() pdfAlignment= Sla2pdfUtils.alignment(slaAlignment) return pdfAlignment
def findTablesAndTags(self): """ Questa funzione crea DUE e dico DUE dizionari, uno con chiave gruppo e valore tags e l'altro con i tags come chiave e il gruppo come valore. il secondo DICT lo trovo assurdo, temo che non consideri campi Dao doppi nel templates e la cosa NON mi piace. NON ho tempo adesso per verificare TODO: Verificare il dizionario tagsTables. ... """ group = '' vector = [] self.tablesTags = {} # relation group -> tags self.tagsTables = {} # relation tag -> group for pageObject in self.slaPageObjects(): isTableItem = (pageObject.get('isTableItem') == "1") if not isTableItem: continue group = str(pageObject.get('GROUPS')).strip() if group: itexts = pageObject.findall('ITEXT') ch = '' if group in self.tablesTags: vector = self.tablesTags[group] else: vector = [] for i in itexts: ch = str(i.get('CH')) # print " CHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH", ch if ch.replace(' ', '') == '': continue tags = Sla2pdfUtils.findTags(ch) # print "TAAAAAAAAAAAAAAGSSS", tags, vector if tags is not None: if tags not in vector: vector.append(tags) for k in tags.keys(): self.tagsTables[k] = group self.tablesTags[group] = vector
def drawTable(self, group=None, monocell=None, reiter = None): """ Drawing a table """ matrix = [] lst = [] matrix2 = [] vector = [] # Total of element's table cells = int(self.tablesPropertie['cells']) columns = int(self.tablesPropertie['columns']) rows = int(self.tablesPropertie['rows']) widths = self.tablesPropertie['widths'] heights = self.tablesPropertie['heights'] xpos = self.tablesPropertie['xpos'] ypos = self.tablesPropertie['ypos'] # print "DATI", cells, columns, rows, group, heights, widths contColumns = 0 ch = '' col = 0 cycle = False vector = [] alignment= None itexts = self.tablesPropertie['itextsobj'] paras = self.tablesPropertie['parasobj'] stile = TableStyle([]) stile.add('VALIGN',(0,0),(-1,-1),'TOP') tblprop = self.tablesPropertie['cellProperties'] if monocell==True: cells = 1 columns=1 rows = 1 for v in xrange(0,cells): if v == 0: contRows = 0 contColumns = 0 elif columns==1: contColumns = -1 contRows= int(v/columns) else: contRows= int(v/columns) contColumns = ((v)%columns) background = self.backgroundFunc(tblprop[v])# Finding background hexBorderColor = self.hexBorderColorFunc(tblprop[v]['borderColor']) stile.add('ROWBACKGROUNDS', (contColumns,contRows), (contColumns,contRows), (background, background)) cellpr = tblprop[v] cellpict = cellpr['cellPicture'] cellIMGHeight = cellpr['cellHeight'] cellIMGWidth = cellpr['cellWidth'] if (cellpr['bottomLine'] == 1 and cellpr['topLine'] == 1 and\ cellpr['leftLine'] == 1 and cellpr['rightLine'] == 1): stile.add('BOX', (contColumns,contRows), (contColumns,contRows), cellpr['lineWidth'], hexBorderColor) else: if cellpr['bottomLine'] == 1: stile.add('LINEBELOW', (contColumns,contRows), (contColumns,contRows), cellpr['lineWidth'], hexBorderColor) elif cellpr['topLine'] == 1: stile.add('LINEABOVE', (contColumns,contRows), (contColumns,contRows), cellpr['lineWidth'], hexBorderColor) if cellpr['leftLine'] == 1: stile.add('LINEBEFORE', (contColumns,contRows), (contColumns,contRows), cellpr['lineWidth'], hexBorderColor) if cellpr['rightLine'] == 1: stile.add('LINEAFTER', (contColumns,contRows), (contColumns,contRows), cellpr['lineWidth'], hexBorderColor) if not monocell: ch = self.chFunc(itexts[v])[0] itext = self.chFunc(itexts[v])[1] else: try: itext = itexts[0] ch = itexts[0].get('CH') except: itext = None ch = "" # self.chFunc(itexts[0])[1] actualPageObject = self.tablesPropertie# Borders uff = self.tablesPropertie['iterproper'] if uff != [] and v > columns: pdfAlignment = self.alignmentFunc(self.tablesPropertie['iterproper'][contColumns],v, reiter=True) else: pdfAlignment = self.alignmentFunc(paras, v, monocell) #alignment stile.add('ALIGN', (contColumns,contRows), (contColumns,contRows), pdfAlignment) if itext != None: fontName = self.fontNameFunc(itext) # Font name stile.add('FONT', (contColumns,contRows), (contColumns,contRows), fontName) fontSize = self.fontSizeFunc(itext)# Font size stile.add('FONTSIZE', (contColumns,contRows), (contColumns,contRows), fontSize) foreground = self.foregroundFunc(itext) #foreground stile.add('TEXTCOLOR', (contColumns,contRows), (contColumns,contRows), foreground) if "bcview" in ch: alignment="LEFT" vector.append(Sla2pdfUtils.createbarcode(ch)) else: vector.append(Sla2pdfUtils.makeParagraphs(ch, background, foreground, alignment, fontName, fontSize)) elif cellpict: (imgPath, imgFile) = os.path.split(cellpict) path = Environment.imagesDir + imgFile widthIMG = (float(cellIMGHeight)-2)*100/(float(cellIMGWidth)-2) img = Image(path,width=widthIMG,height=float(cellIMGHeight)-2) vector.append(img) else: vector.append('') if monocell==True: cycle= True elif ((v+1)%columns) == 0: contRows = 0 cycle= True if cycle == True: matrix.append(vector) vector = [] cycle = False # if columns > 1 and not reiter: # #wid = [] # hei = [] # for h in range(0,len(heights),rows): # hei.append(heights[h]) # heights = hei table=Table(matrix,style=stile, colWidths=widths[:columns], rowHeights=heights[:rows]) lst.append(table) # Effective table size sumRows = Sla2pdfUtils.sumRowsFunc(heights,rows) sumColumns = Sla2pdfUtils.sumColumnsFunc(widths,columns) f = Frame(x1=(xpos[0] - self.pageProperties[self.pdfPage][9]), y1=(self.pageProperties[self.pdfPage][7] - ypos[0] - sumRows + self.pageProperties[self.pdfPage][10] - 12), width=sumColumns, height=(sumRows+12), showBoundary=0) sumRows = sumColumns = 0 f.addFromList(lst, self.canvas) reiter = False
def fontNameFunc(self, itext, monocell=False): if self.version: fontName = Sla2pdfUtils.getPdfFontName(str(itext.get('FONT'))) else: fontName = Sla2pdfUtils.getPdfFontName(str(itext.get('CFONT'))) return fontName
def fillDocument(self): """ Replacing tags with real values """ self.pageObjects = self.slaPageObjects() iterator = 0 while iterator < self.lenPageObjects(): pageObject = self.slaPageObjects()[iterator] isTableItem = pageObject.get('isTableItem') pageNumber = int(pageObject.get('OwnPage')) + 1 group = str(pageObject.get('GROUPS')).strip() try: group= group.strip().split('%%%')[0] except: group = group pfile = pageObject.get('PFILE') if (pfile != ''): iterator += 1 continue if group: actualGroup = group if str(actualGroup).strip() not in self.iteratableGroups: # Replacing non-iterator tags itexts = pageObject.findall('ITEXT') for itext in itexts: ch = str(itext.get('CH')) tags = Sla2pdfUtils.findTags(ch) #print "Stampo il tag", tags if tags is not None: tagsKeys = tags.keys() #print "Dizionario dei tags tagsKeys", tagsKeys for tagkey in tagsKeys: if tagkey.replace(' ', '') == '': continue #try: resolvedTag = '' function = tags[tagkey]['function'] #print "function" , function parameter = tags[tagkey]['parameter'] #print "parameter", parameter if "X" in parameter: parameter = parameter.split("X") if tagkey == 'currentPage': value = pageNumber elif tagkey == 'totalPage': value = self.pagesNumber elif tagkey in self.timeTags: value = Sla2pdfUtils.getNowValue(tagkey) else: if self.cycle <= (len(self.objects) - 1): value = self.objects[self.cycle][tagkey] or '' else: value = '' # Function if function in self.formatFunctions: resolvedTag = self.callFunction(function, value, parameter) else: resolvedTag = str(value) ch = ch.replace(tags[tagkey]['completeTag'], resolvedTag) # Save itext itext.set('CH', ch) else: if isTableItem != '1': iterator += 1 continue itexts = pageObject.findall('ITEXT') for itext in itexts: ch = str(itext.get('CH')) if (ch.find('<<') > -1) and (ch.find('>>') > -1): while (ch.find('<<') > -1) and (ch.find('>>') > -1): arrayIndex = int(ch[ch.find('<<')+2:ch.find('>>')]) ch = ch.replace(('<<%d>>' % arrayIndex), '') else: arrayIndex = -1 tags = Sla2pdfUtils.findTags(ch) if tags is not None: tagsKeys = tags.keys() for k in tagsKeys: if k.replace(' ', '') == '': continue #try: resolvedTag = '' function = tags[k]['function'] parameter = tags[k]['parameter'] if k == 'currentPage': value = pageNumber elif k == 'totalPage': value = self.pagesNumber elif k in self.timeTags: value = Sla2pdfUtils.getNowValue(k) else: indexN = k.find('(n)') if (indexN != -1): indexNP = k.find('(n).') if (indexNP != -1): arrayName = k[:indexNP] tagName = k[indexNP+4:] if self.cycle <= (len(self.objects) - 1): if arrayIndex <= (len(self.objects[self.cycle][arrayName]) - 1): arraySource = self.objects[self.cycle][arrayName][arrayIndex] value = arraySource[tagName] or '' else: value = '' else: value = '' else: tagName = k[:indexN] if arrayIndex <= (len(self.objects) - 1): arraySource = self.objects[arrayIndex] value = arraySource[tagName] or '' else: value = '' else: if self.cycle <= (len(self.objects) - 1): value = self.objects[self.cycle][k] or '' else: value = '' # Function if function in self.formatFunctions: resolvedTag = self.callFunction(function, value, parameter) else: resolvedTag = str(value) ch = ch.replace(tags[k]['completeTag'], resolvedTag) # Save itext itext.set('CH', ch) iterator += 1 #self.pageObjectPropertiesDict() if not self.label: self.findTablesProperties() self.doc.write('___temp.sla')
def duplicateTags(self): self.pageObjects = self.slaPageObjects() for pageObject in self.pageObjects: isTableItem = pageObject.get('isTableItem') == "1" group = str(pageObject.get('GROUPS')).strip() try: group= group.strip().split('%%%')[0] except: group= group if group: self.pageNumber = int(pageObject.get('OwnPage')) + 1 self.tableGroup = self.indexGroupTableFromListDict(group) if isTableItem and (group in self.iteratableGroups): # Qui vengono gestite le tabelle iterabili , e le righe itexts = pageObject.findall('ITEXT') paras = pageObject.findall('para') pages = self.slaPage() cell = int(pageObject.get('OwnLINK')) + 1 columns = self.tableGroup['columns'] row = (cell / columns) + 1 column = (cell % columns) if not (len(itexts) > 0): # first row of the table (with itext) itext = self.tableGroup['itexts'][column - 1].copy() if itext == {}: continue ch = str(itext['CH']) tags = Sla2pdfUtils.findTags(ch) if tags is None: continue tmp = ch tagsKeys = tags.keys() increment = True for k in tagsKeys: if k.replace(' ', '') == '': continue if k.find('(n)') > -1: tmp = self.getTagToPrint(tmp, column = column, increment=increment, tags=tags,k=k) increment = False itext['CH'] = tmp ElementTree.SubElement(pageObject, 'ITEXT', itext) else: # next rows of the table (without itext) # banalmente è la prima riga della tabella es: U.M, DESCRIZIONE itext = itexts[0] ch = str(itext.get('CH')) tags = Sla2pdfUtils.findTags(ch) if tags is not None: tmp = ch tagsKeys = tags.keys() increment = True for k in tagsKeys: if k.replace(' ', '') == '': continue if k.find('(n)') > -1: if self.tableGroup['itexts'][column - 1] == {}: self.tableGroup['itexts'][column - 1] = dict([attribute[0], attribute[1]] for attribute in itext.items()) tmp = self.getTagToPrint(tmp,column = column, increment=increment, tags=tags,k=k) increment = False itext.set('CH', tmp) else: # Qui vengono gestite le tabelle e le celle con tag non iteranti itexts = pageObject.findall('ITEXT') if len(itexts) > 0: itext = itexts[0] ch = str(itext.get('CH')) tags = Sla2pdfUtils.findTags(ch) if tags is not None: tmp = ch if "€" in ch or "Euro" in ch: mettilo = True tagsKeys = tags.keys() increment = True for k in tagsKeys: if k.replace(' ', '') == '': continue tmp = self.getTagToPrint(tmp,increment=increment, tags=tags, k=k) # print " TEEEEMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMP", tmp, ch increment = False prova = ch.replace(tmp,"") if "EUR" in prova.upper() : prova = "€ " # if prova: itext.set('CH',prova +tmp )
def duplicateElementLabel(self): """ Funzione base per la gestione delle frontaline: La gestione frontaline ha problematiche differenti rispetto ai report ed alle stampe singole. Il template contiene una frontalina di base che deve essere replicata enne volte quante dovuto uguale a se stessa per poi gestirne i tag rendendoli "iteranti". La parte meno complessa è quella della traduzione in pdf in quanto lo sla finito non rappresenta complessità particolari """ numPages = self.slaPage() document = self.slaDocumentTag() self.pageProperties = Sla2pdfUtils.pageProFunc(document) group = self.tablesProperties[0].keys()[0] self.tablesPropertie = self.tablesProperties[0][group] widths = self.tablesPropertie['widths'] heights = self.tablesPropertie['heights'] cells = int(self.tablesPropertie['cells']) columns = int(self.tablesPropertie['columns']) rows = int(self.tablesPropertie['rows']) sumRows = Sla2pdfUtils.sumRowsFunc(heights,rows) sumColumns = Sla2pdfUtils.sumColumnsFunc(widths,columns) otherColumn = sumColumns +(int(setconf("Label", "sistemacolonnafrontaline")) or 0) sumRows = sumRows + (int(setconf("Label", "sistemarigafrontaline")) or 0) self.pageYpos = float(numPages[0].get('PAGEYPOS')) self.pageXpos = float(numPages[0].get('PAGEXPOS')) self.pageHeight = float(numPages[0].get('PAGEHEIGHT')) self.borderTop = float(numPages[0].get('BORDERTOP')) self.borderBottom = float(numPages[0].get('BORDERBOTTOM')) self.borderLeft = float(numPages[0].get('BORDERLEFT')) self.borderRight = float(numPages[0].get('BORDERRIGHT')) self.pageWidth = float(numPages[0].get('PAGEWIDTH')) realHeightPage = self.pageHeight - self.borderTop - self.borderBottom realWidthPage = self.pageWidth - self.borderLeft - self.borderRight NumMaxRowLabelForPage = int(realHeightPage/sumRows) NumMaxColumnLabelForPage = int(realWidthPage /otherColumn) NumMaxLabelForPageTotal = NumMaxRowLabelForPage*NumMaxColumnLabelForPage NumLabelInDao = len(self.objects) pagesNumber = int((NumLabelInDao/NumMaxLabelForPageTotal)) +1 self.createPageTag(pagesNumber) self.labelObj = self.slaPageObjects() op = True col = True for j in range(1, NumLabelInDao): p=r=c = 1 for pageObject in self.labelObj: ## Creating dictionary attributes pageobject attributes = pageObject.items() dictionary = {} for k in range(0, len(attributes)): dictionary[attributes[k][0]] = attributes[k][1] ## Applying attributes app = pageObject.makeelement('PAGEOBJECT', dictionary) ## Creating dictionary attributes itext of the pageobject itexts = pageObject.findall('ITEXT') for itext in itexts: attributes = itext.items() dictionary = {} for kk in range(0, len(attributes)): dictionary[attributes[kk][0]] = attributes[kk][1] ## Applying attributes ElementTree.SubElement(app, 'ITEXT', dictionary) paras = pageObject.findall('para') for para in paras: attributes = para.items() dictPara = {} for kkk in range(0, len(attributes)): dictPara[attributes[kkk][0]] = attributes[kkk][1] ## Applying attributes ElementTree.SubElement(app, 'para', dictPara) pageItemAttributes = pageObject.findall('pageItemAttributes') ElementTree.SubElement(app, 'pageItemAttributes') ## Number page #inigroup = str(app.get('GROUPS')).strip() x = str(10 +j)+ " " app.set('GROUPS', str(x)) #app.set('OwnPage', str(j)) ## Coordinates ypos = app.get('YPOS') height = app.get('HEIGHT') xpos = app.get('XPOS') if (j/NumMaxLabelForPageTotal) >= 1: page = int(j/NumMaxLabelForPageTotal) else: page = 0 if j < NumMaxRowLabelForPage: app.set('YPOS',str(float(ypos)+ sumRows*j)) elif (j >= NumMaxRowLabelForPage) and (j < NumMaxLabelForPageTotal): app.set('XPOS',str(float(xpos) + float(otherColumn))) app.set('YPOS',str(float(ypos)+(sumRows*(j-NumMaxRowLabelForPage)))) elif page != 0 and j < ((NumMaxLabelForPageTotal * page) + NumMaxRowLabelForPage): app.set('YPOS',str(float(ypos)+\ ((float(self.pageHeight)+float(self.borderTop))*page)+\ sumRows*(j-(NumMaxLabelForPageTotal*page)))) elif page !=0 and j >= (NumMaxLabelForPageTotal * page) +NumMaxRowLabelForPage and j < NumMaxLabelForPageTotal * page +NumMaxLabelForPageTotal: app.set('XPOS',str(float(xpos) + float(otherColumn))) app.set('YPOS',str(float(ypos)+\ ((float(self.pageHeight)+float(self.borderTop))*page)+\ sumRows*(j-(NumMaxLabelForPageTotal*page)-NumMaxRowLabelForPage))) else: print "attenzione oggetto che non ha trovato collocazione" self.slaDocumentTag().append(app) app = {} self.labelSla() self.findTablesProperties()