output.automaticstyles.addElement(date_style) time_style = Style(name="time", family="table-column") time_style.addElement(TableColumnProperties(columnwidth="1.5cm")) output.automaticstyles.addElement(time_style) examinee_style = Style(name="examinee", family="table-column") examinee_style.addElement(TableColumnProperties(columnwidth="7cm")) output.automaticstyles.addElement(examinee_style) examiner_style = Style(name="examiner", family="table-column") examiner_style.addElement(TableColumnProperties(columnwidth="4cm")) output.automaticstyles.addElement(examiner_style) table = Table() table.addElement(TableColumn(stylename=date_style)) table.addElement(TableColumn(stylename=time_style)) table.addElement(TableColumn(stylename=examinee_style)) table.addElement(TableColumn(numbercolumnsrepeated=max_examiners, stylename=examiner_style)) def homogenize(examiners): tmp = examiners + [""] * (max_examiners - len(examiners)) if homogenize.previous: for k in range(max_examiners): for j in range(max_examiners): for i in range(max_examiners): if tmp[j] == homogenize.previous[i]: if i != j: tmp[i], tmp[j] = tmp[j], tmp[i] homogenize.previous = tmp return tmp
def colloscope_odf(request, classe): """ Affichage du colloscope d'une classe au format OpenDocument """ response = HttpResponse( content_type='application/vnd.oasis.opendocument.spreadsheet') response[ 'Content-Disposition'] = 'attachment; filename="colloscope_{}.ods"'.format( classe.slug) semaines = classe.semaine_set.order_by('debut') creneaux = classe.creneau_set.order_by('enseignement', 'jour', 'debut') colles = classe.colle_set.filter(semaine__in=semaines, creneau__in=creneaux) # On crée le dictionnaire qui à chaque créneau puis à chaque semaine # associe les groupes de colle colloscope = defaultdict(lambda: defaultdict(list)) for colle in colles: colloscope[colle.creneau][colle.semaine].append(colle) ods = OpenDocumentSpreadsheet() # Styles style_entete = Style(parent=ods.automaticstyles, name='cell_entete', family='table-cell') TextProperties(parent=style_entete, fontweight='bold') style_col_semaine = Style(parent=ods.automaticstyles, name='col_semaine', family='table-column') TableColumnProperties(parent=style_col_semaine, columnwidth='1cm') style_col_matiere = Style(parent=ods.automaticstyles, name='col_matiere', family='table-column') TableColumnProperties(parent=style_col_matiere, columnwidth='5cm') style_col_colleur = Style(parent=ods.automaticstyles, name='col_colleur', family='table-column') TableColumnProperties(parent=style_col_colleur, columnwidth='5cm') style_col_salle = Style(parent=ods.automaticstyles, name='col_salle', family='table-column') TableColumnProperties(parent=style_col_salle, columnwidth='2cm') table = Table(name=str(classe), parent=ods.spreadsheet) # Ajout des colonnes d'en-tête fixes entetes_fixes = ("ID", "Matière", "Colleur", "Jour", "Horaire", "Salle") table.addElement(TableColumn(stylename=style_col_semaine)) # ID table.addElement(TableColumn(stylename=style_col_matiere)) # Matière table.addElement(TableColumn(stylename=style_col_colleur)) # Colleur table.addElement(TableColumn()) # Jour table.addElement(TableColumn()) # Horaire table.addElement(TableColumn(stylename=style_col_salle)) # Salle # Ajout des colonnes d'en-tête des semaines for _ in semaines: table.addElement(TableColumn(stylename=style_col_semaine)) # Container pour les lignes d'en-tête th = TableHeaderRows(parent=table) # Ligne d'en-tête avec les semestres au-dessus des semaines tr = TableRow(parent=th) for entete in entetes_fixes: P(parent=TableCell(parent=tr, valuetype='string', numberrowsspanned=2, numbercolumnsspanned=1, stylename=style_entete), text=entete) # On doit savoir combien de semaines se trouvent sur chaque période # pour afficher les en-têtes sur le bon nombre de colonnes nb_semaines = dict([( periode[0], 0, ) for periode in constantes.PERIODE_CHOICES]) for semaine in semaines: nb_semaines[semaine.periode] += 1 # Insertion des titres des périodes for periode_id, periode_nom in constantes.PERIODE_CHOICES: if nb_semaines[periode_id] > 0: P(parent=TableCell(parent=tr, valuetype='string', numbercolumnsspanned=nb_semaines[periode_id], numberrowsspanned=1, stylename=style_entete), text=periode_nom.capitalize()) CoveredTableCell(parent=tr, numbercolumnsrepeated=nb_semaines[periode_id] - 1) tr = TableRow(parent=th) # Ligne d'en-tête avec seulement les semaines # On doit placer des cellules vides pour les case d'en-tête situées # avant les semaines CoveredTableCell(parent=tr, numbercolumnsrepeated=len(entetes_fixes)) # Puis on ajoute les semaines for semaine in semaines: P(parent=TableCell(parent=tr, valuetype='string', stylename=style_entete), text=semaine.numero) # Colles par créneau for creneau in creneaux: tr = TableRow(parent=table) P(parent=TableCell(parent=tr, valuetype='float', value=creneau.pk), text=creneau.pk) P(parent=TableCell(parent=tr, valuetype='string'), text=creneau.matiere) P(parent=TableCell(parent=tr, valuetype='string'), text=creneau.colleur) P(parent=TableCell(parent=tr, valuetype='string'), text=creneau.get_jour_display()) P(parent=TableCell(parent=tr, valuetype='time', timevalue=creneau.debut.strftime("PT%HH%MM%SS")), text=creneau.debut.strftime("%H:%M")) P(parent=TableCell(parent=tr, valuetype='string'), text=creneau.salle) for semaine in semaines: groupes_texte = ','.join([ str(c.groupe) for c in colloscope[creneau][semaine] if c.groupe ]) cell = TableCell(parent=tr) if groupes_texte: cell.valuetype = "string" P(parent=cell, text=groupes_texte) ods.write(response) return response
textdoc.styles.addElement(tablecontents) # Create automatic styles for the column widths. # We want two different widths, one in inches, the other one in metric. # ODF Standard section 15.9.1 widthshort = Style(name="Wshort", family="table-column") widthshort.addElement(TableColumnProperties(columnwidth="1.7cm")) textdoc.automaticstyles.addElement(widthshort) widthwide = Style(name="Wwide", family="table-column") widthwide.addElement(TableColumnProperties(columnwidth="1.5in")) textdoc.automaticstyles.addElement(widthwide) # Start the table, and describe the columns table = Table(name="Password") table.addElement(TableColumn(numbercolumnsrepeated=4,stylename=widthshort)) table.addElement(TableColumn(numbercolumnsrepeated=3,stylename=widthwide)) f = open('/etc/passwd') for line in f: rec = line.strip().split(":") tr = TableRow() table.addElement(tr) for val in rec: tc = TableCell() tr.addElement(tc) p = P(stylename=tablecontents,text=unicode(val,PWENC)) tc.addElement(p) textdoc.spreadsheet.addElement(table) textdoc.save("passwd.ods")
def classe_resultats_odf(request, resultats): response = HttpResponse( content_type='application/vnd.oasis.opendocument.spreadsheet') response[ 'Content-Disposition'] = 'attachment; filename="resultats_{}.ods"'.format( resultats['classe']) ods = OpenDocumentSpreadsheet() # Style numérique pour les notes style_number_note = NumberStyle(name="Note") ods.styles.addElement(style_number_note) Number(parent=style_number_note, minintegerdigits=1, decimalplaces=2) style_note = Style(datastylename=style_number_note, parent=ods.styles, name="Note", family='table-cell') # Style pour le rang style_number_rang = NumberStyle(name="Rang", parent=ods.styles) Number(parent=style_number_rang, minintegerdigits=1, decimalplaces=0) style_rang = Style(datastylename=style_number_rang, parent=ods.styles, name="Rang", family='table-column') for matiere, etudiants in resultats['matieres'].items(): table = Table(name="{} - {}".format(resultats['classe'], matiere), parent=ods.spreadsheet) # Création des colonnes table.addElement(TableColumn()) # Étudiant table.addElement(TableColumn()) # Moyenne table.addElement(TableColumn(stylename=style_rang)) # Rang for _ in range(len(resultats['semaines'])): table.addElement(TableColumn()) # Ligne d'en-tête th = TableHeaderRows(parent=table) tr = TableRow(parent=th) P(parent=TableCell(parent=tr, valuetype='string'), text="Étudiant") P(parent=TableCell(parent=tr, valuetype='string'), text="Moyenne") P(parent=TableCell(parent=tr, valuetype='string'), text="Rang") for semaine in resultats['semaines']: P(parent=TableCell(parent=tr, valuetype='string'), text=semaine.numero) # Ligne pour chaque étudiant for etudiant, notes in etudiants.items(): tr = TableRow(parent=table) P(parent=TableCell(parent=tr, valuetype='string'), text=str(etudiant)) for note in notes: tc = TableCell(parent=tr) if isinstance(note, list) and len(note) == 1: note = note[0] if isinstance(note, int): tc.setAttribute('valuetype', 'float') tc.setAttribute('value', note) P(text="{}".format(note), parent=tc) elif isinstance(note, Note): if note.est_note(): tc.setAttribute('valuetype', 'float') tc.setAttribute('value', note.value) tc.setAttribute('stylename', style_note) P(text="{:.2f}".format(note), parent=tc) elif isinstance(note, list): P(text=', '.join([ "{:.2f}".format(n) for n in note if isinstance(n, Note) ]), parent=tc) ods.write(response) return response
def save(telephoneDir, subdivision=0, collaborator=None, number=None, telephoneType=None): collaborators = list(sorted(telephoneDir.subdivision)) subdivisions = list(sorted(telephoneDir.subdivision.iterSubdivision())) telephoneTypes = list(sorted(telephoneDir.telephones.telephoneTypes)) s = subdivisions[subdivision] lambdaSubdivision = lambda rec: rec.collaborator in s if not collaborator: lambdaCollaborator = lambda rec: True else: l = len(collaborator) lambdaCollaborator = lambda rec: str(rec.collaborator)[ 0:l] == collaborator if not number: lambdaNumber = lambda rec: True else: l = len(number) lambdaNumber = lambda rec: str(rec.telephone.number)[0:l] == number if not telephoneType: lambdaTelephoneType = lambda rec: True else: t = telephoneTypes[telephoneType] lambdaTelephoneType = lambda rec: rec.telephone.type == t root = Template(file=os.path.join(os.curdir, 'index.tmpl')) telephoneDir = filter(lambda telephone: lambdaSubdivision(telephone) and \ lambdaCollaborator(telephone) and \ lambdaNumber(telephone) and \ lambdaTelephoneType(telephone), sorted(telephoneDir)) textdoc = OpenDocumentText() tablecontents = Style(name="Table Contents", family="paragraph") tablecontents.addElement( ParagraphProperties(numberlines="false", linenumber="0")) textdoc.styles.addElement(tablecontents) textdoc.text.addElement( P(stylename=tablecontents, text=s.name.decode("utf-8"))) style2 = Style(name="style2", family="table-column") style2.addElement(TableColumnProperties(columnwidth="2cm")) textdoc.automaticstyles.addElement(style2) table = Table(name=u"Телефонный справочник") table.addElement(TableColumn(numbercolumnsrepeated=3, stylename=style2)) def row(rec): tr = TableRow() table.addElement(tr) for r in rec: tc = TableCell() tr.addElement(tc) p = P(stylename=tablecontents, text=r) tc.addElement(p) for rec in telephoneDir: row((str(rec.collaborator).decode("utf-8"), rec.telephone.number, rec.telephone.type.name.decode("utf-8"))) textdoc.text.addElement(table) textdoc.save("telephonedir.odt")
def get(self, request, queryset, annee=None): creneaux_ods = OpenDocumentSpreadsheet() # Styles style_entete = Style(parent=creneaux_ods.automaticstyles, name='cell_entete', family='table-cell') TextProperties(parent=style_entete, fontweight='bold') style_col_colleur = Style(parent=creneaux_ods.automaticstyles, name='col_colleur', family='table-column') TableColumnProperties(parent=style_col_colleur, columnwidth='5cm') style_col_matiere = Style(parent=creneaux_ods.automaticstyles, name='col_matiere', family='table-column') TableColumnProperties(parent=style_col_matiere, columnwidth='5cm') style_col_standard = Style(parent=creneaux_ods.automaticstyles, name='col_standard', family='table-column') TableColumnProperties(parent=style_col_standard, columnwidth='2cm') table = Table(name="Créneaux de colles", parent=creneaux_ods.spreadsheet) # Définition des colonnes table.addElement(TableColumn(stylename=style_col_colleur)) # Colleur table.addElement(TableColumn(stylename=style_col_standard)) # Classe table.addElement(TableColumn(stylename=style_col_matiere)) # Matière table.addElement(TableColumn(stylename=style_col_standard)) # Jour table.addElement(TableColumn(stylename=style_col_standard)) # Début table.addElement(TableColumn(stylename=style_col_standard)) # Fin table.addElement(TableColumn(stylename=style_col_standard)) # Salle # En-tête de tableau # Container pour les lignes d'en-tête th = TableHeaderRows(parent=table) # Ligne d'en-tête tr = TableRow(parent=th) P(parent=TableCell(parent=tr, valuetype='string', stylename=style_entete), text="Colleur") P(parent=TableCell(parent=tr, valuetype='string', stylename=style_entete), text="Classe") P(parent=TableCell(parent=tr, valuetype='string', stylename=style_entete), text="Matière") P(parent=TableCell(parent=tr, valuetype='string', stylename=style_entete), text="Jour") P(parent=TableCell(parent=tr, valuetype='string', stylename=style_entete), text="Début") P(parent=TableCell(parent=tr, valuetype='string', stylename=style_entete), text="Fin") P(parent=TableCell(parent=tr, valuetype='string', stylename=style_entete), text="Salle") for creneau in queryset: tr = TableRow(parent=table) P(parent=TableCell(parent=tr, valuetype='string'), text=str(creneau.colleur)) P(parent=TableCell(parent=tr, valuetype='string'), text=str(creneau.classe)) P(parent=TableCell(parent=tr, valuetype='string'), text=str(creneau.matiere)) P(parent=TableCell(parent=tr, valuetype='string'), text=str(creneau.get_jour_display())) P(parent=TableCell(parent=tr, valuetype='string'), text=str(creneau.debut)) P(parent=TableCell(parent=tr, valuetype='string'), text=str(creneau.fin)) P(parent=TableCell(parent=tr, valuetype='string'), text=str(creneau.salle)) return OdfResponse(creneaux_ods, filename="creneaux-{annee}.ods".format(annee=annee))
def save(telephoneDir, subdivision, collaborator, number, telephoneType): textdoc = OpenDocumentSpreadsheet() tablecontents = Style(name="Table Contents", family="paragraph") tablecontents.addElement( ParagraphProperties(numberlines="false", linenumber="0")) textdoc.styles.addElement(tablecontents) style2 = Style(name="style2", family="table-column") style2.addElement(TableColumnProperties(columnwidth="2cm")) textdoc.automaticstyles.addElement(style2) style6 = Style(name="style6", family="table-column") style6.addElement(TableColumnProperties(columnwidth="6cm")) textdoc.automaticstyles.addElement(style6) table = Table(name=u"Подразделения") table.addElement(TableColumn(numbercolumnsrepeated=2, stylename=style6)) def row(rec): tr = TableRow() table.addElement(tr) for r in rec: tc = TableCell() tr.addElement(tc) p = P(stylename=tablecontents, text=r) tc.addElement(p) row((u"подразделение", u"головное подразделение")) row((telephoneDir.subdivision.name.decode("utf-8"), "")) def write(subdivision): for s in subdivision.subdivisions: row((s.name.decode("utf-8"), subdivision.name.decode("utf-8"))) write(s) write(telephoneDir.subdivision) textdoc.spreadsheet.addElement(table) table = Table(name=u"Телефонный справочник") table.addElement(TableColumn(numbercolumnsrepeated=2, stylename=style2)) table.addElement(TableColumn(numbercolumnsrepeated=4, stylename=style6)) row((u"телефон", u"фамилия", u"имя", u"отчество", u"подразделение", u"тип тел.")) def find(c, subdivision): if c in subdivision.collaborators: return subdivision.name.decode("utf-8") else: for s in subdivision.subdivisions: r = find(c, s) if r: return r # for r in telephoneDir: # row((r.telephone.number, r.collaborator.code, r.collaborator.family.decode("utf-8"), r.collaborator.name.decode("utf-8"), r.collaborator.patronym.decode("utf-8"), find(r.collaborator, telephoneDir.subdivision), r.telephone.type.name.decode("utf-8"))) subdivision = int(subdivision) telephoneType = int(telephoneType) collaborator = collaborator.encode('utf-8') number = number.encode('utf-8') if not subdivision: lambdaSubdivision = lambda rec: True else: subdivisions = list(sorted(telephoneDir.subdivision.iterSubdivision())) subdivisions.insert(0, 'все') s = subdivisions[subdivision] lambdaSubdivision = lambda rec: rec.collaborator in s if not collaborator: lambdaCollaborator = lambda rec: True else: lambdaCollaborator = lambda rec: str(rec.collaborator)[0:len( collaborator)] == collaborator if not number: lambdaNumber = lambda rec: True else: lambdaNumber = lambda rec: str(rec.telephone.number)[0:len(number) ] == number if not telephoneType: lambdaTelephoneType = lambda rec: True else: telephoneTypes = list(sorted(telephoneDir.telephones.telephoneTypes)) telephoneTypes.insert(0, 'все') t = telephoneTypes[telephoneType] lambdaTelephoneType = lambda rec: rec.telephone.type == t tmpDir = list(sorted(telephoneDir)) tmpDir = filter(lambda telephone: lambdaSubdivision(telephone) and \ lambdaCollaborator(telephone) and \ lambdaNumber(telephone) and \ lambdaTelephoneType(telephone), tmpDir) print subdivision, telephoneType, collaborator, number for r in tmpDir: row((r.telephone.number, r.collaborator.family.decode("utf-8"), r.collaborator.name.decode("utf-8"), r.collaborator.patronym.decode("utf-8"), find(r.collaborator, telephoneDir.subdivision), r.telephone.type.name.decode("utf-8"))) textdoc.spreadsheet.addElement(table) textdoc.save("telephonedir.ods")
def insert_table_(self, ar, column_names=None, table_width=180): ar.setup_from(self.ar) columns, headers, widths = ar.get_field_info(column_names) widths = map(int, widths) tw = sum(widths) # specifying relative widths doesn't seem to work (and that's # a pity because absolute widths requires us to know the # table_width). use_relative_widths = False if use_relative_widths: width_specs = ["%d*" % (w * 100 / tw) for w in widths] else: width_specs = ["%dmm" % (table_width * w / tw) for w in widths] doc = OpenDocumentText() def add_style(**kw): st = Style(**kw) doc.styles.addElement(st) self.my_styles.append(st) return st table_style_name = str(ar.actor) st = add_style(name=table_style_name, family="table", parentstylename="Default") st.addElement( TableProperties(align="margins", maybreakbetweenrows="0")) # create some *visible* styles st = add_style(name="Table Contents", family="paragraph", parentstylename="Default") st.addElement(ParagraphProperties(numberlines="false", linenumber="0")) st = add_style(name="Number Cell", family="paragraph", parentstylename="Table Contents") st.addElement(ParagraphProperties( numberlines="false", textalign="end", justifysingleword="true", linenumber="0")) dn = "Table Column Header" st = self.stylesManager.styles.getStyle(dn) if st is None: st = add_style(name=dn, family="paragraph", parentstylename="Table Contents") st.addElement( ParagraphProperties(numberlines="false", linenumber="0")) st.addElement(TextProperties(fontweight="bold")) dn = "Bold Text" st = self.stylesManager.styles.getStyle(dn) if st is None: st = add_style(name=dn, family="text", parentstylename="Default") #~ st = add_style(name=dn, family="text") st.addElement(TextProperties(fontweight="bold")) if False: dn = "L1" st = self.stylesManager.styles.getStyle(dn) if st is None: st = ListStyle(name=dn) doc.styles.addElement(st) p = ListLevelProperties( listlevelpositionandspacemode="label-alignment") st.addElement(p) #~ label-followed-by="listtab" text:list-tab-stop-position="1.27cm" fo:text-indent="-0.635cm" fo:margin-left="1.27cm"/> p.addElement(ListLevelLabelAlignment(labelfollowedby="listtab", listtabstopposition="1.27cm", textindent="-0.635cm", marginleft="1.27cm" )) self.my_styles.append(st) #~ list_style = add_style(name=dn, family="list") bullet = text.ListLevelStyleBullet( level=1, stylename="Bullet_20_Symbols", bulletchar=u"•") #~ bullet = text.ListLevelStyleBullet(level=1,stylename="Bullet_20_Symbols",bulletchar=u"*") #~ <text:list-level-style-bullet text:level="1" text:style-name="Bullet_20_Symbols" text:bullet-char="•"> st.addElement(bullet) # create some automatic styles def add_style(**kw): st = Style(**kw) doc.automaticstyles.addElement(st) self.my_automaticstyles.append(st) return st cell_style = add_style(name="Lino Cell Style", family="table-cell") cell_style.addElement(TableCellProperties( paddingleft="1mm", paddingright="1mm", paddingtop="1mm", paddingbottom="0.5mm", border="0.002cm solid #000000")) header_row_style = add_style( name="Lino Header Row", family="table-row", parentstylename=cell_style) header_row_style.addElement( TableRowProperties(backgroundcolor="#eeeeee")) total_row_style = add_style( name="Lino Total Row", family="table-row", parentstylename=cell_style) total_row_style.addElement( TableRowProperties(backgroundcolor="#ffffff")) table = Table(name=table_style_name, stylename=table_style_name) table_columns = TableColumns() table.addElement(table_columns) table_header_rows = TableHeaderRows() table.addElement(table_header_rows) table_rows = TableRows() table.addElement(table_rows) # create table columns and automatic table-column styles for i, fld in enumerate(columns): #~ print 20120415, repr(fld.name) name = str(ar.actor) + "." + fld.name cs = add_style(name=name, family="table-column") if use_relative_widths: cs.addElement( TableColumnProperties(relcolumnwidth=width_specs[i])) else: cs.addElement( TableColumnProperties(columnwidth=width_specs[i])) #~ cs.addElement(TableColumnProperties(useoptimalcolumnwidth='true')) #~ k = cs.getAttribute('name') #~ renderer.stylesManager.styles[k] = toxml(e) #~ doc.automaticstyles.addElement(cs) #~ self.my_automaticstyles.append(cs) table_columns.addElement(TableColumn(stylename=name)) def fldstyle(fld): #~ if isinstance(fld,ext_store.VirtStoreField): #~ fld = fld.delegate if isinstance(fld, NumberFieldElement): return "Number Cell" return "Table Contents" def value2cell(ar, i, fld, val, style_name, tc): txt = fld.value2html(ar, val) p = text.P(stylename=style_name) html2odf(txt, p) try: tc.addElement(p) except Exception as e: logger.warning("20120614 addElement %s %s %r : %s", i, fld, val, e) #~ print 20120614, i, fld, val, e #~ yield P(stylename=tablecontents,text=text) # create header row #~ hr = TableRow(stylename=HEADER_ROW_STYLE_NAME) hr = TableRow(stylename=header_row_style) table_header_rows.addElement(hr) for h in headers: #~ for fld in fields: #~ tc = TableCell(stylename=CELL_STYLE_NAME) tc = TableCell(stylename=cell_style) tc.addElement(text.P( stylename="Table Column Header", #~ text=force_unicode(fld.field.verbose_name or fld.name))) text=force_unicode(h))) hr.addElement(tc) sums = [fld.zero for fld in columns] for row in ar.data_iterator: #~ for grp in ar.group_headers(row): #~ raise NotImplementedError() tr = TableRow() has_numeric_value = False for i, fld in enumerate(columns): #~ tc = TableCell(stylename=CELL_STYLE_NAME) tc = TableCell(stylename=cell_style) #~ if fld.field is not None: v = fld.field._lino_atomizer.full_value_from_object(row, ar) stylename = fldstyle(fld) if v is None: tc.addElement(text.P(stylename=stylename, text='')) else: value2cell(ar, i, fld, v, stylename, tc) nv = fld.value2num(v) if nv != 0: sums[i] += nv has_numeric_value = True #~ sums[i] += fld.value2num(v) tr.addElement(tc) if has_numeric_value or not ar.actor.hide_zero_rows: table_rows.addElement(tr) if not ar.actor.hide_sums: if sums != [fld.zero for fld in columns]: tr = TableRow(stylename=total_row_style) table_rows.addElement(tr) for i, fld in enumerate(columns): tc = TableCell(stylename=cell_style) stylename = fldstyle(fld) p = text.P(stylename=stylename) e = fld.format_sum(ar, sums, i) html2odf(e, p) tc.addElement(p) #~ if len(txt) != 0: #~ msg = "html2odf() returned " #~ logger.warning(msg) #~ txt = tuple(html2odf(fld.format_sum(ar,sums,i),p)) #~ assert len(txt) == 1 #~ tc.addElement(text.P(stylename=stylename,text=txt[0])) tr.addElement(tc) doc.text.addElement(table) return toxml(table)
def doit(args): logfile = args.logger if args.report: logfile.loglevel = args.report try: root = ET.parse(args.input).getroot() except: logfile.log("Error parsing FTML input", "S") if args.font: # font(s) specified on command line fontlist = getfonts(args.font, logfile) else: # get font spec from FTML fontsrc element fontlist = getfonts([root.find("./head/fontsrc").text], logfile, False) #fontlist = getfonts( [fs.text for fs in root.findall("./head/fontsrc")], False ) ### would allow multiple fontsrc elements numfonts = len(fontlist) if numfonts == 0: logfile.log("No font(s) specified", "S") if numfonts > 1: formattedfontnum = ["{0:02d}".format(n) for n in range(numfonts)] else: formattedfontnum = [""] logfile.log("Font(s) specified:", "V") for n, (fontname, bold, italic, embeddedfont) in enumerate(fontlist): logfile.log( " " + formattedfontnum[n] + " " + fontname + BoldItalic(bold, italic) + " " + str(embeddedfont), "V") # get optional fontscale; compute pointsize as int(12*fontscale/100). If result xx is not 12, then add "fo:font-size=xxpt" in Px styles pointsize = 12 fontscaleel = root.find("./head/fontscale") if fontscaleel != None: fontscale = fontscaleel.text try: pointsize = int(int(fontscale) * 12 / 100) except ValueError: # any problem leaves pointsize 12 logfile.log("Problem with fontscale value; defaulting to 12 point", "W") # Get FTML styles and generate LO writer styles # P2 is paragraph style for string element when no features specified # each Px (for P3...) corresponds to an FTML style, which specifies lang or feats or both # if numfonts > 1, two-digit font number is appended to make an LO writer style for each FTML style + font combo # When LO writer style is used with attribute rtl="True", "R" appended to style name LOstyles = {} ftmlstyles = {} Pstylenum = 2 LOstyles["P2"] = ("", None, None) ftmlstyles[0] = "P2" for s in root.findall("./head/styles/style"): Pstylenum += 1 Pnum = "P" + str(Pstylenum) featstring = "" if s.get('feats'): featstring = parsefeats(s.get('feats')) langname = None countryname = None lang = s.get('lang') if lang != None: x = re.match(langcode, lang) langname = x.group('langname') countryname = x.group('countryname') # FTML <test> element @stylename attribute references this <style> element @name attribute ftmlstyles[s.get('name')] = Pnum LOstyles[Pnum] = (featstring, langname, countryname) # create LOwriter file and construct styles for tables, column widths, etc. LOdoc = OpenDocumentText() init(LOdoc, numfonts) # Initialize sequence counters sds = SequenceDecls() sd = sds.addElement( SequenceDecl(displayoutlinelevel='0', name='Illustration')) sd = sds.addElement(SequenceDecl(displayoutlinelevel='0', name='Table')) sd = sds.addElement(SequenceDecl(displayoutlinelevel='0', name='Text')) sd = sds.addElement(SequenceDecl(displayoutlinelevel='0', name='Drawing')) LOdoc.text.addElement(sds) # Create Px style for each (featstring, langname, countryname) tuple in LOstyles # and for each font (if >1 font, append to Px style name a two-digit number corresponding to the font in fontlist) # and (if at least one rtl attribute) suffix of nothing or "R" # At the same time, collect info for creating FontFace elements (and any embedded fonts) suffixlist = ["", "R" ] if root.find(".//test/[@rtl='True']") != None else [""] fontfaces = {} for p in sorted(LOstyles, key=lambda x: int(x[1:]) ): # key = lambda x : int(x[1:]) corrects sort order featstring, langname, countryname = LOstyles[p] for n, (fontname, bold, italic, embeddedfont) in enumerate( fontlist): # embeddedfont = None if no embedding needed fontnum = formattedfontnum[n] # Collect fontface info: need one for each font family + feature combination # Put embedded font in list only under fontname with empty featstring if (fontname, featstring) not in fontfaces: fontfaces[(fontname, featstring)] = [] if embeddedfont: if (fontname, "") not in fontfaces: fontfaces[(fontname, "")] = [] if embeddedfont not in fontfaces[(fontname, "")]: fontfaces[(fontname, "")].append(embeddedfont) # Generate paragraph styles for s in suffixlist: pstyle = Style(name=p + fontnum + s, family="paragraph") if s == "R": pstyle.addElement( ParagraphProperties(textalign="end", justifysingleword="false", writingmode="rl-tb")) pstyledic = {} pstyledic['fontnamecomplex'] = \ pstyledic['fontnameasian'] =\ pstyledic['fontname'] = fontname + featstring pstyledic['fontsizecomplex'] = \ pstyledic['fontsizeasian'] = \ pstyledic['fontsize'] = str(pointsize) + "pt" if bold: pstyledic['fontweightcomplex'] = \ pstyledic['fontweightasian'] = \ pstyledic['fontweight'] = 'bold' if italic: pstyledic['fontstylecomplex'] = \ pstyledic['fontstyleasian'] = \ pstyledic['fontstyle'] = 'italic' if langname != None: pstyledic['languagecomplex'] = \ pstyledic['languageasian'] = \ pstyledic['language'] = langname if countryname != None: pstyledic['countrycomplex'] = \ pstyledic['countryasian'] = \ pstyledic['country'] = countryname pstyle.addElement(TextProperties(attributes=pstyledic)) # LOdoc.styles.addElement(pstyle) ### tried this, but when saving the generated odt, LO changed them to automatic styles LOdoc.automaticstyles.addElement(pstyle) fontstoembed = [] for fontname, featstring in sorted( fontfaces ): ### Or find a way to keep order of <style> elements from original FTML? ff = FontFace(name=fontname + featstring, fontfamily=fontname + featstring, fontpitch="variable") LOdoc.fontfacedecls.addElement(ff) if fontfaces[(fontname, featstring)]: # embedding needed for this combination for fontfile in fontfaces[(fontname, featstring)]: fontstoembed.append(fontfile) # make list for embedding ffsrc = FontFaceSrc() ffuri = FontFaceUri( **{ 'href': "Fonts/" + os.path.basename(fontfile), 'type': "simple" }) ffformat = FontFaceFormat(**{'string': 'truetype'}) ff.addElement(ffsrc) ffsrc.addElement(ffuri) ffuri.addElement(ffformat) basename = "Table1.B" colorcount = 0 colordic = { } # record color #rrggbb as key and "Table1.Bx" as stylename (where x is current color count) tablenum = 0 # get title and comment and use as title and subtitle titleel = root.find("./head/title") if titleel != None: LOdoc.text.addElement( H(outlinelevel=1, stylename="Title", text=titleel.text)) commentel = root.find("./head/comment") if commentel != None: LOdoc.text.addElement(P(stylename="Subtitle", text=commentel.text)) # Each testgroup element begins a new table for tg in root.findall("./testgroup"): # insert label attribute of testgroup element as subtitle tglabel = tg.get('label') if tglabel != None: LOdoc.text.addElement( H(outlinelevel=1, stylename="Subtitle", text=tglabel)) # insert text from comment subelement of testgroup element tgcommentel = tg.find("./comment") if tgcommentel != None: #print("commentel found") LOdoc.text.addElement(P(text=tgcommentel.text)) tgbg = tg.get( 'background') # background attribute of testgroup element tablenum += 1 table = Table(name="Table" + str(tablenum), stylename="Table1") table.addElement(TableColumn(stylename="Table1.A")) for n in range(numfonts): table.addElement(TableColumn(stylename="Table1.B")) table.addElement(TableColumn(stylename="Table1.A")) table.addElement(TableColumn(stylename="Table1.D")) for t in tg.findall("./test"): # Each test element begins a new row # stuff to start the row labeltext = t.get('label') stylename = t.get('stylename') stringel = t.find('./string') commentel = t.find('./comment') rtlsuffix = "R" if t.get('rtl') == 'True' else "" comment = commentel.text if commentel != None else None colBstyle = "Table1.A1" tbg = t.get( 'background' ) # get background attribute of test group (if one exists) if tbg == None: tbg = tgbg if tbg != None: # if background attribute for test element (or background attribute for testgroup element) if tbg not in colordic: # if color not found in color dic, create new style colorcount += 1 newname = basename + str(colorcount) colordic[tbg] = newname tb1style = Style(name=newname, family="table-cell") tb1style.addElement( TableCellProperties( attributes={ 'padding': "0.0382in", 'border': "0.05pt solid #000000", 'backgroundcolor': tbg })) LOdoc.automaticstyles.addElement(tb1style) colBstyle = colordic[tbg] row = TableRow() table.addElement(row) # fill cells # column A (label) cell = TableCell(stylename="Table1.A1", valuetype="string") if labeltext: cell.addElement( P(stylename="Table_20_Contents", text=labeltext)) row.addElement(cell) # column B (string) for n in range(numfonts): Pnum = ftmlstyles[stylename] if stylename != None else "P2" Pnum = Pnum + formattedfontnum[n] + rtlsuffix ### not clear if any of the following can be moved outside loop and reused cell = TableCell(stylename=colBstyle, valuetype="string") par = P(stylename=Pnum) if len(stringel) == 0: # no <em> subelements par.addText(re.sub(backu, hextounichr, stringel.text)) else: # handle <em> subelement(s) if stringel.text != None: par.addElement( Span(stylename="T1", text=re.sub(backu, hextounichr, stringel.text))) for e in stringel.findall("em"): if e.text != None: par.addText(re.sub(backu, hextounichr, e.text)) if e.tail != None: par.addElement( Span(stylename="T1", text=re.sub(backu, hextounichr, e.tail))) cell.addElement(par) row.addElement(cell) # column C (comment) cell = TableCell(stylename="Table1.A1", valuetype="string") if comment: cell.addElement(P(stylename="Table_20_Contents", text=comment)) row.addElement(cell) # column D (stylename) cell = TableCell(stylename="Table1.A1", valuetype="string") if comment: cell.addElement( P(stylename="Table_20_Contents", text=stylename)) row.addElement(cell) LOdoc.text.addElement(table) LOdoc.text.addElement(P(stylename="Subtitle", text="")) # Empty paragraph to end ### necessary? try: if fontstoembed: logfile.log("Embedding fonts in document", "V") for f in fontstoembed: LOdoc._extra.append( OpaqueObject( filename="Fonts/" + os.path.basename(f), mediatype= "application/x-font-ttf", ### should be "application/font-woff" or "/font-woff2" for WOFF fonts, "/font-opentype" for ttf content=io.open(f, "rb").read())) ci = ConfigItem(**{ 'name': 'EmbedFonts', 'type': 'boolean' }) ### (name = 'EmbedFonts', type = 'boolean') ci.addText('true') cis = ConfigItemSet(**{'name': 'ooo:configuration-settings' }) ### (name = 'ooo:configuration-settings') cis.addElement(ci) LOdoc.settings.addElement(cis) except: logfile.log("Error embedding fonts in document", "E") logfile.log("Writing output file: " + args.output, "P") LOdoc.save(args.output) return
def getRsltTable(testType): global ranks, showalllinks, useapps, tagsr, tagsp if testType == "all": aux=targetApps else: aux=[] for t in targetApps: if t.find(testType) >=0: aux.append(t) print aux if useapps is None: targetAppsSel=aux else: targetAppsSel=[] for t in aux: if t.split()[0] in useapps: targetAppsSel.append(t) print targetAppsSel # Start the table, and describe the columns table = Table(name=testType) table.addElement(TableColumn(numbercolumnsrepeated=1,stylename=nameColStyle)) table.addElement(TableColumn(numbercolumnsrepeated=4,stylename=rankColStyle)) for i in targetAppsSel: for i in range(len(testLabels)-1): table.addElement(TableColumn(stylename=valColStyle)) table.addElement(TableColumn(stylename=linkColStyle)) table.addElement(TableColumn(stylename=rankColStyle)) table.addElement(TableColumn(stylename=linkColStyle)) table.addElement(TableColumn(stylename=rankColStyle)) table.addElement(TableColumn(stylename=tagColStyle)) table.addElement(TableColumn(stylename=tagColStyle)) table.addElement(TableColumn(stylename=tagColStyle)) #First row: application names tr = TableRow() table.addElement(tr) tc = TableCell() #empty cell tr.addElement(tc) tc = TableCell() #empty cell tr.addElement(tc) tc = TableCell() #empty cell tr.addElement(tc) tc = TableCell() #empty cell tr.addElement(tc) tc = TableCell() #empty cell tr.addElement(tc) appcolumns=len(testLabels) for a in targetAppsSel: print a tc = TableCell(numbercolumnsspanned=2*(appcolumns-1), stylename="THstyle") tr.addElement(tc) p = P(stylename=tablecontents,text=unicode("Target: %s "%a, PWENC)) tc.addElement(p) for i in range(2*(appcolumns-1)-1): # create empty cells for the merged one tc = TableCell() tr.addElement(tc) tc = TableCell(stylename="Csepstyle") tr.addElement(tc) #Second row: test names tr = TableRow() table.addElement(tr) tc = TableCell(stylename="THstyle") #empty cell tr.addElement(tc) p = P(stylename=tablecontents,text=unicode("Test case",PWENC)) tc.addElement(p) tc = TableCell(stylename="THstyle") #empty cell tr.addElement(tc) p = P(stylename=tablecontents,text=unicode("P/R",PWENC)) tc.addElement(p) tc.addElement(addAnn("Negative: progression, positive: regression, 0: no change")) tc = TableCell(stylename="THstyle") #empty cell tr.addElement(tc) p = P(stylename=tablecontents,text=unicode("Max last",PWENC)) tc.addElement(p) tc.addElement(addAnn("Max grade for the last LO version")) tc = TableCell(stylename="THstyle") #empty cell tr.addElement(tc) p = P(stylename=tablecontents,text=unicode("Sum last",PWENC)) tc.addElement(p) tc.addElement(addAnn("Sum of grades for the last LO version")) tc = TableCell(stylename="THstyle") #empty cell tr.addElement(tc) p = P(stylename=tablecontents,text=unicode("Sum all",PWENC)) tc.addElement(p) tc.addElement(addAnn("Sum of grades for all tested versions")) for a in targetAppsSel: for tl in range(1, len(testLabelsShort)): # we do not show the PPOI value tc = TableCell(numbercolumnsspanned=2,stylename="THstyle") tr.addElement(tc) p = P(stylename=tablecontents,text=unicode(testLabelsShort[-tl],PWENC)) tc.addElement(p) tc.addElement(addAnn(testAnnotation[testLabelsShort[-tl]])) tc = TableCell() #the merged cell tr.addElement(tc) tc = TableCell(stylename="Csepstyle") tr.addElement(tc) tc = TableCell(stylename="THstyle") tr.addElement(tc) #tc = TableCell(stylename="THstyle") #tr.addElement(tc) #p = P(stylename=tablecontents,text=unicode("Views",PWENC)) #tc.addElement(p) #tc.addElement(addAnnL(testViewsExpl)) if ranks: for c in ['rank', 'tag 1', 'tag 2', 'tag 3']: tc = TableCell(stylename="THstyle") tr.addElement(tc) p = P(stylename=tablecontents,text=unicode(c,PWENC)) tc.addElement(p) for testcase in values.keys(): try: agrades = np.array([valToGrade(values[testcase][a][1:]) for a in targetAppsSel]) lastgrade=agrades[-1] maxgrade=agrades.max(axis=0) mingrade=agrades.min(axis=0) except KeyError: # In case a testcase is in the first csv but not in the second one continue #identify regressions and progressions progreg='x' #ipdb.set_trace() if (lastgrade>mingrade).any(): #We have regression progreg=str(sum(lastgrade-mingrade)) else: progreg=str(sum(lastgrade-maxgrade)) if int(progreg) >= 0 and not np.array_equal(agrades[0], [7,7,7,7]) \ and not np.array_equal(agrades[0], [6,6,6,6]): continue #testcase=testcase.split('/')[1] tr = TableRow() table.addElement(tr) tc = TableCell() tr.addElement(tc) #p = P(stylename=tablecontents,text=unicode(testcase,PWENC)) p = P(stylename=tablecontents,text=unicode("",PWENC)) link = A(type="simple",href="%s%s"%(lpath,testcase), text=testcase) p.addElement(link) tc.addElement(p) tc = TableCell(valuetype="float", value=progreg) tr.addElement(tc) #p = P(stylename=tablecontents,text=unicode(progreg,PWENC)) #tc.addElement(p) # max last lastmax = max([valToGrade(values[testcase][a][1:]) for a in targetAppsSel][-1]) tc = TableCell(valuetype="float", value=str(lastmax)) tr.addElement(tc) # sum last lastsum = sum([valToGrade(values[testcase][a][1:]) for a in targetAppsSel][-1]) tc = TableCell(valuetype="float", value=str(lastsum)) tr.addElement(tc) # sum all allsum = sum([sum(valToGrade(values[testcase][a][1:])) for a in targetAppsSel] ) tc = TableCell(valuetype="float", value=str(allsum)) tr.addElement(tc) for a in targetAppsSel: grades = valToGrade(values[testcase][a][1:]) #grades = values[testcase][a][1:] #for val in values[testcase][a][1:]: # we do not show the PPOI value #print grades viewTypes=['s','p','l','z'] app, ttype = a.split() subapp = app.split('-')[0] #create pdf path #ipdb.set_trace() filename=testcase.split("/",1)[-1] # get subdirectories, too if ttype=="roundtrip": pdfpath=app+"/"+filename+"-pair" else: pdfpath=app+"/"+filename+"."+subapp+"-pair" pdfPathInDoc = lpath + pdfpath for (grade, viewType) in zip(reversed(grades), viewTypes): # we do not show the PPOI value if max(grades) > 1: tc = TableCell(valuetype="float", value=str(grade), stylename='C'+str(int(grade))+'style') else: tc = TableCell(valuetype="float", value=str(grade), stylename='CBstyle') tr.addElement(tc) tc = TableCell(stylename="THstyle") tr.addElement(tc) p = P(stylename=tablecontents,text=unicode("",PWENC)) if os.path.exists(pdfpath + '-' + viewType + '.pdf'): link = A(type="simple",href=pdfPathInDoc+"-%s.pdf"%viewType, text=">") if showalllinks or a==targetAppsSel[-1]: p.addElement(link) tc.addElement(p) tc = TableCell(stylename="THstyle") sumall = sum(valToGrade(values[testcase][a][1:])) if grades == [7,7,7,7]: p = P(stylename=tablecontents,text=unicode("timeout",PWENC)) if testType == "roundtrip": gradesPrint = valToGrade(values[testcase][a.replace(testType, 'print')][1:]) if gradesPrint != [7,7,7,7]: p = P(stylename=tablecontents,text=unicode("corrupted",PWENC)) elif grades == [6,6,6,6]: p = P(stylename=tablecontents,text=unicode("empty",PWENC)) elif sumall <= 8: if testType == "print": goodDocuments.append(testcase) p = P(stylename=tablecontents,text=unicode("good import",PWENC)) elif testType == "roundtrip": if testcase in goodDocuments: p = P(stylename=tablecontents,text=unicode("good import, good export",PWENC)) elif testcase in badDocuments: p = P(stylename=tablecontents,text=unicode("bad import, good export",PWENC)) elif sumall <= 20: if testType == "roundtrip": if testcase in goodDocuments: p = P(stylename=tablecontents,text=unicode("good import, bad export",PWENC)) badDocuments.append(testcase) elif testcase in badDocuments: p = P(stylename=tablecontents,text=unicode("bad import, bad export",PWENC)) elif testType == "print": badDocuments.append(testcase) p = P(stylename=tablecontents,text=unicode("bad import",PWENC)) else: p = P(stylename=tablecontents,text=unicode("",PWENC)) tc.addElement(p) tr.addElement(tc) tc = TableCell(stylename="THstyle") tr.addElement(tc) if ranks: rankinfo = ranks[testcase.split('/')[-1]] #tc = TableCell(valuetype="float", value=str("%.3f"%float(rankinfo[0]))) tc = TableCell(valuetype="float", value=str("%.3f"%float(rankinfo[0])), stylename=rankCellStyle) tr.addElement(tc) for c in rankinfo[1:]: if testType == "print": if tagsp: if c in tagsp: tc = TableCell(stylename="C1style") p = P(stylename=C1,text=unicode(c,PWENC)) else: tc = TableCell(stylename="C3style") p = P(stylename=C3,text=unicode(c,PWENC)) else: tc = TableCell(stylename="tagColStyle") p = P(stylename=tagColStyle,text=unicode(c,PWENC)) if testType == "roundtrip": if tagsr: if c in tagsr: tc = TableCell(stylename="C1style") p = P(stylename=C1,text=unicode(c,PWENC)) else: tc = TableCell(stylename="C3style") p = P(stylename=C3,text=unicode(c,PWENC)) else: tc = TableCell(stylename="tagColStyle") p = P(stylename=tagColStyle,text=unicode(c,PWENC)) tr.addElement(tc) tc.addElement(p) return table
ns2.addElement(Number(decimalplaces="2", minintegerdigits="1", grouping="true")) ns2.addElement(Map(condition="value()>=0", applystylename="positive-AUD")) textdoc.styles.addElement(ns2) # Create automatic style for the price cells. moneycontents = Style(name="ce1", family="table-cell", parentstylename=tablecontents, datastylename="main-AUD") textdoc.automaticstyles.addElement(moneycontents) # Start the table, and describe the columns table = Table(name="Currency colours") # Create a column (same as <col> in HTML) Make all cells in column default to currency table.addElement(TableColumn(stylename=widewidth, defaultcellstylename="ce1")) # Create a row (same as <tr> in HTML) tr = TableRow() table.addElement(tr) # Create a cell with a negative value. It should show as red. cell = TableCell(valuetype="currency", currency="AUD", value="-125") cell.addElement(P(text=u"$-125.00")) # The current displayed value tr.addElement(cell) # Create a row (same as <tr> in HTML) tr = TableRow() table.addElement(tr) # Create another cell but with a positive value. It should show in black cell = TableCell(valuetype="currency", currency="AUD", value="123") cell.addElement(P(text=u"$123.00")) # The current displayed value tr.addElement(cell)
def do_args(doc, args): if args is None: return table = Table(name="Table 1") table.addElement( TableColumn(numbercolumnsrepeated='3', stylename='TableAutoWidth')) tr = TableRow(stylename='TableAutoWidth') table.addElement(tr) tc = TableCell(valuetype="string", stylename='Table Heading') tc.addElement(P(text='Name')) tr.addElement(tc) tc = TableCell(valuetype="string", stylename='Table Heading') tc.addElement(P(text='Type')) tr.addElement(tc) tc = TableCell(valuetype="string", stylename='Table Heading') tc.addElement(P(text='Description')) tr.addElement(tc) for t in args.findall('arg'): tr = TableRow(stylename='TableAutoWidth') table.addElement(tr) # Name. tc = TableCell(valuetype="string", stylename='Table Contents') tc.addElement(P(text=t.attrib['name'])) tr.addElement(tc) # Type. tc = TableCell(valuetype="string", stylename='Table Contents') tname = t.attrib['type'].strip() if tname == 'List': refs = [] for subtype in t.findall('types/type'): stname = subtype.attrib['name'] ref = BookmarkRef(referenceformat='text', refname=stname) ref.addText(stname) refs.append(ref) if len(refs) == 1: c = P(text='List of ') c.addElement(refs[0]) tc.addElement(c) else: c = P(text='List of: ') tc.addElement(c) lst = List() for r in refs: item_p = P() item_p.addElement(r) item = ListItem() item.addElement(item_p) lst.addElement(item) tc.addElement(lst) else: ref = BookmarkRef(referenceformat='text', refname=tname) ref.addText(tname) c = P() c.addElement(ref) tc.addElement(c) tr.addElement(tc) # Description. tc = TableCell(valuetype="string", stylename='Table Contents') tr.addElement(tc) desc = t.find('doc').text if 'value' in t.attrib: desc += 'This argument has a fixed value of %s.' % t.attrib['value'] tc.addElement(P(text=desc)) lst = do_values(doc, t.find('values')) if lst is not None: tc.addElement(lst) doc.text.addElement(table)