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 do_job(job): """Do something""" warnings = get_warnings(job['sts'], job['ets'], job['wfo'], job['wtype']) mydir = "/tmp/%s" % (job['jobid'], ) if not os.path.isdir(mydir): os.makedirs(mydir) os.chdir(mydir) basefn = "%s-%s-%s-%s-%s" % (job['wfo'], job['wtype'].replace( ",", "_"), job['radar'], job['sts'].strftime("%Y%m%d%H"), job['ets'].strftime("%Y%m%d%H")) outputfile = "%s.odp" % (basefn, ) doc = OpenDocumentPresentation() # We must describe the dimensions of the page pagelayout = PageLayout(name="MyLayout") doc.automaticstyles.addElement(pagelayout) pagelayout.addElement( PageLayoutProperties(margin="0pt", pagewidth="800pt", pageheight="600pt", printorientation="landscape")) # Style for the title frame of the page # We set a centered 34pt font with yellowish background titlestyle = Style(name="MyMaster-title2", family="presentation") titlestyle.addElement(ParagraphProperties(textalign="center")) titlestyle.addElement(TextProperties(fontsize="34pt")) titlestyle.addElement(GraphicProperties(fillcolor="#ffff99")) doc.styles.addElement(titlestyle) # Style for the title frame of the page # We set a centered 34pt font with yellowish background indexstyle = Style(name="MyMaster-title", family="presentation") indexstyle.addElement(ParagraphProperties(textalign="center")) indexstyle.addElement(TextProperties(fontsize="28pt")) indexstyle.addElement(GraphicProperties(fillcolor="#ffffff", stroke="none")) doc.styles.addElement(indexstyle) # Style for the photo frame photostyle = Style(name="MyMaster-photo", family="presentation") doc.styles.addElement(photostyle) # Every drawing page must have a master page assigned to it. masterpage = MasterPage(name="MyMaster", pagelayoutname=pagelayout) doc.masterstyles.addElement(masterpage) dpstyle = Style(name="dp1", family="drawing-page") # dpstyle.addElement(DrawingPageProperties(transitiontype="automatic", # transitionstyle="move-from-top", duration="PT5S")) doc.automaticstyles.addElement(dpstyle) # Title slide page = Page(masterpagename=masterpage) doc.presentation.addElement(page) frame = Frame(stylename=indexstyle, width="720pt", height="500pt", x="40pt", y="10pt") page.addElement(frame) textbox = TextBox() frame.addElement(textbox) textbox.addElement(P(text="IEM Raccoon Report")) frame = Frame(stylename=indexstyle, width="720pt", height="500pt", x="40pt", y="150pt") page.addElement(frame) textbox = TextBox() frame.addElement(textbox) textbox.addElement(P(text="WFO: %s" % (job['wfo'], ))) textbox.addElement( P(text=("Radar: %s Product: %s" "") % (job['radar'], job['nexrad_product']))) textbox.addElement(P(text="Phenomenas: %s" % (job['wtype'], ))) textbox.addElement( P(text="Start Time: %s UTC" % (job['sts'].strftime("%d %b %Y %H"), ))) textbox.addElement( P(text="End Time: %s UTC" % (job['ets'].strftime("%d %b %Y %H"), ))) textbox.addElement(P(text="")) textbox.addElement(P(text="Raccoon Version: %s" % (__REV__, ))) textbox.addElement( P(text="Generated on: %s" % (datetime.datetime.utcnow().strftime("%d %b %Y %H:%M %Z")))) textbox.addElement(P(text="")) textbox.addElement( P(text="Bugs/Comments/Yelling?: daryl herzmann [email protected]")) i = 0 for warning in warnings: # Make Index page for the warning page = Page(masterpagename=masterpage) doc.presentation.addElement(page) titleframe = Frame(stylename=indexstyle, width="700pt", height="500pt", x="10pt", y="10pt") page.addElement(titleframe) textbox = TextBox() titleframe.addElement(textbox) textbox.addElement( P(text="%s.O.NEW.K%s.%s.W.%04i" % (job['sts'].year, job['wfo'], warning['phenomena'], warning['eventid']))) textbox.addElement( P(text="Issue: %s UTC" % (warning['issue'].strftime("%d %b %Y %H:%M"), ))) textbox.addElement( P(text="Expire: %s UTC" % (warning['expire'].strftime("%d %b %Y %H:%M"), ))) textbox.addElement( P(text="Poly Area: %.1f sq km (%.1f sq mi) [%.1f%% vs County]" % (warning['polyarea'], warning['polyarea'] * 0.386102, warning['polyarea'] / warning['countyarea'] * 100.0))) textbox.addElement( P(text="County Area: %.1f square km (%.1f square miles)" % (warning['countyarea'], warning['countyarea'] * 0.386102))) url = ("http://iem.local/GIS/radmap.php?" "layers[]=places&layers[]=legend&layers[]=ci&layers[]=cbw" "&layers[]=sbw&layers[]=uscounties&layers[]=bufferedlsr" "&lsrbuffer=15") url += "&vtec=%s.O.NEW.K%s.%s.W.%04i" % (job['sts'].year, job['wfo'], warning['phenomena'], warning['eventid']) cmd = "wget -q -O %i.png '%s'" % (i, url) os.system(cmd) photoframe = Frame(stylename=photostyle, width="480pt", height="360pt", x="160pt", y="200pt") page.addElement(photoframe) href = doc.addPicture("%i.png" % (i, )) photoframe.addElement(Image(href=href)) i += 1 times = [] now = warning['issue'] while now < warning['expire']: times.append(now) now += datetime.timedelta(minutes=15) times.append(warning['expire'] - datetime.timedelta(minutes=1)) for now in times: page = Page(stylename=dpstyle, masterpagename=masterpage) doc.presentation.addElement(page) titleframe = Frame(stylename=titlestyle, width="720pt", height="56pt", x="40pt", y="10pt") page.addElement(titleframe) textbox = TextBox() titleframe.addElement(textbox) textbox.addElement( P(text="%s.W.%04i Time: %s UTC" % (warning['phenomena'], warning['eventid'], now.strftime("%d %b %Y %H%M")))) if job['nexrad_product'] == 'N0U': if now < SUPER_RES: n0qn0r = 'N0V' else: n0qn0r = 'N0U' else: if now < SUPER_RES: n0qn0r = 'N0R' else: n0qn0r = 'N0Q' url = "http://iem.local/GIS/radmap.php?" url += "layers[]=ridge&ridge_product=%s&ridge_radar=%s&" % ( n0qn0r, job['radar']) url += "layers[]=sbw&layers[]=sbwh&layers[]=uscounties&" url += "layers[]=lsrs&ts2=%s&" % (( now + datetime.timedelta(minutes=15)).strftime("%Y%m%d%H%M"), ) url += "vtec=%s.O.NEW.K%s.%s.W.%04i&ts=%s" % ( job['sts'].year, job['wfo'], warning['phenomena'], warning['eventid'], now.strftime("%Y%m%d%H%M")) cmd = "wget -q -O %i.png '%s'" % (i, url) os.system(cmd) photoframe = Frame(stylename=photostyle, width="640pt", height="480pt", x="80pt", y="70pt") page.addElement(photoframe) href = doc.addPicture("%i.png" % (i, )) photoframe.addElement(Image(href=href)) i += 1 doc.save(outputfile) del doc cmd = "unoconv -f ppt %s" % (outputfile, ) subprocess.call(cmd, shell=True) pptfn = "%s.ppt" % (basefn, ) print("Generated %s with %s slides" % (pptfn, i)) if os.path.isfile(pptfn): print('...copied to webfolder') shutil.copyfile(pptfn, "/mesonet/share/pickup/raccoon/%s" % (pptfn, )) else: print("Uh oh, no output file, lets kill soffice.bin") subprocess.call("pkill --signal 9 soffice.bin", shell=True) add_job(job)
def __init__(self): self.textdoc = OpenDocumentText() self.oneandhalflines = Style(name="oneandhalflines", parentstylename="Standard", family="paragraph") self.oneandhalflines.addElement(ParagraphProperties(lineheight="1.5")) self.textdoc.automaticstyles.addElement(self.oneandhalflines) # Create a style for the paragraph with page-break self.withbreak = Style(name="WithBreak", parentstylename="Standard", family="paragraph") self.withbreak.addElement(ParagraphProperties(breakbefore="page")) self.textdoc.automaticstyles.addElement(self.withbreak) self.footercenterstyle = Style(name="footercenter", family="paragraph", parentstylename="Standard") self.footercenterstyle.addElement(ParagraphProperties(textalign="center")) self.textdoc.automaticstyles.addElement(self.footercenterstyle) self.footerstyle = FooterStyle() self.footerstyle.addElement(HeaderFooterProperties(padding="0.05cm",borderleft="none",borderright="none",bordertop="none",borderbottom="none",shadow="none", minheight="1cm")) #Text Header self.plheaderstyle = PageLayout(name="pl") self.plheaderstyle.addElement(PageLayoutProperties(marginleft="2cm",marginright="2cm",margintop="1cm",marginbottom="1cm")) self.headerstyle = HeaderStyle() self.headerstyle.addElement(HeaderFooterProperties(backgroundcolor="#e6e6ff",padding="0.05cm",borderleft="none",borderright="none",bordertop="none",borderbottom="2.01pt solid #000099",shadow="none", minheight="1cm")) self.plheaderstyle.addElement(self.headerstyle) self.plheaderstyle.addElement(self.footerstyle) self.textdoc.automaticstyles.addElement(self.plheaderstyle) #image header self.pliheaderstyle = PageLayout(name="pli") self.pliheaderstyle.addElement(PageLayoutProperties(marginleft="2cm",marginright="2cm",margintop="1cm",marginbottom="1cm")) self.headeristyle = HeaderStyle() self.headeristyle.addElement(HeaderFooterProperties(padding="0.05cm",borderleft="none",borderright="none",bordertop="none",borderbottom="none",shadow="none", minheight="2cm")) self.pliheaderstyle.addElement(self.headeristyle) self.pliheaderstyle.addElement(self.footerstyle) self.textdoc.automaticstyles.addElement(self.pliheaderstyle) self.h1style = Style(name="Heading 1", family="paragraph",parentstylename="Heading 1") self.h1style.addElement(GraphicProperties(fill="solid",fillcolor="#e6e6ff")) self.h1style.addElement(TextProperties(attributes={'fontsize':"14pt",'fontweight':"bold",'color':"#000099" })) self.h1style.addElement(ParagraphProperties(breakbefore="page",margintop="0.4cm",marginbottom="0.2cm",backgroundcolor="#e6e6ff",padding="0.05cm",borderleft="none",borderright="none",bordertop="none",borderbottom="2.01pt solid #000099",shadow="none")) self.textdoc.automaticstyles.addElement(self.h1style) self.h2style = Style(name="Heading 2s", family="paragraph",parentstylename="Heading 2") self.h2style.addElement(TextProperties(attributes={'fontsize':"12pt",'fontweight':"bold",'color':"#000099" })) self.h2style.addElement(ParagraphProperties(marginleft="0cm",marginright="0cm",margintop="0.2cm",marginbottom="0.2cm",lineheight="150%",textindent="1.2cm",autotextindent="false")) self.textdoc.automaticstyles.addElement(self.h2style) self.h2bstyle = Style(name="Heading 2b", family="paragraph",parentstylename="Heading 2") self.h2bstyle.addElement(ParagraphProperties(breakbefore="page",marginleft="0cm",marginright="0cm",margintop="0.2cm",marginbottom="0.2cm",lineheight="150%",textindent="1.2cm",autotextindent="false")) self.textdoc.automaticstyles.addElement(self.h2bstyle) self.h3style = Style(name="Heading 3s", family="paragraph",parentstylename="Heading 3") self.h3style.addElement(TextProperties(attributes={'fontsize':"12pt",'fontweight':"bold",'color':"#000099" })) self.h3style.addElement(ParagraphProperties(marginleft="0cm",marginright="0cm",margintop="0.2cm",marginbottom="0.2cm",lineheight="150%",textindent="1.2cm",autotextindent="false")) self.textdoc.automaticstyles.addElement(self.h3style) self.h3bstyle = Style(name="Heading 3b", family="paragraph",parentstylename="Heading 3") self.h3bstyle.addElement(TextProperties(attributes={'fontsize':"12pt",'fontweight':"bold",'color':"#000099" })) self.h3bstyle.addElement(ParagraphProperties(breakbefore="page",marginleft="0cm",marginright="0cm",margintop="0.2cm",marginbottom="0.2cm",lineheight="150%",textindent="1.2cm",autotextindent="false")) self.textdoc.automaticstyles.addElement(self.h3bstyle) self.TAB_style = Style(name="Table", family="table-cell", parentstylename="Standard") self.TAB_style.addElement(TableCellProperties(border="0.05pt solid #000000")) self.textdoc.automaticstyles.addElement(self.TAB_style) self.TAB_stylered = Style(name="Table red", family="table-cell", parentstylename="Standard") self.TAB_stylered.addElement(TableCellProperties(backgroundcolor="ff0000",border="0.05pt solid #000000")) self.textdoc.automaticstyles.addElement(self.TAB_stylered) self.tableheaders = Style(name="Table Headers", family="paragraph", parentstylename="Standard") self.tableheaders.addElement(ParagraphProperties(numberlines="false", linenumber="0",textalign="center",margintop="0.2cm",marginbottom="0.2cm")) self.tableheaders.addElement(TextProperties(attributes={'fontsize':"12pt",'fontweight':"bold"})) self.textdoc.styles.addElement(self.tableheaders) self.tablecontents = Style(name="Table Contents", family="paragraph", parentstylename="Standard") self.tablecontents.addElement(ParagraphProperties(numberlines="false", linenumber="0",margintop="0.2cm",marginbottom="0.2cm")) self.tablecontents.addElement(TextProperties(attributes={'fontsize':"12pt" })) self.textdoc.styles.addElement(self.tablecontents) self.tablecontentscenter = Style(name="Table Contents Center", family="paragraph", parentstylename="Standard") self.tablecontentscenter.addElement(ParagraphProperties(numberlines="false", linenumber="0", textalign="center",margintop="0.2cm",marginbottom="0.2cm")) self.tablecontentscenter.addElement(TextProperties(attributes={'fontsize':"12pt" })) self.textdoc.styles.addElement(self.tablecontentscenter) self.tablecontentscenterred = Style(name="Table Contents Center Red", family="paragraph", parentstylename="Standard") self.tablecontentscenterred.addElement(ParagraphProperties(numberlines="false", linenumber="0", textalign="center", backgroundcolor="#ff0000",margintop="0.2cm",marginbottom="0.2cm")) self.tablecontentscenterred.addElement(TextProperties(attributes={'fontsize':"12pt" })) self.textdoc.styles.addElement(self.tablecontentscenterred)
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 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)
if tm1print: tagsp=loadTags(tm1print) print "targetApps: ",targetApps textdoc = OpenDocumentSpreadsheet() # Create automatic styles for the column widths. # ODF Standard section 15.9.1 nameColStyle = Style(name="nameColStyle", family="table-column") nameColStyle.addElement(TableColumnProperties(columnwidth="6cm")) textdoc.automaticstyles.addElement(nameColStyle) tagColStyle = Style(name="tagColStyle", family="table-column") tagColStyle.addElement(TableColumnProperties(columnwidth="5cm")) tagColStyle.addElement(ParagraphProperties(textalign="left")) #?? textdoc.automaticstyles.addElement(tagColStyle) rankColStyle = Style(name="rankColStyle", family="table-column") rankColStyle.addElement(TableColumnProperties(columnwidth="1.5cm")) rankColStyle.addElement(ParagraphProperties(textalign="center")) #?? textdoc.automaticstyles.addElement(rankColStyle) valColStyle = Style(name="valColStyle", family="table-column") valColStyle.addElement(TableColumnProperties(columnwidth="0.9cm")) valColStyle.addElement(ParagraphProperties(textalign="center")) #?? textdoc.automaticstyles.addElement(valColStyle) linkColStyle = Style(name="linkColStyle", family="table-column") linkColStyle.addElement(TableColumnProperties(columnwidth="0.3cm")) linkColStyle.addElement(ParagraphProperties(textalign="center")) #??
# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # # This example shows how to create a manual page break. from odf.opendocument import OpenDocumentText from odf.style import Style, TextProperties, ParagraphProperties from odf.text import P textdoc = OpenDocumentText() # Create a style for the paragraph with page-break withbreak = Style(name="WithBreak", parentstylename="Standard", family="paragraph") withbreak.addElement(ParagraphProperties(breakbefore="page")) textdoc.automaticstyles.addElement(withbreak) p = P(text=u'First paragraph') textdoc.text.addElement(p) p = P(stylename=withbreak, text=u'Second paragraph') textdoc.text.addElement(p) textdoc.save("pagebreak_odfpy.odt")
#!/usr/bin/env python # -*- coding: utf-8 -*- from odf.opendocument import OpenDocumentText from odf.style import Style, TextProperties, ParagraphProperties from odf.style import TableColumnProperties from odf.text import P from odf.table import Table, TableColumn, TableRow, TableCell doc = OpenDocumentText() # Create a style for the table content. One we can modify # later in the word processor. tablecontents = Style(name="Table Contents", family="paragraph") tablecontents.addElement(ParagraphProperties(numberlines="false", linenumber="0")) doc.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")) doc.automaticstyles.addElement(widthshort) widthwide = Style(name="Wwide", family="table-column") widthwide.addElement(TableColumnProperties(columnwidth="1.5in")) doc.automaticstyles.addElement(widthwide) # Start the table, and describe the columns table = Table() table.addElement(TableColumn(numbercolumnsrepeated=4,stylename=widthshort)) table.addElement(TableColumn(numbercolumnsrepeated=3,stylename=widthwide))
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
def _add_headerstyle(self): header = Style(name="ColumnHeader", family="table-cell") header.addElement(ParagraphProperties(textalign="center")) header.addElement(TextProperties(fontweight="bold")) self.doc.styles.addElement(header) return header