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 bold(p, text): p.addElement(Span(text=text, stylename='TextBold'))
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 __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 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 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)
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()
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")
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 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