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 addText(self, data_box): text = data_box.getText() frame_style = Style(name='FrameStyle', family='graphic') debug('Angle: %s', data_box.text_data.angle) angle = data_box.text_data.angle if angle: frame_style = Style(name='FrameStyleRotated', family='graphic') x, y, width, height = data_box.getBoundsPrintSize( self.current_page_resolution) frame = Frame(stylename=frame_style, width=str(width) + 'in', height=str(height) + 'in', x=str(x) + 'in', y=str(y) + 'in', anchortype='paragraph') if angle: frame.addAttribute( 'transform', 'rotate (%s) translate (%scm %scm)' % (abs(math.radians(angle)), x, y)) self.current_page.addElement(frame) textbox = TextBox() frame.addElement(textbox) for line in text.split('\n'): textbox.addElement( P(stylename=self.__handleFrameStyle(data_box.text_data), text=line))
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 extract_highlight_odf(name, img_quality, two_col, output_folder=None): textdoc = OpenDocumentText() doc_mask = fitzopen(name) doc_text = fitzopen(name) nb_pages = doc_text.pageCount #create style for paragraph style_p = Style(name="P1", family="paragraph", parentstylename="Standard") p_prop = ParagraphProperties(textalign="justify", justifysingleword="false") style_p.addElement(p_prop) textdoc.automaticstyles.addElement(style_p) #create style for images style_i = Style(name="fr1", family="graphic", parentstylename="Graphics") i_prop = GraphicProperties(wrap="none", runthrough="foreground", horizontalpos="center", horizontalrel="paragraph") style_i.addElement(i_prop) textdoc.automaticstyles.addElement(style_i) #insert pdf file name textdoc.text.addElement(P(stylename=style_p, text=f"{name}\n\n")) #isolate highlights in _mask and text in _text doc_mask, doc_text = Page_Get_Highlights(doc_mask, doc_text) #iterate over pages to create rectangles to extract for i in range(nb_pages): if two_col == True: #colonnes for col in [1, 2]: rect, hierarchy, Xrects = Page_Get_Rects(doc_mask[i], col) if rect.shape[0] > 0: textdoc = Page_Rect_get_Text_odf(doc_text, i, rect, hierarchy, Xrects, textdoc, style_p, style_i, img_quality, col) else: col = 0 rect, hierarchy, Xrects = Page_Get_Rects(doc_mask[i], col) if rect.shape[0] > 0: textdoc = Page_Rect_get_Text_odf(doc_text, i, rect, hierarchy, Xrects, textdoc, style_p, style_i, img_quality, col) if output_folder is not None: basename = os.path.basename(name) outname = basename.replace(".pdf", ".odt") outname = os.path.join(output_folder, outname) textdoc.save(outname) else: textdoc.save(name.replace(".pdf", ".odt")) doc_mask.close() doc_text.close()
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 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 count_size(wh_list, row): """Count height of image row. Args: wh_list - list with attributes, contains width and height: row - image row. """ height, width = -1, -1 for l in wh_list: if l[0] == 'width': width = float(l[1].replace('in', '')) if l[0] == 'height': height = float(l[1].replace('in', '')) if height == -1 or width == -1: width = ININTENCM height = ININTENCM if width > ININTENCM: new_width = ININTENCM new_height = height * new_width / width else: new_width = width new_height = height height_set = str(new_height) + 'in' new_name = 'image' + str(image_counter) height_suit = Style(name=new_name, family='table-row') height_suit.addElement(TableRowProperties(rowheight=height_set)) ods.automaticstyles.addElement(height_suit) row.setAttribute(attr='stylename', value=new_name) new_width = str(new_width) + 'in' new_height = height_set return new_width, new_height
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 generate_ods(data): """ Generate a ODS file. :param data: list-like of dict with the data. :return: """ doc = OpenDocumentSpreadsheet() table = Table() tr = TableRow() colautowidth = Style(name="co1", family="table-column") colautowidth.addElement(TableColumnProperties(useoptimalcolumnwidth=True)) doc.automaticstyles.addElement(colautowidth) for column in data[0].keys(): table.addElement(TableColumn(stylename=colautowidth)) tc = TableCell(valuetype="string", value=column) tc.addElement(P(text=column)) tr.addElement(tc) table.addElement(tr) for row in data: tr = TableRow() for column in row.keys(): tc = TableCell(valuetype="string", value=row[column]) tc.addElement(P(text=row[column])) tr.addElement(tc) table.addElement(tr) file = os.path.join( tempfile.gettempdir(), 'SIGE' + datetime.now().strftime('%Y%m%d%H%M%S%f') + '.ods') doc.spreadsheet.addElement(table) print(doc.automaticstyles.childNodes[0].attributes) doc.save(file) return file
def extract_highlight_odf(name): textdoc = OpenDocumentText() location = os.path.join("/tmp/pdf_highlight/", name) doc_mask = fitzopen(location) doc_text = fitzopen(location) nb_pages = doc_text.pageCount style_p = Style(name="P1", family="paragraph", parentstylename="Standard") p_prop = ParagraphProperties(textalign="justify", justifysingleword="false") style_p.addElement(p_prop) textdoc.automaticstyles.addElement(style_p) textdoc.text.addElement(P(stylename=style_p, text=f"{name}\n\n")) for i in range(nb_pages): rect, hierarchy = Page_Get_Rects(doc_mask, doc_text, name, i) if rect.shape[0] > 0: textdoc = Page_Rect_get_Text_odf(doc_text, name, i, rect, hierarchy, textdoc, style_p) text_name = name.replace(".pdf", ".odt") location_out = os.path.join("/tmp/pdf_highlight/", text_name) textdoc.save(location_out) #print('fin') return text_name, location_out
def add_style(self, name, family, styles, **kwargs): style = Style(name=name, family=family, **kwargs) for v in styles: style.addElement(v) self._document.automaticstyles.addElement(style)
def colwidth(self, width): if width not in self._widthstyles: w = Style(name="W{}".format(width), family="table-column") w.addElement(TableColumnProperties(columnwidth=width)) self.doc.automaticstyles.addElement(w) self._widthstyles[width] = w return self._widthstyles[width]
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 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 _add_datestyle(self, name="Date", include_time=False): """Construct a date style""" slash = number.Text() slash.addText('/') ds = number.DateStyle(name="Date", automaticorder="true", formatsource="language") ds.addElement(number.Day()) ds.addElement(slash) ds.addElement(number.Month()) ds.addElement(slash) ds.addElement(number.Year()) if include_time: space = number.Text() space.addText(' ') colon = number.Text() colon.addText(':') ds.addElement(space) ds.addElement(number.Hours()) ds.addElement(colon) ds.addElement(number.Minutes()) self.doc.styles.addElement(ds) datestyle = Style(name=name, family="table-cell", parentstylename="Default", datastylename=name) self.doc.styles.addElement(datestyle) return datestyle
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 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 _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 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 saltolinea(documento): withbreak = Style(name="WithBreak", parentstylename="Standard", family="paragraph") withbreak.addElement(ParagraphProperties(breakafter="page")) documento.automaticstyles.addElement(withbreak) p = P(stylename=withbreak) documento.text.addElement(p) return documento
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 __init__(self, name): self.name = name self.document = OpenDocumentText() self.current_page = None self.photo_style = Style(name="Photo", family="graphic") self.document.styles.addElement(self.photo_style) self.font_styles = [] self.page_layouts = [] self.page_masters = [] self.page_styles = [] self.temp_images = [] frame_style = Style(name='FrameStyle', family='graphic') frame_style.addElement(GraphicProperties(borderlinewidth='none')) self.document.styles.addElement(frame_style) frame_style_rotated = Style(name='FrameStyleRotated', family='graphic') frame_style_rotated.addElement( GraphicProperties(fill='none', stroke='none', verticalpos='from-top', verticalrel='paragraph')) self.document.automaticstyles.addElement(frame_style_rotated)
def newPage(self, page_data): master_name = self.__handlePageMaster(page_data) page_style_name = '%sPage' % master_name if not page_style_name in self.page_styles: page_style = Style(name=page_style_name, family='paragraph', masterpagename=master_name) page_style.addElement(ParagraphProperties(breakbefore='page')) self.document.automaticstyles.addElement(page_style) new_page = P(stylename=page_style_name) self.document.text.addElement(new_page) return new_page
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 _add_currencystyle(self, name="Pounds"): """Construct a currency style""" cs = number.CurrencyStyle(name=name) symbol = number.CurrencySymbol(language="en", country="GB") symbol.addText("£") cs.addElement(symbol) n = number.Number(decimalplaces=2, minintegerdigits=1, grouping="true") cs.addElement(n) self.doc.styles.addElement(cs) currencystyle = Style(name=name, family="table-cell", parentstylename="Default", datastylename=name) self.doc.styles.addElement(currencystyle) return currencystyle
def write(self): super().write() self.doc = OpenDocumentSpreadsheet() self.cell_formats = {} for key, value in self.colours.items(): style = Style(name=key, family="table-cell") style.addElement(TableCellProperties(backgroundcolor="#" + value)) self.doc.automaticstyles.addElement(style) self.cell_formats[key] = style for sheet in self.sheets: self.write_table(sheet) self.doc.save(self.filename, True)