def __init__(self, filename=None): self.doc = OpenDocumentSpreadsheet() self.filename = filename # Add some common styles self.tablecontents = Style(name="Table Contents", family="paragraph") self.tablecontents.addElement( ParagraphProperties(numberlines="false", linenumber="0")) self.doc.styles.addElement(self.tablecontents) self.currencystyle = self._add_currencystyle() self.boldcurrencystyle = Style(name="BoldPounds", family="table-cell", parentstylename=self.currencystyle) self.boldcurrencystyle.addElement(TextProperties(fontweight="bold")) self.doc.styles.addElement(self.boldcurrencystyle) self.boldtextstyle = Style(name="BoldText", family="table-cell", parentstylename=self.tablecontents) self.boldtextstyle.addElement(TextProperties(fontweight="bold")) self.doc.styles.addElement(self.boldtextstyle) self._widthstyles = {}
def getStyle(self, c, cell, datastylename, style_id, odfdoc): ''' get a style_name by style_id ''' if not style_id in list(self.styles.keys()): # create new style cs = Style(name = cell, family = 'table-cell', datastylename=datastylename) cs.addElement(TextProperties(color = c.color, fontsize =c.font_size, fontfamily = c.font_family)) # set backgound and borders if c.background_color != "default" and c.background_color != "transparent": cs.addElement(TableCellProperties(backgroundcolor = c.background_color)) if c.border_top != "none": cs.addElement(TableCellProperties(bordertop = c.border_top)) if c.border_bottom != "none": cs.addElement(TableCellProperties(borderbottom = c.border_bottom)) if c.border_left != "none": cs.addElement(TableCellProperties(borderleft = c.border_left)) if c.border_right != "none": cs.addElement(TableCellProperties(borderright = c.border_right)) # set ods conditional style if (c.condition): cns = Style(name = "cns"+cell, family = 'table-cell') cns.addElement(TextProperties(color = c.condition_color)) cns.addElement(TableCellProperties(backgroundcolor = c.condition_background_color)) odfdoc.styles.addElement(cns) cs.addElement(Map(condition = c.condition, applystylename = "cns"+cell)) odfdoc.automaticstyles.addElement(cs) self.styles[style_id] = cell return self.styles[style_id]
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 _modifyFont(doc, stylename, changeto=None, addto=0): ''' :param doc: document handle :param stylename: style name which needs fontsize changing :param change: amount to change fontsize by; Ex. +2/-2 :return: -1 if fail to find text-properties child node ''' node = doc.getStyleByName(stylename) tp = TextProperties() for child in node.childNodes: if child.qname[1] == 'text-properties': tp = child break if tp is None: return -1 attr = _buildAttributesFromSource(tp) if changeto: attr["fontsize"] = changeto else: attr["fontsize"] = str( int(attr["fontsize"].replace('pt', '')) + addto) + 'pt' newTP = TextProperties(attributes=attr) node.insertBefore(newTP, tp) node.removeChild(tp)
def export_to_odt(self, data): document = OpenDocumentText() # Styles s = document.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': "16pt", 'fontweight': "bold" })) s.addElement(h2style) h3style = Style(name="Heading 3", family="paragraph") h3style.addElement( TextProperties(attributes={ 'fontsize': "12pt", 'fontweight': "bold" })) s.addElement(h3style) h4style = Style(name="Heading 4", family="paragraph") h4style.addElement(TextProperties(attributes={'fontsize': "8pt"})) s.addElement(h4style) # Text h = H(outlinelevel=1, stylename=h1style, text="Data of AtmoStation") document.text.addElement(h) h = H(outlinelevel=1, stylename=h2style, text=str(datetime.datetime.now())) document.text.addElement(h) for k, v in data.items(): h = H(outlinelevel=1, stylename=h2style, text=k) document.text.addElement(h) for v1 in v: h = H(outlinelevel=2, stylename=h3style, text="Item") document.text.addElement(h) for v2 in v1: h = H(outlinelevel=3, stylename=h4style, text=str(v2) + ": " + str(v1[v2])) document.text.addElement(h) document.save('templates\\formated_data\\data.odt')
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 __init__(self, filename): self.filename = filename self.doc = OpenDocumentText() # font self.doc.fontfacedecls.addElement((FontFace(name="Arial", fontfamily="Arial", fontsize="10", fontpitch="variable", fontfamilygeneric="swiss"))) # styles style_standard = Style(name="Standard", family="paragraph", attributes={"class": "text"}) style_standard.addElement( ParagraphProperties(punctuationwrap="hanging", writingmode="page", linebreak="strict")) style_standard.addElement(TextProperties(fontname="Arial", fontsize="10pt", fontsizecomplex="10pt", fontsizeasian="10pt")) self.doc.styles.addElement(style_standard) # automatic styles style_normal = Style(name="ResumeText", parentstylename="Standard", family="paragraph") self.doc.automaticstyles.addElement(style_normal) style_bold_text = Style( name="ResumeBoldText", parentstylename="Standard", family="text") style_bold_text.addElement(TextProperties(fontweight="bold", fontweightasian="bold", fontweightcomplex="bold")) self.doc.automaticstyles.addElement(style_bold_text) style_list_text = ListStyle(name="ResumeListText") style_list_bullet = ListLevelStyleBullet(level="1", stylename="ResumeListTextBullet", numsuffix=".", bulletchar=u'\u2022') style_list_bullet.addElement(ListLevelProperties(spacebefore="0.1in", minlabelwidth="0.2in")) style_list_text.addElement(style_list_bullet) self.doc.automaticstyles.addElement(style_list_text) style_bold_para = Style(name="ResumeH2", parentstylename="Standard", family="paragraph") style_bold_para.addElement(TextProperties(fontweight="bold", fontweightasian="bold", fontweightcomplex="bold")) self.doc.automaticstyles.addElement(style_bold_para) style_bold_center = Style(name="ResumeH1", parentstylename="Standard", family="paragraph") style_bold_center.addElement(TextProperties(fontweight="bold", fontweightasian="bold", fontweightcomplex="bold")) style_bold_center.addElement(ParagraphProperties(textalign="center")) self.doc.automaticstyles.addElement(style_bold_center)
def createFinalReportTargetFormat(self, finalReport: List[list]) -> bytes: textdoc = OpenDocumentSpreadsheet() tablecontents = Style(name="Table Contents", family="paragraph") tablecontents.addElement( ParagraphProperties(numberlines="false", linenumber="0")) tablecontents.addElement(TextProperties(fontweight="bold")) textdoc.styles.addElement(tablecontents) table = Table(name="Java Metrics") tr = self.newRow(table) for columnLabels in finalReport[0]: self.addElementToRow(columnLabels, "string", tr, tablecontents) for row in finalReport[1:]: tr = self.newRow(table) self.addElementToRow(row[0], "string", tr, tablecontents) self.addElementToRow(row[1], "string", tr, tablecontents) for element in row[2:]: self.addElementToRow(str(element), "float", tr, tablecontents) textdoc.spreadsheet.addElement(table) stringOutput = BytesIO() textdoc.write(stringOutput) return stringOutput.getvalue()
def create_doc(self): doc = OpenDocumentText() # Page layout: A4 pagelayout = PageLayout(name="A4") doc.automaticstyles.addElement(pagelayout) pagelayout.addElement( PageLayoutProperties(margin="2cm", pageheight="297mm", pagewidth="210mm", printorientation="portrait")) # Use page layout on master page, to set it: masterpage = MasterPage(name="Standard", pagelayoutname="A4") doc.masterstyles.addElement(masterpage) # Styles s = doc.styles self.h1style = Style(name="Heading 1", family="paragraph") self.h1style.addElement( TextProperties(attributes={ 'fontsize': "24pt", 'fontweight': "bold" })) s.addElement(self.h1style) return doc
def test_percentage(self): """ Test that an automatic style can refer to a PercentageStyle as a datastylename """ doc = OpenDocumentSpreadsheet() nonze = PercentageStyle(name='N11') nonze.addElement(Number(decimalplaces='2', minintegerdigits='1')) nonze.addElement(Text(text='%')) doc.automaticstyles.addElement(nonze) pourcent = Style(name='pourcent', family='table-cell', datastylename='N11') pourcent.addElement(ParagraphProperties(textalign='center')) pourcent.addElement( TextProperties(attributes={ 'fontsize': "10pt", 'fontweight': "bold", 'color': "#000000" })) doc.automaticstyles.addElement(pourcent) table = Table(name='sheet1') tr = TableRow() tc = TableCell(formula='=AVERAGE(C4:CB62)/2', stylename='pourcent', valuetype='percentage') tr.addElement(tc) table.addElement(tr) doc.spreadsheet.addElement(table) doc.save(u"TEST.ods") self.saved = True d = load(u"TEST.ods") result = d.contentxml() # contentxml is supposed to yeld a bytes self.assertNotEqual(-1, result.find(b'''<number:percentage-style''')) self.assertNotEqual(-1, result.find(b'''style:data-style-name="N11"''')) self.assertNotEqual(-1, result.find(b'''style:name="pourcent"'''))
def createTargetFormat(self, metricValues: Dict[str, List[int]], metricLabels: List[str]) -> bytes: textdoc = OpenDocumentSpreadsheet() tablecontents = Style(name="Table Contents", family="paragraph") tablecontents.addElement( ParagraphProperties(numberlines="false", linenumber="0")) tablecontents.addElement(TextProperties(fontweight="bold")) textdoc.styles.addElement(tablecontents) table = Table(name="Java Metrics") tr = self.newRow(table) for metricLabel in metricLabels: self.addElementToRow(metricLabel, "string", tr, tablecontents) for methodName in metricValues.keys(): tr = self.newRow(table) self.addElementToRow(methodName, "string", tr, tablecontents) for metricValue in metricValues[methodName]: self.addElementToRow(str(metricValue), "float", tr, tablecontents) textdoc.spreadsheet.addElement(table) stringOutput = BytesIO() textdoc.write(stringOutput) return stringOutput.getvalue()
def create_blank_ods_with_styles(): """Create a dmutils.ods.SpreadSheet pre-configured with some default styles, ready for population with data appropriate for the subclass View. Modifications here (except adding styles) are likely breaking changes.""" spreadsheet = ods.SpreadSheet() # Add the font we will use for the entire spreadsheet. spreadsheet.add_font(FontFace(name="Arial", fontfamily="Arial")) # Add some default styles for columns. spreadsheet.add_style("col-default", "table-column", ( TableColumnProperties(breakbefore="auto"), ), parentstylename="Default") spreadsheet.add_style("col-wide", "table-column", ( TableColumnProperties(columnwidth="150pt", breakbefore="auto"), ), parentstylename="Default") spreadsheet.add_style("col-extra-wide", "table-column", ( TableColumnProperties(columnwidth="300pt", breakbefore="auto"), ), parentstylename="Default") # Add some default styles for rows. spreadsheet.add_style("row-default", "table-row", ( TableRowProperties(breakbefore="auto", useoptimalrowheight="false"), ), parentstylename="Default") spreadsheet.add_style("row-tall", "table-row", ( TableRowProperties(breakbefore="auto", rowheight="30pt", useoptimalrowheight="false"), ), parentstylename="Default") spreadsheet.add_style("row-tall-optimal", "table-row", ( TableRowProperties(breakbefore="auto", rowheight="30pt", useoptimalrowheight="true"), ), parentstylename="Default") # Add some default styles for cells. spreadsheet.add_style("cell-default", "table-cell", ( TableCellProperties(wrapoption="wrap", verticalalign="top"), TextProperties(fontfamily="Arial", fontnameasian="Arial", fontnamecomplex="Arial", fontsize="11pt"), ), parentstylename="Default") spreadsheet.add_style("cell-header", "table-cell", ( TableCellProperties(wrapoption="wrap", verticalalign="top"), TextProperties(fontfamily="Arial", fontnameasian="Arial", fontnamecomplex="Arial", fontsize="11pt", fontweight="bold"), ), parentstylename="Default") return spreadsheet
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
def addParagraphStyle(self, id, name, paragraph_properties={}, text_properties={}, graphic_properties={}): style = Style(name=name, family="paragraph") if len(paragraph_properties)>0: style.addElement(ParagraphProperties(**paragraph_properties)) if len(text_properties)>0: style.addElement(TextProperties(**text_properties)) setattr(self, id, style) self.document.styles.addElement(style)
def writer(data, **kwargs): """ Liberally adapted from odfpy's csv2ods script. """ def handle_formula(f): return TableCell(valuetype="float", formula="{}".format(f)) textdoc = OpenDocumentSpreadsheet(**kwargs) # 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")) tablecontents.addElement(TextProperties(fontweight="bold")) textdoc.styles.addElement(tablecontents) # Start the table table = Table(name=u'Sheet 1') fltExp = re.compile('^\s*[-+]?\d+(\.\d+)?\s*$') for row in data: tr = TableRow() table.addElement(tr) for val in row: if isinstance(val, spreadsheet.Formula): tc = handle_formula(val) else: valuetype = 'string' if not isinstance(val, unicode): if isinstance(val, str): text_value = "{}".format(val, PWENC, 'replace') else: text_value = "{}".format(val) else: text_value = val if isinstance(val, (float, int, long)) or (isinstance( val, str) and fltExp.match(text_value)): valuetype = 'float' if valuetype == 'float': tc = TableCell(valuetype="float", value=text_value.strip()) else: tc = TableCell(valuetype=valuetype) if val is not None: p = P(stylename=tablecontents, text=text_value) tc.addElement(p) tr.addElement(tc) textdoc.spreadsheet.addElement(table) result = StringIO() textdoc.write(result) return result.getvalue()
def _generate_styles(self): self._h1_style = Style(name="Heading 1", family="paragraph") self._h1_style.addElement(ParagraphProperties(attributes={"margintop": "24pt", "marginbottom": "12pt", "keepwithnext": "always"})) self._h1_style.addElement(TextProperties(attributes={"fontsize": "16pt"})) self._document.styles.addElement(self._h1_style) self._p_style = Style(name="Body", family="paragraph") self._p_style.addElement(ParagraphProperties(attributes={"textindent": "1.25cm", "textalign": "justify", "orphans": 2, "widows": 2})) self._document.styles.addElement(self._p_style)
def init(LOdoc, numfonts=1): totalwid = 6800 #6.8inches #compute column widths f = min(numfonts,4) ashare = 4*(6-f) dshare = 2*(6-f) bshare = 100 - 2*ashare - dshare awid = totalwid * ashare // 100 dwid = totalwid * dshare // 100 bwid = totalwid * bshare // (numfonts * 100) # create styles for table, for columns (one style for each column width) # and for one cell (used for everywhere except where background changed) tstyle = Style(name="Table1", family="table") tstyle.addElement(TableProperties(attributes={'width':str(totalwid/1000.)+"in", 'align':"left"})) LOdoc.automaticstyles.addElement(tstyle) tastyle = Style(name="Table1.A", family="table-column") tastyle.addElement(TableColumnProperties(attributes={'columnwidth':str(awid/1000.)+"in"})) LOdoc.automaticstyles.addElement(tastyle) tbstyle = Style(name="Table1.B", family="table-column") tbstyle.addElement(TableColumnProperties(attributes={'columnwidth':str(bwid/1000.)+"in"})) LOdoc.automaticstyles.addElement(tbstyle) tdstyle = Style(name="Table1.D", family="table-column") tdstyle.addElement(TableColumnProperties(attributes={'columnwidth':str(dwid/1000.)+"in"})) LOdoc.automaticstyles.addElement(tdstyle) ta1style = Style(name="Table1.A1", family="table-cell") ta1style.addElement(TableCellProperties(attributes={'padding':"0.035in", 'border':"0.05pt solid #000000"})) LOdoc.automaticstyles.addElement(ta1style) # text style used with non-<em> text t1style = Style(name="T1", family="text") t1style.addElement(TextProperties(attributes={'color':"#999999" })) LOdoc.automaticstyles.addElement(t1style) # create styles for Title, Subtitle tstyle = Style(name="Title", family="paragraph") tstyle.addElement(TextProperties(attributes={'fontfamily':"Arial",'fontsize':"24pt",'fontweight':"bold" })) LOdoc.styles.addElement(tstyle) ststyle = Style(name="Subtitle", family="paragraph") ststyle.addElement(TextProperties(attributes={'fontfamily':"Arial",'fontsize':"18pt",'fontweight':"bold" })) LOdoc.styles.addElement(ststyle)
def _process_style(self, style: dict[str, Any]) -> str: """Convert a style dictionary to a OpenDocument style sheet Parameters ---------- style : Dict Style dictionary Returns ------- style_key : str Unique style key for later reference in sheet """ from odf.style import ( ParagraphProperties, Style, TableCellProperties, TextProperties, ) if style is None: return None style_key = json.dumps(style) if style_key in self._style_dict: return self._style_dict[style_key] name = f"pd{len(self._style_dict)+1}" self._style_dict[style_key] = name odf_style = Style(name=name, family="table-cell") if "font" in style: font = style["font"] if font.get("bold", False): odf_style.addElement(TextProperties(fontweight="bold")) if "borders" in style: borders = style["borders"] for side, thickness in borders.items(): thickness_translation = {"thin": "0.75pt solid #000000"} odf_style.addElement( TableCellProperties( attributes={ f"border{side}": thickness_translation[thickness] })) if "alignment" in style: alignment = style["alignment"] horizontal = alignment.get("horizontal") if horizontal: odf_style.addElement(ParagraphProperties(textalign=horizontal)) vertical = alignment.get("vertical") if vertical: odf_style.addElement( TableCellProperties(verticalalign=vertical)) self.book.styles.addElement(odf_style) return name
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 _create_style(name, family=None, **kwargs): """Helper function for creating a new style.""" if family == 'paragraph' and 'marginbottom' not in kwargs: kwargs['marginbottom'] = '.5cm' style = Style(name=name, family=family) # Extract paragraph properties. kwargs_par = {} keys = sorted(kwargs.keys()) for k in keys: if 'margin' in k: kwargs_par[k] = kwargs.pop(k) style.addElement(TextProperties(**kwargs)) if kwargs_par: style.addElement(ParagraphProperties(**kwargs_par)) return style
def defineStyles(self): # entête s = Style(name = "Header", family ="paragraph") prop = {"numberlines":"false", "linenumber":"0"} P = ParagraphProperties(**prop) Q = TabStops() Q.addElement(TabStop(position="8.5cm", type="center")) Q.addElement(TabStop(position="17cm", type="right")) P.addElement(Q) s.addElement(P) prop2 = {"fontfamily": "Verdana", "fontweight": "bold", "fontsize": "14pt"} s.addElement(TextProperties(**prop2)) self.document.styles.addElement(s) setattr(self, "Header", s) #autres self.addParagraphStyle("heading1", "Heading 1", paragraph_properties={"breakbefore": "page", "lineheight": "24pt"}, text_properties={"fontfamily": "Verdana", "fontweight": "bold", "fontsize": "14pt"} ) self.addParagraphStyle("heading2", "Heading 2", paragraph_properties={"breakbefore": "false", "lineheight": "24pt"}, text_properties={"fontfamily": "Verdana", "fontweight": "italic", "fontsize": "14pt"} ) self.addParagraphStyle("heading3", "Heading 3", paragraph_properties={"breakbefore": "false", "lineheight": "20pt"}, text_properties={"fontfamily": "Liberation Sans", "fontweight": "bold", "fontsize": "14pt"} ) self.addParagraphStyle("normal", "Normal", paragraph_properties={"breakbefore": "false", "lineheight": "20pt"}, text_properties={"fontfamily": "Liberation Serif", "fontsize": "12pt"} ) self.addParagraphStyle("gras", "Bgr", paragraph_properties={"breakbefore": "false", "lineheight": "20pt"}, text_properties={"fontfamily": "Liberation Serif", "fontweight": "bold", "fontsize": "12pt"} ) self.addParagraphStyle("tablecontents", "Table Contents", paragraph_properties={"numberlines": "false", "linenumber": "0"} ) self.addPageLayoutStyle("mpm1", "Mpm1", \ properties={"pagewidth":"21.001cm", "pageheight": "14.801cm",\ "numformat": "1", "printorientation": "landscape",\ "margintop":"1cm", "marginbottom": "1cm", "marginleft": "1cm",\ "marginright": "1cm", "writingmode":"lr-tb"})#, "footnotemaxheight":"0cm" self.addTableColumnStyle("column1", "Left Column", properties={"columnwidth": "4cm"}) self.addTableColumnStyle("column2", "Center Column", properties={"columnwidth": "4cm"}) self.addTableColumnStyle("column3", "Right Column", properties={"columnwidth": "2cm"})
def inittable(textdoc): # 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")) tablecontents.addElement(TextProperties(fontweight="bold")) textdoc.styles.addElement(tablecontents) widewidth = Style(name="co1", family="table-column") widewidth.addElement( TableColumnProperties(columnwidth="9", breakbefore="auto")) textdoc.automaticstyles.addElement(widewidth) textdoc.styles.addElement(widewidth) table = Table(name='test') table.addElement( TableColumn(stylename=widewidth, defaultcellstylename="ce1")) return table, tablecontents, textdoc
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 __handleFrameStyleRotated(self, text_data): style_name = 'box%s%s%s%s%sRotated' % ( text_data.face, text_data.size, text_data.line_space, text_data.letter_space, text_data.justification) if not style_name in self.font_styles: frame_style = Style(name=style_name, family='paragraph') frame_style.addElement( ParagraphProperties(linespacing='%spt' % text_data.line_space, textalign=self.convertTextAlign( text_data.justification))) frame_style.addElement( TextProperties( letterspacing='%spt' % text_data.letter_space, fontstyle=self.convertFontStyle(text_data.style), fontweight=self.convertFontWeight(text_data.weight), fontsize='%spt' % text_data.size, fontfamily=str(text_data.face))) self.document.automaticstyles.addElement(frame_style) self.font_styles.append(style_name) return style_name
def __init__(self): self.doc = OpenDocumentSpreadsheet() #styles self.itemRowStyle1 = Style(name="itemRowStyle", family="table-row") self.itemRowStyle1.addElement(TableRowProperties(rowheight="7mm")) self.doc.automaticstyles.addElement(self.itemRowStyle1) self.itemRowStyle3 = Style(name="itemRowStyle", family="table-row") self.itemRowStyle3.addElement(TableRowProperties(rowheight="30mm")) self.doc.automaticstyles.addElement(self.itemRowStyle3) self.colStyle30 = Style(name="colStyle30", family="table-column") self.colStyle30.addElement(TableColumnProperties(columnwidth="25mm")) self.doc.automaticstyles.addElement(self.colStyle30) self.colStyle40 = Style(name="colStyle40", family="table-column") self.colStyle40.addElement(TableColumnProperties(columnwidth="40mm")) self.doc.automaticstyles.addElement(self.colStyle40) self.colStyle50 = Style(name="colStyle50", family="table-column") self.colStyle50.addElement(TableColumnProperties(columnwidth="50mm")) self.doc.automaticstyles.addElement(self.colStyle50) self.colStyle200 = Style(name="colStyle200", family="table-column") self.colStyle200.addElement(TableColumnProperties(columnwidth="200mm")) self.doc.automaticstyles.addElement(self.colStyle200) self.cellStyle1 = Style(name="cellStyle1",family="table-cell", parentstylename='Standard', displayname="middle") self.cellStyle1.addElement(ParagraphProperties(textalign="center")) self.cellStyle1.addElement(TableCellProperties(verticalalign="middle")) self.cellStyle1.addElement(TableCellProperties(wrapoption="wrap")) self.doc.automaticstyles.addElement(self.cellStyle1) self.hdrStyle = Style(name="hdrStyle",family="table-cell", parentstylename='Standard', displayname="middle") self.hdrStyle.addElement(ParagraphProperties(textalign="center")) self.hdrStyle.addElement(TextProperties(fontweight="bold")) self.hdrStyle.addElement(TableCellProperties(verticalalign="middle")) self.doc.automaticstyles.addElement(self.hdrStyle)
# Contributor(s): # Søren Roug # This example shows how to do a conditional currency style. We want negative # numbers to show as red and as Australian dollars. from odf.opendocument import OpenDocumentSpreadsheet from odf.style import Style, TextProperties, TableColumnProperties, Map from odf.number import NumberStyle, CurrencyStyle, CurrencySymbol, Number, Text from odf.text import P from odf.table import Table, TableColumn, TableRow, TableCell textdoc = OpenDocumentSpreadsheet() # Create a style for the table content. One we can modify # later in the spreadsheet. tablecontents = Style(name="Large number", family="table-cell") tablecontents.addElement(TextProperties(fontfamily="Arial", fontsize="15pt")) textdoc.styles.addElement(tablecontents) # Create automatic styles for the column widths. widewidth = Style(name="co1", family="table-column") widewidth.addElement( TableColumnProperties(columnwidth="2.8cm", breakbefore="auto")) textdoc.automaticstyles.addElement(widewidth) # Create the styles for $AUD format currency values ns1 = CurrencyStyle(name="positive-AUD", volatile="true") ns1.addElement(CurrencySymbol(language="en", country="AU", text=u"$")) ns1.addElement(Number(decimalplaces="2", minintegerdigits="1", grouping="true")) textdoc.styles.addElement(ns1)
def insert_table_(self, ar, column_names=None, table_width=180): # logger.info("20160330 insert_table(%s)", ar) 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(**cleankw(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(**cleankw(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) + "." + str(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): # if i == 0: # logger.info("20160330a value2cell(%s, %s)", fld.__class__, val) txt = fld.value2html(ar, val) # if i == 0: # logger.info("20160330b value2cell(%s)", E.tostring(txt)) p = text.P(stylename=style_name) html2odf(txt, p) try: tc.addElement(p) except Exception as e: dd.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_text(fld.field.verbose_name or fld.name))) text=force_text(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) sums = {fld.name: sums[i] for i, fld in enumerate(columns)} 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)
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-title", family="presentation") titlestyle.addElement(ParagraphProperties(textalign="center")) titlestyle.addElement(TextProperties(fontsize="34pt")) titlestyle.addElement(GraphicProperties(fillcolor="#ffff99")) doc.styles.addElement(titlestyle) # Style for the photo frame photostyle = Style(name="MyMaster-photo", family="presentation") doc.styles.addElement(photostyle) # Create automatic transition dpstyle = Style(name="dp1", family="drawing-page") dpstyle.addElement( DrawingPageProperties(transitiontype="automatic", transitionstyle="move-from-top", duration="PT5S")) doc.automaticstyles.addElement(dpstyle)
numstyle1 = ListLevelStyleNumber(level="1", stylename="Numbering_20_Symbols", numsuffix=".", numformat='1') L5prop1 = ListLevelProperties(spacebefore="0.25in", minlabelwidth="0.25in") numstyle1.addElement(L5prop1) L5style.addElement(numstyle1) textdoc.automaticstyles.addElement(L5style) # T1 """ <style:style style:name="T1" style:family="text"> <style:text-properties fo:font-style="italic" style:font-style-asian="italic" style:font-style-complex="italic"/> </style:style> """ T1style = Style(name="T1", family="text") T1style.addElement(TextProperties(fontstyle="italic",fontstyleasian="italic", fontstylecomplex="italic")) textdoc.automaticstyles.addElement(T1style) # T2 """ <style:style style:name="T2" style:family="text"> <style:text-properties fo:font-weight="bold" style:font-weight-asian="bold" style:font-weight-complex="bold"/> </style:style> """ T2style = Style(name="T2", family="text") T2style.addElement(TextProperties(fontweight="bold",fontweightasian="bold", fontweightcomplex="bold")) textdoc.automaticstyles.addElement(T2style) # T5
def do_job(job): """Do something""" warnings = get_warnings(job['sts'], job['ets'], job['wfo'], job['wtype']) mydir = "%s/%s" % (TMPDIR, 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, )) # Cleanup os.chdir(TMPDIR) subprocess.call("rm -rf %s" % (job['jobid'], ), shell=True) else: print("Uh oh, no output file, lets kill soffice.bin") subprocess.call("pkill --signal 9 soffice.bin", shell=True) add_job(job)