def text(self, text, stylename=None): """Add text within the current container.""" assert self._containers container = self._containers[-1] if stylename is not None: stylename = self._get_style_name(stylename) container.addElement(Span(stylename=stylename, text=text)) else: container.addElement(Span(text=text))
def setUp(self): d = OpenDocumentText() # Styles h1style = style.Style(name=u"Heading 1", family=u"paragraph") h1style.addElement( style.TextProperties(attributes={ 'fontsize': u"24pt", 'fontweight': u"bold" })) d.styles.addElement(h1style) boldstyle = style.Style(name=u"Bold", family=u"text") boldstyle.addElement( style.TextProperties(attributes={'fontweight': u"bold"})) d.automaticstyles.addElement(boldstyle) # Text h = H(outlinelevel=1, stylename=h1style, text=u"Simple test document") d.text.addElement(h) p = P( text= u"The earth's climate has not changed many times in the course of its long history. " ) d.text.addElement(p) boldpart = Span(stylename=boldstyle, text=u"This part is bold. ") p.addElement(boldpart) p.addText(u"This is after bold.") d.save(u"TEST.odt")
def sample(): textdoc = OpenDocumentText() # Styles s = textdoc.styles h1style = Style(name="Heading 1", family="paragraph") h1style.addElement( TextProperties(attributes={ 'fontsize': "24pt", 'fontweight': "bold" })) s.addElement(h1style) # An automatic style boldstyle = Style(name="Bold", family="text") boldprop = TextProperties(fontweight="bold") boldstyle.addElement(boldprop) textdoc.automaticstyles.addElement(boldstyle) # Text h = H(outlinelevel=1, stylename=h1style, text="My first texta") textdoc.text.addElement(h) p = P(text="Hello world. ") boldpart = Span(stylename=boldstyle, text="This part is bold. ") p.addElement(boldpart) p.addText("This is after bold.") quotStyle = Style(name="Quotations") marginaliaStyle = Style(name="Marginalia") # p2 = P(text="2nd par. ", stylename=textBodyStyle) p3 = P(text="3rd par. ", stylename=quotStyle) textdoc.text.addElement(p) textdoc.text.addElement(p2) textdoc.text.addElement(p3) a = textdoc.save("myfirstdocument.odt")
def fusion_attestation(modele, etudiant, jury): """ Remplace dans un modèle OpenDocument d'attestation de résultats les champs utilisateurs par les données de l'étudiant. Cette fonction renvoie le document OpenDocument modifié. Le modèle est copié, donc n'est pas modifié par l'appel. """ attestation = copy.deepcopy(modele) remplacement = { 'pykol.date_naissance_etudiant': etudiant.birth_date.strftime("%d/%m/%Y"), 'pykol.ine_etudiant': etudiant.ine, 'pykol.nom_formation': nom_formation(jury), 'pykol.domaines_etude': jury.classe.mef.domaines_etude, 'pykol.nom_etudiant': str(etudiant), 'pykol.nom_etudiant_civilite': etudiant.name_civilite(), 'pykol.date_attestation': jury.date.strftime("%d/%m/%Y"), 'pykol.nom_signataire': jury.classe.etablissement.chef_etablissement.name_civilite(), 'pykol.nom_lycee': jury.classe.etablissement.appellation, 'pykol.statut_lycee': jury.classe.etablissement.get_nature_uai_display(), 'pykol.ville_lycee': jury.classe.etablissement.ville, 'pykol.nom_academie': jury.classe.etablissement.academie.nom_complet, 'pykol.annee_academique': "{annee_debut}/{annee_fin}".format( annee_debut=jury.classe.annee.debut.year, annee_fin=jury.classe.annee.fin.year), 'pykol.ne_accord': "né" if etudiant.sexe == etudiant.SEXE_HOMME \ else "née", } mention_globale = jury.mention_set.filter(etudiant=etudiant, globale=True).first() if mention_globale: remplacement[ 'pykol.mention_globale'] = mention_globale.get_mention_display() remplacement['pykol.total_ects'] = mention_globale.credits else: remplacement['pykol.mention_globale'] = "Aucune" remplacement['pykol.total_ects'] = "−" # On parcourt la nouvelle attestation à la recherche des # utilisations des champs utilisations que l'on souhaite # substituer. for field in attestation.getElementsByType(UserFieldGet): try: valeur = remplacement[field.getAttrNS(odf.namespaces.TEXTNS, 'name')] except KeyError: continue field.parentNode.insertBefore(Span(text=valeur), field) field.parentNode.removeChild(field) # Suppression des déclarations des champs utilisateurs de # l'en-tête du document global. for field in attestation.getElementsByType(UserFieldDecl): if field.getAttrNS(odf.namespaces.TEXTNS, 'name') in remplacement: field.parentNode.removeChild(field) return attestation
def WriteMultiline(self, data): lines = data.split('\n') self.currPara.addText(lines[0]) for line in lines[1:]: self.currPara = P(stylename=self.programliststyle) self.textdoc.text.addElement(self.currPara) self.currSpan = Span(stylename=self.strSpanStyle) self.WriteSingleline(self.currSpan, line) self.currPara.addElement(self.currSpan)
def _code_line(self, line): """Add a code line.""" assert self._containers container = self._containers[-1] # Handle extra spaces. text = line while text: if text.startswith(' '): r = re.match(r'(^ +)', text) n = len(r.group(1)) container.addElement(S(c=n)) text = text[n:] elif ' ' in text: assert not text.startswith(' ') i = text.index(' ') container.addElement(Span(text=text[:i])) text = text[i:] else: container.addElement(Span(text=text)) text = ''
def odt_write(object, filename, introduction=None, lmf2odt=lmf_to_odt, items=lambda lexical_entry: lexical_entry.get_lexeme(), sort_order=None, paradigms=False, reverse=False): """! @brief Write a document file. @param object The LMF instance to convert into document output format. @param filename The name of the document file to write with full path, for instance 'user/output.odt'. @param introduction The name of the text file with full path containing the introduction of the document, for instance 'user/config/introduction.txt'. Default value is None. @param lmf2odt A function giving the mapping from LMF representation information that must be written to ODT commands, in a defined order. Default value is 'lmf_to_odt' function defined in 'pylmflib/config/odt.py'. Please refer to it as an example. @param items Lambda function giving the item to sort. Default value is 'lambda lexical_entry: lexical_entry.get_lexeme()', which means that the items to sort are lexemes. @param sort_order Python list. Default value is 'None', which means that the document output is alphabetically ordered. @param paradigms A boolean value to introduce paradigms in document or not. @param reverse A boolean value to set if a reverse dictionary is wanted. """ import string if sort_order is None: # Lowercase and uppercase letters must have the same rank sort_order = dict([(c, ord(c)) for c in string.lowercase]) up = dict([(c, ord(c) + 32) for c in string.uppercase]) sort_order.update(up) sort_order.update({'':0, ' ':0}) textdoc = OpenDocumentText() # Styles s = textdoc.styles h1style = Style(name="Heading 1", family="paragraph") h1style.addElement(TextProperties(attributes={'fontsize':"24pt", 'fontweight':"bold" })) s.addElement(h1style) # An automatic style boldstyle = Style(name="Bold", family="text") boldprop = TextProperties(fontweight="bold", fontname="Arial", fontsize="8pt") boldstyle.addElement(boldprop) textdoc.automaticstyles.addElement(boldstyle) # Parse LMF values if object.__class__.__name__ == "LexicalResource": for lexicon in object.get_lexicons(): # Document title h = H(outlinelevel=1, stylename=h1style, text=lexicon.get_id()) textdoc.text.addElement(h) # Plain paragraph p = P(text=lexicon.get_label()) # Text boldpart = Span(stylename=boldstyle, text="Test. ") p.addElement(boldpart) # Introduction if introduction is not None: p.addText(file_read(introduction)) textdoc.text.addElement(p) # Page break # # Text body lmf2odt(lexicon, textdoc, items, sort_order, paradigms, reverse) else: raise OutputError(object, "Object to write must be a Lexical Resource.") textdoc.save(filename)
def save_test(self): new_partition = OpenDocumentText() T5style = Style(name="T5", family="text") T5style.addElement(TextProperties(fontname="Arial")) new_partition.automaticstyles.addElement(T5style) for i in range(len(self.allText)): old_text = teletype.extractText(self.allText[i]) p = text.P(text="", stylename="T5") for j in range(len(old_text)): if (old_text[j] == " " and i in self.lignes): p.addElement(Span(text=' ', stylename='T5')) else: p.addText(old_text[j]) new_partition.text.addElement(p) new_partition.save("x_test.odt")
def translate_flow_diagram(filename, destination='en'): doc = load(filename) alltext = doc.getElementsByType(Span) # Create translation block translator = Translator() translations = translator.translate( [addSpaces(teletype.extractText(t)) for t in alltext], dest='en', src='cs') # grammar check checkedText = [ language_check.correct( translation._line, language_check.LanguageTool("en-US").check(translation._line)) for translation in translations ] ###### test print translation #print([(translation.text, translation.origin) for translation in translations]) ###### # Replace old text with translation s = len(alltext) styleID = {} for i in range(s): newSpan = Span() old_style = alltext[i].getAttribute("stylename") styleID.setdefault(old_style, i) newSpan.setAttribute("stylename", old_style) newSpan.addText(translations[i]._line) alltext[i].parentNode.insertBefore(newSpan, alltext[i]) alltext[i].parentNode.removeChild(alltext[i]) #print(styleID.keys()) for id in styleID.keys(): if odf_util.shrinkFont(doc, id, by=2) == -1: print("Failed to shrink font: could not find 'text-properties'") doc.save('Tchv10_main_program2.odg')
def ChangeStyle(self, strStyle): """ Generate output to change from existing style to another style only. """ # # Output minimal formatting code: only output anything if the style has # actually changed. # if self.strSpanStyle != strStyle: if strStyle == 'NewPara': self.currPara = P(stylename=self.programliststyle) self.textdoc.text.addElement(self.currPara) self.currSpan = None self.strSpanStyle = None elif strStyle != 'Keep': if strStyle is None: self.currSpan = None else: self.currSpan = Span(stylename=strStyle) self.currPara.addElement(self.currSpan) self.strSpanStyle = strStyle
def imprimir(conexion, obra): textdoc = OpenDocumentText() # Styles s = textdoc.styles h1style = Style(name="Heading 1", family="paragraph") h1style.addElement(TextProperties(attributes={'fontsize':"24pt",'fontweight':"bold" })) s.addElement(h1style) # An automatic style boldstyle = Style(name="Bold", family="text") boldprop = TextProperties(fontweight="bold") boldstyle.addElement(boldprop) textdoc.automaticstyles.addElement(boldstyle) # Text h=H(outlinelevel=1, stylename=h1style, text="My first text") textdoc.text.addElement(h) p = P(text="Hello world. ") boldpart = Span(stylename=boldstyle, text="This part is bold. ") p.addElement(boldpart) p.addText("This is after bold.") textdoc.text.addElement(p) textdoc.save("/home/david/programacion/python/odfpy/myfirstdocument.odt") print ("TodoOK")
def generate_row(datetime, location, extra, acolytes): # Datum und Uhrzeit formatieren date_string = datetime.strftime("%d.%m.%Y") time_string = datetime.strftime("%H:%M") # Neue TableRow erstellen und einfügen row = TableRow() table.addElement(row) # Datum - Zeit Zelle anlegen date_time_cell = TableCell() date_time_cell.addElement(P(stylename=center, text=date_string)) date_time_cell.addElement(P(stylename=center_bold, text=time_string)) # Ort - Information Zelle anlegen location_extra_cell = TableCell() location_extra_cell.addElement(P(stylename=center_bold, text=location)) location_extra_cell.addElement(P(stylename=center, text=extra)) # Messdiener Zelle anlegen acolytes_cell = TableCell() # Messdiener nach Rolle sortiert auflisten for role_name in acolytes: p = P(stylename=left) p.addElement(Span(stylename=bold_style, text=f"{role_name}: ")) p.addText(text=', '.join(acolytes[role_name])) acolytes_cell.addElement(p) # Zellen zur TableRow hinzufügen row.addElement(date_time_cell) row.addElement(location_extra_cell) row.addElement(acolytes_cell) # TableRow zurückgeben return row
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(unicode(args.output)) return
def imprimir(conexion, obra, documento, propiedades=None): consulta = QtSql.QSqlQuery(conexion) Autor = "" Obra = "" Listado = u"RESUMEN DE PRESUPUESTO" Instancia = modulo.Estilo() s = documento.styles d = Instancia.ListaEstilos() for key in d: s.addElement(d[key]) precision = "%.2f" ############### ###Contenido### ############### #Titulo consulta.exec_( "SELECT resumen FROM \"" + obra + "_Conceptos\" AS C, \"" + obra + "_Relacion\" AS R WHERE C.codigo = R.codhijo AND R.codpadre IS NULL") resumen = "" while consulta.next(): resumen = consulta.value(0) linea = Listado parrafo = P(stylename=Instancia.Estilos("Heading 1")) teletype.addTextToElement(parrafo, linea) documento.text.addElement(parrafo) titulo = P(stylename=Instancia.Estilos("Heading 2")) teletype.addTextToElement(titulo, resumen) documento.text.addElement(titulo) #linea horizontal linea = " " lineahorizontal = P(stylename=Instancia.Estilos("Linea horizontal gruesa")) teletype.addTextToElement(lineahorizontal, linea) documento.text.addElement(lineahorizontal) #consulta consulta.exec_("SELECT * FROM ver_resumen_capitulos('" + obra + "')") #datos de la consulta rec = consulta.record() codigo = rec.indexOf("codigo") resumen = rec.indexOf("resumen") cantidad = rec.indexOf("cantidad") euros = rec.indexOf("total") porcentaje = rec.indexOf("porcentaje") EM = 0.0 while consulta.next(): linea = consulta.value( codigo) + "\t" + consulta.value(resumen) + "\t" + formatear( consulta.value(euros)) + "\t" + formatear( consulta.value(porcentaje)) + " %" print(linea) tabp = P( stylename=Instancia.Estilos("Normal con tabuladores capitulos")) teletype.addTextToElement(tabp, linea) documento.text.addElement(tabp) EM = EM + consulta.value(euros) #EM salto = P() lb = LineBreak() salto.addElement(lb) documento.text.addElement(salto) lineaEM = "\tTotal Ejecución Material:\t" + formatear(EM) parrafo = P( stylename=Instancia.Estilos("Normal con tabuladores resumen negritas")) teletype.addTextToElement(parrafo, lineaEM) documento.text.addElement(parrafo) #GG GG = 0.0 consulta.exec_( "SELECT datos->>'Valor' FROM (SELECT jsonb_array_elements(propiedades->'Valor') AS datos \ FROM \"" + obra + "_Propiedades\" \ WHERE propiedades->>'Propiedad' = 'Porcentajes') AS subdatos WHERE datos->>'Variable' = 'zPorGastosGenerales'" ) while consulta.next(): GG = float(consulta.value(0)) print("Gastos generales " + str(GG) + "\t") GastosGenerales = EM * GG / 100 lineaGG = "\t\t" + str(GG) + "% Gastos generales\t" + formatear( GastosGenerales) parrafo = P(stylename=Instancia.Estilos("Normal con tabuladores resumen")) teletype.addTextToElement(parrafo, lineaGG) documento.text.addElement(parrafo) #BI BI = 0.0 consulta.exec_( "SELECT datos->>'Valor' FROM (SELECT jsonb_array_elements(propiedades->'Valor') AS datos \ FROM \"" + obra + "_Propiedades\" \ WHERE propiedades->>'Propiedad' = 'Porcentajes') AS subdatos WHERE datos->>'Variable' = 'zPorBenIndustrial'" ) while consulta.next(): BI = float(consulta.value(0)) print("Gastos generales " + str(BI) + "\t") BeneficioIndustrial = EM * BI / 100 lineaBI = "\t\t" + str(BI) + "%Beneficio Industrial\t" + formatear( BeneficioIndustrial) parrafo = P(stylename=Instancia.Estilos("Normal con tabuladores resumen")) teletype.addTextToElement(parrafo, lineaBI) documento.text.addElement(parrafo) #suma de GG+BI lineaGGBI = "\t\tSuma de G.G. + B.I.: \t" + formatear(GastosGenerales + BeneficioIndustrial) parrafo = P(stylename=Instancia.Estilos("Normal con tabuladores resumen")) teletype.addTextToElement(parrafo, lineaGGBI) documento.text.addElement(parrafo) #PContrata importeTPC = EM + GastosGenerales + BeneficioIndustrial lineaTPC = "\tTOTAL PRESUPUESTO DE CONTRATA: \t" + formatear(importeTPC) parrafo = P( stylename=Instancia.Estilos("Normal con tabuladores resumen negritas")) teletype.addTextToElement(parrafo, lineaTPC) documento.text.addElement(parrafo) #IVA IVA = 0 consulta.exec_( "SELECT datos->>'Valor' FROM (SELECT jsonb_array_elements(propiedades->'Valor') AS datos \ FROM \"" + obra + "_Propiedades\" \ WHERE propiedades->>'Propiedad' = 'Porcentajes') AS subdatos WHERE datos->>'Variable' = 'zPorIVAEjecucion'" ) while consulta.next(): IVA = float(consulta.value(0)) importeIVA = importeTPC * IVA / 100 lineaIVA = "\t\t" + str(IVA) + "% IVA\t" + formatear(importeIVA) parrafo = P(stylename=Instancia.Estilos("Normal con tabuladores resumen")) teletype.addTextToElement(parrafo, lineaIVA) documento.text.addElement(parrafo) #PGeneral importeTPG = importeTPC + (importeTPC * IVA / 100) lineaTPC = "\tTOTAL PRESUPUESTO GENERAL: \t" + formatear(importeTPG) parrafo = P( stylename=Instancia.Estilos("Normal con tabuladores resumen negritas")) teletype.addTextToElement(parrafo, lineaTPC) documento.text.addElement(parrafo) #salto salto = P() lb = LineBreak() salto.addElement(lb) documento.text.addElement(salto) #cantidad en letra consulta.exec_("SELECT numero_en_euro(" + str(importeTPG) + ")") print(consulta.lastError().text()) cantidadenletra = "" while consulta.next(): cantidadenletra = consulta.value(0) print("cantidad en letras " + cantidadenletra) resumen = P() texto_resumen = Span( stylename=Instancia.Estilos("Normal"), text="Asciende el presupuesto general a la expresada cantidad de ") resumen.addElement(texto_resumen) texto_cantidad_letra = Span(stylename=Instancia.Estilos("Negritas"), text=cantidadenletra) resumen.addElement(texto_cantidad_letra) documento.text.addElement(resumen) #firmas-datos encabezado_firma_proyectista = "" nombre_proyectista1 = "" nombre_proyectista2 = "" encabezado_firma_promotor = "" nombre_promotor1 = "" nombre_promotor2 = "" ciudad = "" consulta.exec_( "SELECT datos->>'Valor' FROM (SELECT jsonb_array_elements(propiedades->'Valor') AS datos \ FROM \"" + obra + "_Propiedades\" \ WHERE propiedades->>'Propiedad' = 'Proyectista') AS subdatos WHERE datos->>'Variable' = 'zPryEncabezamiento'" ) while consulta.next(): encabezado_firma_proyectista = consulta.value(0) consulta.exec_( "SELECT datos->>'Valor' FROM (SELECT jsonb_array_elements(propiedades->'Valor') AS datos \ FROM \"" + obra + "_Propiedades\" \ WHERE propiedades->>'Propiedad' = 'Proyectista') AS subdatos WHERE datos->>'Variable' = 'zPryNombre1'" ) while consulta.next(): nombre_proyectista1 = consulta.value(0) consulta.exec_( "SELECT datos->>'Valor' FROM (SELECT jsonb_array_elements(propiedades->'Valor') AS datos \ FROM \"" + obra + "_Propiedades\" \ WHERE propiedades->>'Propiedad' = 'Proyectista') AS subdatos WHERE datos->>'Variable' = 'zPryNombre2'" ) while consulta.next(): nombre_proyectista2 = consulta.value(0) consulta.exec_( "SELECT datos->>'Valor' FROM (SELECT jsonb_array_elements(propiedades->'Valor') AS datos \ FROM \"" + obra + "_Propiedades\" \ WHERE propiedades->>'Propiedad' = 'El promotor') AS subdatos WHERE datos->>'Variable' = 'zProEncabezamiento'" ) while consulta.next(): encabezado_firma_promotor = consulta.value(0) consulta.exec_( "SELECT datos->>'Valor' FROM (SELECT jsonb_array_elements(propiedades->'Valor') AS datos \ FROM \"" + obra + "_Propiedades\" \ WHERE propiedades->>'Propiedad' = 'El promotor') AS subdatos WHERE datos->>'Variable' = 'zProNombre1'" ) while consulta.next(): nombre_promotor1 = consulta.value(0) consulta.exec_( "SELECT datos->>'Valor' FROM (SELECT jsonb_array_elements(propiedades->'Valor') AS datos \ FROM \"" + obra + "_Propiedades\" \ WHERE propiedades->>'Propiedad' = 'El promotor') AS subdatos WHERE datos->>'Variable' = 'zProNombre2'" ) while consulta.next(): nombre_promotor2 = consulta.value(0) consulta.exec_( "SELECT datos->>'Valor' FROM (SELECT jsonb_array_elements(propiedades->'Valor') AS datos \ FROM \"" + obra + "_Propiedades\" \ WHERE propiedades->>'Propiedad' = 'Datos generales') AS subdatos WHERE datos->>'Variable' = 'zCiudad'" ) while consulta.next(): ciudad = consulta.value(0) #Linea ciudad y fecha #salto salto = P() lb = LineBreak() salto.addElement(lb) documento.text.addElement(salto) fecha = datetime.now() dia = fecha.strftime("%d") mes = fecha.strftime("%B") anno = fecha.strftime("%Y") lineaciudadfecha = "En " + ciudad + ", a " + dia + " de " + mes + " de " + anno parrafo = P(stylename=Instancia.Estilos("NormalP")) teletype.addTextToElement(parrafo, lineaciudadfecha) documento.text.addElement(parrafo) #salto salto = P() lb = LineBreak() salto.addElement(lb) documento.text.addElement(salto) #linea 1 firmas linea1 = encabezado_firma_proyectista + "\t\t\t" + encabezado_firma_promotor parrafo = P(stylename=Instancia.Estilos("NegritasP")) teletype.addTextToElement(parrafo, linea1) documento.text.addElement(parrafo) #saltos de linea for n in range(0, 2): salto = P() lb = LineBreak() salto.addElement(lb) documento.text.addElement(salto) #linea 2 firmas linea2 = nombre_proyectista1 + "\t\t\t" + nombre_promotor1 parrafo = P(stylename=Instancia.Estilos("NormalP")) teletype.addTextToElement(parrafo, linea2) documento.text.addElement(parrafo) #linea 2 firmas linea3 = nombre_proyectista2 + "\t\t\t" + nombre_promotor2 parrafo = P(stylename=Instancia.Estilos("NormalP")) teletype.addTextToElement(parrafo, linea3) documento.text.addElement(parrafo) return documento
def bold(p, text): p.addElement(Span(text=text, stylename='TextBold'))
s.addElement(tabstyle) # Styles s = textdoc.styles h1style = Style(name="Heading 1", family="paragraph") h1style.addElement(TextProperties(attributes={'fontsize':"24pt",'fontweight':"bold" })) s.addElement(h1style) # An automatic style boldstyle = Style(name="Bold", family="text") boldprop = TextProperties(fontweight="bold") boldstyle.addElement(boldprop) textdoc.automaticstyles.addElement(boldstyle) # Text h=H(outlinelevel=1, stylename=h1style, text="My first text") textdoc.text.addElement(h) p = P(text="Hello world. ") boldpart = Span(stylename=boldstyle, text="Ich möchte auch Ümläute schräben können") p.addElement(boldpart) p.addText("This is after bold.") textdoc.text.addElement(p) textdoc.save("myfirstdocument.odt")
def opIn(self, opt: Union[float, str, "odf.element.Element", List, "AQOdsImage"]): """ Add options to the line. @param opt. Line options, each cell ends with the value assignment """ from odf.text import P, Span # type: ignore from odf.draw import Frame, Image # type: ignore if isinstance(opt, float): if self.fix_precision_ is not None: opt = "%s" % round(opt, self.fix_precision_) else: opt = "%s" % opt if isinstance(opt, str): # Último paso cell, style = self.__newCell__() if self.style_cell_text_: text_elem = P(text="") txt_ = Span(stylename=self.style_cell_text_, text=opt) text_elem.addElement(txt_) else: text_elem = P(text=opt) self.sheet_.spread_sheet_parent_.automaticstyles.addElement(style) cell.addElement(text_elem) self.cells_list_.append(cell) self.fix_precision_ = None self.style_cell_text_ = None else: if isinstance(opt, list): # Si es lista , Insertamos todos los parámetros uno a uno for l in opt: self.opIn(l) elif isinstance(opt, AQOdsImage): href = self.sheet_.spread_sheet_parent_.addPictureFromFile(opt.link_) cell, style = self.__newCell__() # p = P() frame = Frame( width="%spt" % opt.width_, height="%spt" % opt.height_, x="%spt" % opt.x_, y="%spt" % opt.y_, ) frame.addElement(Image(href=href)) # p.addElement(frame) cell.addElement(frame) self.cells_list_.append(cell) # self.coveredCell() # self.opIn(href) # print("FIXME:: Vacio", href) elif isinstance(opt, odf.element.Element): if opt.tagName in ("style:paragraph-properties", "style:table-cell-properties"): import copy prop = copy.copy(opt) self.property_cell_.append(prop) elif opt.tagName == "style:style": self.sheet_.spread_sheet_parent_.automaticstyles.addElement(opt) self.style_cell_text_ = opt else: logger.warning("%s:Parámetro desconocido %s", __name__, opt.tagName)
def __init__(self, *datos): self.textDoc = OpenDocumentText() self.h = Header() self.f = Footer() self.s = self.textDoc.styles self.pl = PageLayout(name="pagelayout") #datos para la cabecera Autor = datos[0] Obra = datos[1] #margenes para la pagina (PageLayout) layoutPagina = datos[2] print("layoutPagina") print(layoutPagina) MRight = str(layoutPagina[0]) + "cm" print("MRight " + MRight) MLeft = str(layoutPagina[1]) + "cm" MTop = str(layoutPagina[2]) + "cm" MBottom = str(layoutPagina[3]) + "cm" PaginaInicial = layoutPagina[4] #anadimos los datos a la pagina self.pl.addElement( PageLayoutProperties(margintop=MTop, marginbottom=MBottom, marginleft=MRight, marginright=MLeft)) self.textDoc.automaticstyles.addElement(self.pl) self.mp = MasterPage(name="Standard", pagelayoutname=self.pl) self.textDoc.masterstyles.addElement(self.mp) #Cabecera estilos #Normal EstiloCabeceraNormal = "CabeceraNormal" estilo = Style(name=EstiloCabeceraNormal, family="text", parentstylename="Standard") estilo.addElement( TextProperties(fontweight="light", fontfamily="helvetica", fontsize="9pt")) self.s.addElement(estilo) #Negritas EstiloCabeceraNegritas = "CabeceraNegritas" estilo = Style(name=EstiloCabeceraNegritas, family="text", parentstylename=EstiloCabeceraNormal) estilo.addElement(TextProperties(fontweight="bold")) self.s.addElement(estilo) #Normal centrado EstiloCabeceraNormalCentrado = "CabeceraNormalCentrado" estilo = Style(name=EstiloCabeceraNormalCentrado, family="paragraph", parentstylename=EstiloCabeceraNormal) estilo.addElement( ParagraphProperties(textalign="center", numberlines="true", linenumber="0")) self.s.addElement(estilo) #linea horizontal fina linea_horizontal_fina = Style(name="Lineahorizontalfina", displayname="Horizontal Line Thin", family="paragraph") linea_horizontal_fina.addElement(ParagraphProperties(margintop="0cm", marginbottom="0cm", marginright="0cm", marginleft="0cm", \ contextualspacing="false", borderlinewidthbottom="0cm 0.030cm 0.02cm", padding="0cm", borderleft="none", borderright="none", \ bordertop="none", borderbottom="0.06pt double #3a3b3d", numberlines="false", linenumber="0", joinborder="false")) self.s.addElement(linea_horizontal_fina) #numeracion numeracion = "Numeracion" estilo = Style(name=numeracion, family="paragraph") #estilo.addElement(PageNumber(selectpage="current")) #Cabecera contenidos hp = P() texto_cabecera = Span(stylename=EstiloCabeceraNegritas, text="Proyecto:\t") hp.addElement(texto_cabecera) texto_cabecera = Span(stylename=EstiloCabeceraNormal, text=Obra) hp.addElement(texto_cabecera) self.h.addElement(hp) hp = P() texto_cabecera = Span(stylename=EstiloCabeceraNegritas, text="Autor:\t") hp.addElement(texto_cabecera) texto_cabecera = Span(stylename=EstiloCabeceraNormal, text=Autor) hp.addElement(texto_cabecera) self.h.addElement(hp) hp = P(stylename=linea_horizontal_fina) self.h.addElement(hp) self.mp.addElement(self.h) #Pie de pagina fp = P(stylename=EstiloCabeceraNormalCentrado) pagina = Span(stylename=EstiloCabeceraNormal, text="Página: ") fp.addElement(pagina) numero = PageNumber(selectpage="auto", text=4) fp.addElement(numero) self.f.addElement(fp) self.mp.addElement(self.f)
def sols2odt(variables, file_name, user_input): ''' Soluciones a documento Open Document Text ''' from odf.opendocument import OpenDocumentText from odf.style import Style, TextProperties from odf.text import H, P, Span # Comienza la salida: textdoc = OpenDocumentText() # Styles s = textdoc.styles h1style = Style(name="Heading 1", family="paragraph") h1style.addElement(TextProperties(attributes={'fontsize': "24pt", 'fontweight': "bold"})) s.addElement(h1style) h2style = Style(name="Heading 2", family="paragraph") h2style.addElement(TextProperties(attributes={'fontsize': "18pt", 'fontweight': "bold"})) s.addElement(h2style) # An automatic style Bold boldstyle = Style(name="Bold", family="text") boldprop = TextProperties(fontweight="bold") boldstyle.addElement(boldprop) textdoc.automaticstyles.addElement(boldstyle) # Italic italicstyle = Style(name="Italic", family="text") italicprop = TextProperties(fontstyle="italic") italicstyle.addElement(italicprop) textdoc.automaticstyles.addElement(italicstyle) # Text h = H(outlinelevel=1, stylename=h1style, text="Reporte pyENL") textdoc.text.addElement(h) p = P(text='') textdoc.text.addElement(p) h = H(outlinelevel=1, stylename=h2style, text="Ecuaciones") textdoc.text.addElement(h) p = P(text='') textdoc.text.addElement(p) # Añadimos las ecuaciones: for eqn in user_input: p = P(text='') if '<<' in eqn: comentario = eqn comentario = comentario.replace('<<', '') comentario = comentario.replace('>>', '') boldpart = Span(stylename=boldstyle, text=comentario) p.addElement(boldpart) else: italicpart = Span(stylename=italicstyle, text=eqn) p.addElement(italicpart) textdoc.text.addElement(p) # Ahora añadir las soluciones: p = P(text='') textdoc.text.addElement(p) h = H(outlinelevel=1, stylename=h2style, text="Soluciones") textdoc.text.addElement(h) p = P(text='') textdoc.text.addElement(p) for variable in variables: # Primero insertar el nombre de la variable con su valor y finalmente # El comentario de la misma: p = P(text=variable.name + ' = ' + str(variable.guess) + ' ' + str(variable.units)) textdoc.text.addElement(p) p = P(text=variable.comment) textdoc.text.addElement(p) p = P(text='') textdoc.text.addElement(p) # Guardar... textdoc.save(file_name)
h1style = Style(name="Heading 1", family="paragraph") h1style.addElement(TextProperties(attributes={'fontsize':"24pt",'fontweight':"bold" })) s.addElement(h1style) # An automatic style boldstyle = Style(name="Bold", family="text") boldprop = TextProperties(fontweight="bold") boldstyle.addElement(boldprop) textdoc.automaticstyles.addElement(boldstyle) algo = Style(name = "kk") numeracion = ParagraphProperties(pagenumber = "2") algo.addElement(numeracion) textdoc.automaticstyles.addElement(algo) # Text h=H(outlinelevel=1, stylename=h1style, text="My first text") textdoc.text.addElement(h) p = P(text="Hello world. ") boldpart = Span(stylename=boldstyle, text="This part is bold. ") p.addElement(boldpart) p.addText("This is after bold.") textdoc.text.addElement(p) fp = P(stylename=" foot") pagina = Span(stylename="foot2", text="Página: ") fp.addElement(pagina) numero = PageNumber(selectpage="auto") fp.addElement(numero) f.addElement(fp) mp.addElement(f) textdoc.save("myfirstdocument.odt")
def write(self, model): self.doc.text.addElement(P(text=model.name, stylename="ResumeH1")) self.doc.text.addElement(P(text=model.address, stylename="ResumeH1")) self.doc.text.addElement(P(text=", ".join([model.phone, model.email]), stylename="ResumeH1")) for contact in model.contacts: self.doc.text.addElement(P(text=contact, stylename="ResumeH1")) self.nl() self.doc.text.addElement(P(text=model.objective_title, stylename="ResumeH1")) self.nl() for objective in model.objectives: self.doc.text.addElement(P(text=objective, stylename="ResumeText")) self.nl() self.doc.text.addElement(P(text=model.skillarea_title, stylename="ResumeH1")) self.nl() for i in range(0, len(model.skillset_titles)): skillset_line = P(text="") skillset_line.addElement(Span(text=model.skillset_titles[i], stylename="ResumeBoldText")) skillset_line.addElement(Span( text=": ", stylename="ResumeBoldText")) skillset_line.addText(", ".join(model.skillsets[i])) self.doc.text.addElement(skillset_line) self.nl() self.doc.text.addElement(P( text=model.jobs_title, stylename="ResumeH1")) for i in range(0, len(model.job_titles)): self.nl() self.doc.text.addElement(P(text=model.job_titles[i], stylename="ResumeH2")) self.doc.text.addElement(P(text=model.job_employers[i], stylename="ResumeH2")) self.doc.text.addElement(P(text=model.job_descriptions[i], stylename="ResumeText")) achievements_list = List(stylename="ResumeTextList") for achievement in model.job_achievements[i]: achievements_listitem = ListItem() achievements_listitem.addElement(P(text=achievement, stylename="ResumeText")) achievements_list.addElement(achievements_listitem) self.doc.text.addElement(achievements_list) self.nl() self.doc.text.addElement(P(text=model.academics_title, stylename="ResumeH1")) academics_list = List(stylename="ResumeTextList") for academic in model.academics: academics_listitem = ListItem() academics_listitem.addElement(P( text=academic, stylename="ResumeText")) academics_list.addElement(academics_listitem) self.doc.text.addElement(academics_list) self.nl() self.doc.text.addElement(P( text=model.awards_title, stylename="ResumeH1")) awards_list = List(stylename="ResumeTextList") for award in model.awards: awards_listitem = ListItem() awards_listitem.addElement(P(text=award, stylename="ResumeText")) awards_list.addElement(awards_listitem) self.doc.text.addElement(awards_list) self.nl()
textdoc.text.addElement(textList) # A paragraph with bold, italics, font change, and hyperlinks """ <text:p>The <text:span text:style-name="T1">URL</text:span> for <text:span text:style-name="T5">Flickr</text:span> is <text:a xlink:type="simple" xlink:href="http://www.flickr.com/" >http://www.flickr.com</text:a>. <text:s/>The <text:span text:style-name="T2" >API page</text:span> is <text:a xlink:type="simple" xlink:href="http://www.flickr.com/services/api/" >http://www.flickr.com/services/api/</text:a></text:p> """ p = P(text='The ') # italicized URL s = Span(text='URL', stylename='T1') p.addElement(s) p.addText(' for ') # Flickr in red and Arial font p.addElement(Span(text='Flickr',stylename='T5')) p.addText(' is ') # link link = A(type="simple",href="http://www.flickr.com", text="http://www.flickr.com") p.addElement(link) p.addText('. The ') # API page in bold s = Span(text='API page', stylename='T2') p.addElement(s) p.addText(' is ') link = A(type="simple",href="http://www.flickr.com/services/api", text="http://www.flickr.com/services/api")
def createodt(file, data, feuille, dirpath): textdoc = OpenDocumentText() textdoc.fontfacedecls.addElement( FontFace(name="Arial", fontfamily="Arial", fontfamilygeneric="swiss", fontpitch="variable")) # Styles s = textdoc.styles #style normal ---> faire plutôt un style par défaut en justilié taille 16... StandardStyle = Style(name="Standard", family="paragraph") StandardStyle.addElement(TextProperties(fontsize="16")) s.addElement(StandardStyle) # bold style b = Style(name="b", family="text", parentstylename='Standard') boldprop = TextProperties(fontweight="bold") b.addElement(boldprop) textdoc.automaticstyles.addElement(b) # red style r = Style(name="r", family="text", parentstylename='Standard') redprop = TextProperties(fontweight="bold", color="#FF0000") r.addElement(redprop) textdoc.automaticstyles.addElement(r) # green style g = Style(name="g", family="text", parentstylename='Standard') greenprop = TextProperties(color="#008000") g.addElement(greenprop) textdoc.automaticstyles.addElement(g) # Create a style for the paragraph with page-break pb = Style(name="pb", parentstylename="Standard", family="paragraph") pb.addElement(ParagraphProperties(breakafter="page")) #mettre breakafter ? textdoc.automaticstyles.addElement(pb) # Text p = P() part = Span(stylename=b, text="Mode d'emploi pour le prof : ") p.addElement(part) textdoc.text.addElement(p) p = P() part = Span(text="Il y a une page par élève.") p.addElement(part) textdoc.text.addElement(p) p = P() part = Span( text= "Compléter le bas de chaque page par un commentaire, par exemple sur l'efficacité des méthodes de travail de l'élève." ) p.addElement(part) textdoc.text.addElement(p) p = P() part = Span( text= "Imprimer en deux pages par feuilles et faire un rendu à la classe.") p.addElement(part) textdoc.text.addElement(p) p = P() textdoc.text.addElement(p) p = P(stylename=pb) textdoc.text.addElement(p) for user in data: p = P() part = Span(stylename=b, text="Bilan du travail sur Wims : ") p.addElement(part) part = Span(text="feuille n°" + str(feuille) + " (" + fsheets(file)[feuille] + ")") p.addElement(part) textdoc.text.addElement(p) p = P() textdoc.text.addElement(p) p = P() part = Span(stylename=b, text="Élève : ") p.addElement(part) part = Span(text=user.firstname + " " + user.lastname) p.addElement(part) textdoc.text.addElement(p) p = P() textdoc.text.addElement(p) p = P() part = Span(stylename=b, text="Note : ") p.addElement(part) part = Span(text=str(user.note)) p.addElement(part) textdoc.text.addElement(p) p = P() textdoc.text.addElement(p) p = P() part = Span(stylename=b, text="Durée approximative de travail : ") p.addElement(part) part = Span(text=str(user.h) + " h " + str(user.min) + " min (sans doute plus que " + str(user.sh) + " h " + str(user.smin) + " min)") p.addElement(part) textdoc.text.addElement(p) p = P() textdoc.text.addElement(p) p = P() part = Span(stylename=b, text="Légende : ") p.addElement(part) p = P( text= "Chaque tiret indique la visualisation d'un nouvel énoncé (un tiret long indique une recherche de plus de 5 minutes et un point une recherche de moins d'une minute)." ) textdoc.text.addElement(p) p = P(text="Chaque nombre indique un score obtenu.") textdoc.text.addElement(p) p = P(text="Une lettre 'a' indique la consultation d'un indication.") textdoc.text.addElement(p) p = P(text="La ") part = Span(stylename=g, text="couleur verte ") p.addElement(part) part = Span( text="indique que l'enregistrement des notes est désactivé.") p.addElement(part) textdoc.text.addElement(p) p = P(text="La ") part = Span(stylename=r, text="couleur rouge ") p.addElement(part) part = Span(text="indique que l'enregistrement des notes est activé.") p.addElement(part) textdoc.text.addElement(p) p = P() textdoc.text.addElement(p) for i in range(len(user.listdata)): if len(user.listdata[i]) > 0: p = P() part = Span(stylename=b, text="Exercice n° : " + str(i + 1)) p.addElement(part) textdoc.text.addElement(p) for dict in user.listdata[i]: p = P() part = Span(text="le " + dict['date'] + " à partir de " + dict['heure'] + " : ") p.addElement(part) for data in dict['data']: part = Span(stylename=data[0][0], text=data[1]) p.addElement(part) textdoc.text.addElement(p) p = P() textdoc.text.addElement(p) p = P() part = Span(stylename=b, text="Commentaires : ") p.addElement(part) textdoc.text.addElement(p) p = P() textdoc.text.addElement(p) p = P(stylename=pb) textdoc.text.addElement(p) titre = 'WimsActivityViewer_feuille_' + str(feuille) + '.odt' titre = os.path.join(dirpath, titre) textdoc.save(titre) return titre