def setUp(self): d = OpenDocumentText() # Styles h1style = style.Style(name=u"Heading 1", family=u"paragraph") h1style.addElement( style.TextProperties(attributes={ 'fontsize': u"24pt", 'fontweight': u"bold" })) d.styles.addElement(h1style) boldstyle = style.Style(name=u"Bold", family=u"text") boldstyle.addElement( style.TextProperties(attributes={'fontweight': u"bold"})) d.automaticstyles.addElement(boldstyle) # Text h = H(outlinelevel=1, stylename=h1style, text=u"Simple test document") d.text.addElement(h) p = P( text= u"The earth's climate has not changed many times in the course of its long history. " ) d.text.addElement(p) boldpart = Span(stylename=boldstyle, text=u"This part is bold. ") p.addElement(boldpart) p.addText(u"This is after bold.") d.save(u"TEST.odt")
def convert_text_only(self): """Конвертация текста в файле ODT. Конвертируется все содерржимое <body>. Результат записывается в файл *.cnv.odt :return: None """ body = self.doc.body new_doc = OpenDocumentText() for _body_elem in body.childNodes: for _elem in _body_elem.childNodes: body_text = teletype.extractText(_elem) body_text = self.converter(body_text) para = text.P() teletype.addTextToElement(para, body_text) new_doc.text.addElement(para) # print(body_text) # Замена шрифта в стилях. if self.style_font: self.set_font_for_all_styles() _suffix = '.all.odt' if self.extension: _suffix = self.extension new_odt = self.p_odt.with_suffix(_suffix) new_doc.save(new_odt.as_posix())
class OdtConverter(Converter): def __init__(self, output_file_name): self._document = OpenDocumentText() self._raw_document_content = [] self._output_file_path = "target/{}.odt".format(output_file_name) self._h1_style = None self._p_style = None def convert(self): self._generate_styles() sources = self._process_input_files() for source in sources: self._raw_document_content += source self._process_raw_document_content() self._document.save(self._output_file_path) 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 _process_raw_document_content(self): for line in self._raw_document_content: if line.startswith("# "): new_element = H(outlinelevel=1, stylename=self._h1_style, text=line.replace("# ", "")) else: new_element = P(text=line, stylename=self._p_style) self._document.text.addElement(new_element)
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 test_headings(self): textdoc = OpenDocumentText() textdoc.text.addElement(H(outlinelevel=1, text="Heading 1")) textdoc.text.addElement(P(text="Hello World!")) textdoc.text.addElement(H(outlinelevel=2, text="Heading 2")) textdoc.save("TEST.odt") self.saved = True result = odf2moinmoin.ODF2MoinMoin("TEST.odt") self.assertEquals(u'= Heading 1 =\n\nHello World!\n== Heading 2 ==\n\n', result.toString())
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 test_linebreak(self): textdoc = OpenDocumentText() p = P(text="Hello World!") textdoc.text.addElement(p) p.addElement(LineBreak()) p.addText("Line 2") textdoc.save("TEST.odt") self.saved = True result = odf2moinmoin.ODF2MoinMoin("TEST.odt") self.assertEquals(u'Hello World![[BR]]Line 2\n', result.toString())
def exportODT(examen, archivo): """ Function to export the data exam to a odt file. The input data is the exam and the ODT file to write. This function uses odfpy library """ # Extract data from exam asignatura = examen.asignatura nombre = examen.nombre preguntas = examen.preguntas textdoc = OpenDocumentText() h = H(outlinelevel=1, text=asignatura) textdoc.text.addElement(h) h = H(outlinelevel=4, text=nombre) textdoc.text.addElement(h) # an element is added to the object "textdoc" for each question i = 1 for pregunta in preguntas: texto = str(i) + ".- " + pregunta.texto p = P(text=texto) textdoc.text.addElement(p) # For test questions if pregunta.tipo == 1: for opcion in pregunta.opciones: texto = opcion.letra + ") " + opcion.texto p = P(text=texto) textdoc.text.addElement(p) # For true or false questions elif pregunta.tipo == 2: texto = "A) Verdadero" p = P(text=texto.encode('utf-8')) textdoc.text.addElement(p) texto = "B) Falso" p = P(text=texto) textdoc.text.addElement(p) p = P() textdoc.text.addElement(p) p = P() textdoc.text.addElement(p) i = i + 1 # Save complete file textdoc.save(archivo) return examen
def exportODT(examen, archivo): """ Function to export the data exam to a odt file. The input data is the exam and the ODT file to write. This function uses odfpy library """ # Extract data from exam asignatura = examen.asignatura nombre = examen.nombre preguntas = examen.preguntas textdoc = OpenDocumentText() h = H(outlinelevel=1, text=asignatura) textdoc.text.addElement(h) h = H(outlinelevel=4, text=nombre) textdoc.text.addElement(h) # an element is added to the object "textdoc" for each question i = 1 for pregunta in preguntas: texto = str(i) + ".- " + pregunta.texto p = P(text = texto) textdoc.text.addElement(p) # For test questions if pregunta.tipo == 1: for opcion in pregunta.opciones: texto = opcion.letra + ") " + opcion.texto p = P(text = texto) textdoc.text.addElement(p) # For true or false questions elif pregunta.tipo == 2: texto = "A) Verdadero" p = P(text = texto.encode('utf-8')) textdoc.text.addElement(p) texto = "B) Falso" p = P(text = texto) textdoc.text.addElement(p) p = P() textdoc.text.addElement(p) p = P() textdoc.text.addElement(p) i = i + 1 # Save complete file textdoc.save(archivo) return examen
def create_dummy_odt(lorem, iter, rand): """ Création de pièces jointes ODT dummy """ lorem_rand = random.randint(1, 6) lorem_rand_2 = random.randint(1, 6) for x in range(1, iter): textdoc = OpenDocumentText() texte = lorem[lorem_rand] + lorem[lorem_rand_2] p = P(text=texte) textdoc.text.addElement(p) textdoc.save("./dummy/test_{a}".format(a=str(x)), True) print("Fait ODT")
class Document_Generic(object): """Example of document""" def __init__(self): self.document = OpenDocumentText() self.defineStyles() def defineStyles(self): """ """ pass def addParagraphStyle(self, id, name, paragraph_properties={}, text_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 addTableColumnStyle(self, id, name, properties={}): """ """ style = Style(name=name, family="table-column") style.addElement(TableColumnProperties(**properties)) setattr(self, id, style) self.document.automaticstyles.addElement(style) def addParagraph(self, text, stylename): """ """ stylename = getattr(self, stylename, None) p = P(stylename=stylename, text=text) self.document.text.addElement(p) def addTable(self, content, cell_style, column_styles=[]): """ """ cell_style = getattr(self, cell_style, None) table = Table() for style in column_styles: if "stylename" in style.keys(): style["stylename"] = getattr(self, style["stylename"], None) table.addElement(TableColumn(**style)) for row in content: tr = TableRow() table.addElement(tr) for cell in row: tc = TableCell() tr.addElement(tc) p = P(stylename=cell_style,text=cell) tc.addElement(p) self.document.text.addElement(table) def save(self, filename): """ """ self.document.save(filename)
def test_headings(self): """ Create a document, save it and load it """ textdoc = OpenDocumentText() textdoc.text.addElement(H(outlinelevel=1, text=u"Heading 1")) textdoc.text.addElement(P(text=u"Hello World!")) textdoc.text.addElement(H(outlinelevel=2, text=u"Heading 2")) textdoc.save(u"TEST.odt") self.saved = True d = load(u"TEST.odt") result = d.contentxml() # contentxml() is supposed to yeld a bytes self.assertNotEqual(-1, result.find(b"""<text:h text:outline-level="1">Heading 1</text:h><text:p>Hello World!</text:p><text:h text:outline-level="2">Heading 2</text:h>"""))
def test_linebreak(self): """ Test that a line break (empty) element show correctly """ textdoc = OpenDocumentText() p = P(text=u"Hello World!") textdoc.text.addElement(p) p.addElement(LineBreak()) p.addText(u"Line 2") textdoc.save(u"TEST.odt") self.saved = True d = load(u"TEST.odt") result = d.contentxml() # contentxml() is supposed to yeld a bytes self.assertNotEqual(-1, result.find(b"""<text:p>Hello World!<text:line-break/>Line 2</text:p>"""))
class TestUnicode(unittest.TestCase): def setUp(self): self.textdoc = OpenDocumentText() self.saved = False def tearDown(self): if self.saved: os.unlink("TEST.odt") def assertContains(self, stack, needle): self.assertNotEqual(-1, stack.find(needle)) def assertNotContains(self, stack, needle): self.assertEqual(-1, stack.find(needle)) @unittest.skipIf(sys.version_info[0] != 2, "For Python3, unicode strings are type 'str'.") def test_xstyle(self): self.assertRaises(UnicodeDecodeError, style.Style, name="X✗", family="paragraph") xstyle = style.Style(name=u"X✗", family=u"paragraph") pp = style.ParagraphProperties(padding=u"0.2cm") pp.setAttribute(u"backgroundcolor", u"rød") xstyle.addElement(pp) self.textdoc.styles.addElement(xstyle) self.textdoc.save(u"TEST.odt") self.saved = True def test_text(self): p = P(text=u"Æblegrød") p.addText(u' Blåbærgrød') self.textdoc.text.addElement(p) self.textdoc.save(u"TEST.odt") self.saved = True def test_contenttext(self): p = H(outlinelevel=1,text=u"Æblegrød") p.addText(u' Blåbærgrød') self.textdoc.text.addElement(p) c = self.textdoc.contentxml() # contentxml is supposed to yield a bytes self.assertContains(c, b'<office:body><office:text><text:h text:outline-level="1">\xc3\x86blegr\xc3\xb8d Bl\xc3\xa5b\xc3\xa6rgr\xc3\xb8d</text:h></office:text></office:body>') self.assertContains(c, b'xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"') self.assertContains(c, b'<office:automatic-styles/>') def test_illegaltext(self): p = H(outlinelevel=1,text=u"Spot \u001e the") p.addText(u' d\u00a3libe\u0000rate \ud801 mistakes\U0002fffe') self.textdoc.text.addElement(p) c = self.textdoc.contentxml() # contentxml is supposed to yield a bytes # unicode replacement char \UFFFD === \xef\xbf\xbd in UTF-8 self.assertContains(c, b'<office:body><office:text><text:h text:outline-level="1">Spot \xef\xbf\xbd the d\xc2\xa3libe\xef\xbf\xbdrate \xef\xbf\xbd mistakes\xef\xbf\xbd</text:h></office:text></office:body>') self.assertContains(c, b'xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"') self.assertContains(c, b'<office:automatic-styles/>')
class TestUnicode(unittest.TestCase): def setUp(self): self.textdoc = OpenDocumentText() self.saved = False def tearDown(self): if self.saved: os.unlink("TEST.odt") def test_subobject(self): df = draw.Frame(width="476pt", height="404pt", anchortype="paragraph") self.textdoc.text.addElement(df) subdoc = OpenDocumentText() # Here we add the subdocument to the main document. We get back a reference # to use in the href. subloc = self.textdoc.addObject(subdoc) self.assertEqual(subloc, "./Object 1") do = draw.Object(href=subloc) df.addElement(do) subsubdoc = OpenDocumentText() subsubloc = subdoc.addObject(subsubdoc) self.assertEqual(subsubloc, "./Object 1/Object 1") c = unicode(self.textdoc.contentxml(), "UTF-8") c.index( u'<office:body><office:text><draw:frame svg:width="476pt" text:anchor-type="paragraph" svg:height="404pt"><draw:object xlink:href="./Object 1"/></draw:frame></office:text></office:body>' ) c.index(u'xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"') self.textdoc.save("TEST.odt") self.saved = True m = _getxmlpart("TEST.odt", "META-INF/manifest.xml") m.index( '<manifest:file-entry manifest:media-type="application/vnd.oasis.opendocument.text" manifest:full-path="/"/>' ) m.index('<manifest:file-entry manifest:media-type="text/xml" manifest:full-path="styles.xml"/>') m.index('<manifest:file-entry manifest:media-type="text/xml" manifest:full-path="content.xml"/>') m.index('<manifest:file-entry manifest:media-type="text/xml" manifest:full-path="meta.xml"/>') m.index( '<manifest:file-entry manifest:media-type="application/vnd.oasis.opendocument.text" manifest:full-path="Object 1/"/>' ) m.index('<manifest:file-entry manifest:media-type="text/xml" manifest:full-path="Object 1/styles.xml"/>') m.index('<manifest:file-entry manifest:media-type="text/xml" manifest:full-path="Object 1/content.xml"/>') m.index( '<manifest:file-entry manifest:media-type="application/vnd.oasis.opendocument.text" manifest:full-path="Object 1/Object 1/"/>' ) m.index( '<manifest:file-entry manifest:media-type="text/xml" manifest:full-path="Object 1/Object 1/styles.xml"/>' ) m.index( '<manifest:file-entry manifest:media-type="text/xml" manifest:full-path="Object 1/Object 1/content.xml"/>' )
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 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')
class TestUnicode(unittest.TestCase): def setUp(self): self.textdoc = OpenDocumentText() self.saved = False def tearDown(self): if self.saved: os.unlink("TEST.odt") def test_subobject(self): df = draw.Frame(width="476pt", height="404pt", anchortype="paragraph") self.textdoc.text.addElement(df) subdoc = OpenDocumentText() # Here we add the subdocument to the main document. We get back a reference # to use in the href. subloc = self.textdoc.addObject(subdoc) self.assertEqual(subloc,'./Object 1') do = draw.Object(href=subloc) df.addElement(do) subsubdoc = OpenDocumentText() subsubloc = subdoc.addObject(subsubdoc) self.assertEqual(subsubloc,'./Object 1/Object 1') c = self.textdoc.contentxml() # contentxml() is supposed to yeld a bytes c.index(b'<office:body><office:text><draw:frame ') e = ElementParser(c.decode("utf-8"), u'draw:frame') # e = ElementParser('<draw:frame svg:width="476pt" text:anchor-type="paragraph" svg:height="404pt">') self.assertTrue(e.has_value(u'svg:width',"476pt")) self.assertTrue(e.has_value(u'svg:height',"404pt")) self.assertTrue(e.has_value(u'text:anchor-type',"paragraph")) self.assertFalse(e.has_value(u'svg:height',"476pt")) c.index(b'<draw:object xlink:href="./Object 1"/></draw:frame></office:text></office:body>') c.index(b'xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"') self.textdoc.save(u"TEST.odt") self.saved = True m = _getxmlpart(u"TEST.odt", u"META-INF/manifest.xml").decode('utf-8') assert(element_has_attributes(m, u'manifest:file-entry', u'manifest:media-type="application/vnd.oasis.opendocument.text" manifest:full-path="/"')) assert(element_has_attributes(m, u'manifest:file-entry', u'manifest:media-type="application/vnd.oasis.opendocument.text" manifest:full-path="/"')) assert(element_has_attributes(m, u'manifest:file-entry', u'manifest:media-type="text/xml" manifest:full-path="content.xml"')) assert(element_has_attributes(m, u'manifest:file-entry', u'manifest:media-type="text/xml" manifest:full-path="meta.xml"')) assert(element_has_attributes(m, u'manifest:file-entry', u'manifest:media-type="application/vnd.oasis.opendocument.text" manifest:full-path="Object 1/"')) assert(element_has_attributes(m, u'manifest:file-entry', u'manifest:media-type="text/xml" manifest:full-path="Object 1/styles.xml"')) assert(element_has_attributes(m, u'manifest:file-entry', u'manifest:media-type="text/xml" manifest:full-path="Object 1/content.xml"')) assert(element_has_attributes(m, u'manifest:file-entry', u'manifest:media-type="application/vnd.oasis.opendocument.text" manifest:full-path="Object 1/Object 1/"')) assert(element_has_attributes(m, u'manifest:file-entry', u'manifest:media-type="text/xml" manifest:full-path="Object 1/Object 1/styles.xml"')) assert(element_has_attributes(m, u'manifest:file-entry', u'manifest:media-type="text/xml" manifest:full-path="Object 1/Object 1/content.xml"'))
class TestUnicode(unittest.TestCase): def setUp(self): self.textdoc = OpenDocumentText() self.saved = False def tearDown(self): if self.saved: os.unlink("TEST.odt") def assertContains(self, stack, needle): self.assertNotEqual(-1, stack.find(needle)) def assertNotContains(self, stack, needle): self.assertEqual(-1, stack.find(needle)) @unittest.skipIf(sys.version_info[0] != 2, "For Python3, unicode strings are type 'str'.") def test_xstyle(self): self.assertRaises(UnicodeDecodeError, style.Style, name="X✗", family="paragraph") xstyle = style.Style(name=u"X✗", family=u"paragraph") pp = style.ParagraphProperties(padding=u"0.2cm") pp.setAttribute(u"backgroundcolor", u"rød") xstyle.addElement(pp) self.textdoc.styles.addElement(xstyle) self.textdoc.save(u"TEST.odt") self.saved = True def test_text(self): p = P(text=u"Æblegrød") p.addText(u' Blåbærgrød') self.textdoc.text.addElement(p) self.textdoc.save(u"TEST.odt") self.saved = True def test_contenttext(self): p = H(outlinelevel=1, text=u"Æblegrød") p.addText(u' Blåbærgrød') self.textdoc.text.addElement(p) c = self.textdoc.contentxml() # contentxml is supposed to yeld a bytes self.assertContains( c, b'<office:body><office:text><text:h text:outline-level="1">\xc3\x86blegr\xc3\xb8d Bl\xc3\xa5b\xc3\xa6rgr\xc3\xb8d</text:h></office:text></office:body>' ) self.assertContains( c, b'xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"') self.assertContains(c, b'<office:automatic-styles/>')
def test_headings(self): """ Create a document, save it and load it """ textdoc = OpenDocumentText() textdoc.text.addElement(H(outlinelevel=1, text="Heading 1")) textdoc.text.addElement(P(text="Hello World!")) textdoc.text.addElement(H(outlinelevel=2, text="Heading 2")) textdoc.save("TEST.odt") self.saved = True d = load("TEST.odt") result = d.contentxml() self.assertNotEqual( -1, result.find( u"""<text:h text:outline-level="1">Heading 1</text:h><text:p>Hello World!</text:p><text:h text:outline-level="2">Heading 2</text:h>""" ))
def test_linebreak(self): """ Test that a line break (empty) element show correctly """ textdoc = OpenDocumentText() p = P(text="Hello World!") textdoc.text.addElement(p) p.addElement(LineBreak()) p.addText("Line 2") textdoc.save("TEST.odt") self.saved = True d = load("TEST.odt") result = d.contentxml() self.assertNotEqual( -1, result.find( u"""<text:p>Hello World!<text:line-break/>Line 2</text:p>"""))
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")
class TestUnicode(unittest.TestCase): def setUp(self): self.textdoc = OpenDocumentText() self.saved = False def tearDown(self): if self.saved: os.unlink("TEST.odt") def assertContains(self, stack, needle): self.assertNotEqual(-1, stack.find(needle)) def assertNotContains(self, stack, needle): self.assertEquals(-1, stack.find(needle)) def test_xstyle(self): self.assertRaises(UnicodeDecodeError, style.Style, name="X✗", family="paragraph") xstyle = style.Style(name=u"X✗", family="paragraph") pp = style.ParagraphProperties(padding="0.2cm") pp.setAttribute("backgroundcolor", u"rød") xstyle.addElement(pp) self.textdoc.styles.addElement(xstyle) self.textdoc.save("TEST.odt") self.saved = True def test_text(self): p = P(text=u"Æblegrød") p.addText(u' Blåbærgrød') self.textdoc.text.addElement(p) self.textdoc.save("TEST.odt") self.saved = True def test_contenttext(self): p = H(outlinelevel=1, text=u"Æblegrød") p.addText(u' Blåbærgrød') self.textdoc.text.addElement(p) c = unicode(self.textdoc.contentxml(), 'UTF-8') self.assertContains( c, u'<office:body><office:text><text:h text:outline-level="1">\xc6blegr\xf8d Bl\xe5b\xe6rgr\xf8d</text:h></office:text></office:body>' ) self.assertContains( c, u'xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"') self.assertContains(c, u'<office:automatic-styles/>')
def convert_and_save(text, filename): textdoc = OpenDocumentText() # Useless: This style setting is somehow overwritten by LibreOffice ''' rubistyle = Style(name="Rubi1", family="ruby") rubistyle.addElement(RubyProperties(attributes={"rubyalign": "center", "rubyposition": "above"})) textdoc.styles.addElement(rubistyle) ''' lines = text.splitlines() for line in lines: paragraph_element = create_paragraph(line) textdoc.text.addElement(paragraph_element) textdoc.save(filename)
class DocFactory: def __init__(self, filename): self.filename = filename self.quotStyle = Style(name="Quotations") self.marginaliaStyle = Style(name="Marginalia") self.doc = OpenDocumentText() def add_p1_text(self, txt): self.doc.text.addElement(P(text=txt)) def add_p2_text(self, txt): self.doc.text.addElement(P(text=txt, stylename=self.quotStyle)) def add_p3_text(self, txt): self.doc.text.addElement(P(text=txt, stylename=self.marginaliaStyle)) def save(self): self.doc.save(self.filename)
def save_test(self): new_partition = OpenDocumentText() T5style = Style(name="T5", family="text") T5style.addElement(TextProperties(fontname="Arial")) new_partition.automaticstyles.addElement(T5style) for i in range(len(self.allText)): old_text = teletype.extractText(self.allText[i]) p = text.P(text="", stylename="T5") for j in range(len(old_text)): if (old_text[j] == " " and i in self.lignes): p.addElement(Span(text=' ', stylename='T5')) else: p.addText(old_text[j]) new_partition.text.addElement(p) new_partition.save("x_test.odt")
def image_spice(genre, font, spice): for myspice in spice: myodt = OpenDocumentText() # template is updated by font text_template[genre].update(text_style[genre][font]) paragraph_template[genre].update(paragraph_style[genre][font]) template = genre2template(genre, text_template[genre], font, paragraph_template[genre]) myodt.styles.addElement(template) image_spices(myodt, myspice, font) text_frame(myodt, genre, font) label(myodt, myspice, font) myname = genre + "_" + font + "_" + myspice myodt.save(myname, True)
class TestUnicode(unittest.TestCase): def setUp(self): self.textdoc = OpenDocumentText() self.saved = False def tearDown(self): if self.saved: os.unlink("TEST.odt") def test_subobject(self): df = draw.Frame(width="476pt", height="404pt", anchortype="paragraph") self.textdoc.text.addElement(df) subdoc = OpenDocumentText() # Here we add the subdocument to the main document. We get back a reference # to use in the href. subloc = self.textdoc.addObject(subdoc) self.assertEqual(subloc,'./Object 1') do = draw.Object(href=subloc) df.addElement(do) subsubdoc = OpenDocumentText() subsubloc = subdoc.addObject(subsubdoc) self.assertEqual(subsubloc,'./Object 1/Object 1') c = unicode(self.textdoc.contentxml(),'UTF-8') c.index(u'<office:body><office:text><draw:frame svg:width="476pt" text:anchor-type="paragraph" svg:height="404pt"><draw:object xlink:href="./Object 1"/></draw:frame></office:text></office:body>') c.index(u'xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"') self.textdoc.save("TEST.odt") self.saved = True m = _getxmlpart("TEST.odt", "META-INF/manifest.xml") m.index('<manifest:file-entry manifest:media-type="application/vnd.oasis.opendocument.text" manifest:full-path="/"/>') m.index('<manifest:file-entry manifest:media-type="text/xml" manifest:full-path="styles.xml"/>') m.index('<manifest:file-entry manifest:media-type="text/xml" manifest:full-path="content.xml"/>') m.index('<manifest:file-entry manifest:media-type="text/xml" manifest:full-path="meta.xml"/>') m.index('<manifest:file-entry manifest:media-type="application/vnd.oasis.opendocument.text" manifest:full-path="Object 1/"/>') m.index('<manifest:file-entry manifest:media-type="text/xml" manifest:full-path="Object 1/styles.xml"/>') m.index('<manifest:file-entry manifest:media-type="text/xml" manifest:full-path="Object 1/content.xml"/>') m.index('<manifest:file-entry manifest:media-type="application/vnd.oasis.opendocument.text" manifest:full-path="Object 1/Object 1/"/>') m.index('<manifest:file-entry manifest:media-type="text/xml" manifest:full-path="Object 1/Object 1/styles.xml"/>') m.index('<manifest:file-entry manifest:media-type="text/xml" manifest:full-path="Object 1/Object 1/content.xml"/>')
class TestUnicode(unittest.TestCase): def setUp(self): self.textdoc = OpenDocumentText() self.saved = False def tearDown(self): if self.saved: os.unlink("TEST.odt") def assertContains(self, stack, needle): self.assertNotEqual(-1, stack.find(needle)) def assertNotContains(self, stack, needle): self.assertEquals(-1, stack.find(needle)) def test_xstyle(self): self.assertRaises(UnicodeDecodeError, style.Style, name="X✗", family="paragraph") xstyle = style.Style(name=u"X✗", family=u"paragraph") pp = style.ParagraphProperties(padding=u"0.2cm") pp.setAttribute(u"backgroundcolor", u"rød") xstyle.addElement(pp) self.textdoc.styles.addElement(xstyle) self.textdoc.save(u"TEST.odt") self.saved = True def test_text(self): p = P(text=u"Æblegrød") p.addText(u' Blåbærgrød') self.textdoc.text.addElement(p) self.textdoc.save(u"TEST.odt") self.saved = True def test_contenttext(self): p = H(outlinelevel=1,text=u"Æblegrød") p.addText(u' Blåbærgrød') self.textdoc.text.addElement(p) c = self.textdoc.contentxml() # contentxml is supposed to yeld a bytes self.assertContains(c, b'<office:body><office:text><text:h text:outline-level="1">\xc3\x86blegr\xc3\xb8d Bl\xc3\xa5b\xc3\xa6rgr\xc3\xb8d</text:h></office:text></office:body>') self.assertContains(c, b'xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"') self.assertContains(c, b'<office:automatic-styles/>')
def write_export_node_to_file(odt_file, item_list): """ Exporting process to ODT file. :param odt_file: ODT file pathname, :param item_list: array of strings with document list items. """ mixed_list_spec = '1.,1.,1.,1.,1.,1.' textdoc = OpenDocumentText() s = textdoc.styles list_style = easyliststyle.styleFromString( "mix", mixed_list_spec, ",", "0.8cm", easyliststyle.SHOW_ONE_LEVEL) s.addElement(list_style) list_element = BpmnDiagramGraphOdtExport.create_list( item_list, ">", "mix") textdoc.text.addElement(list_element) textdoc.save(odt_file)
def main(): doc = OpenDocumentText() p = P(text=u'text') df = odf.draw.Frame(zindex=0, anchortype='as-char') p.addElement(df) doc.text.addElement(p) formula = u'c=sqrt(a^2+b^2)' math = Math() annot = Element(qname=(MATHNS, u'annotation')) annot.addText(formula, check_grammar=False) annot.setAttribute((MATHNS, 'encoding'), 'StarMath 5.0', check_grammar=False) math.addElement(annot) do = odf.draw.Object() do.addElement(math) df.addElement(do) outputfile = u'result' doc.save(outputfile, True)
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 setUp(self): d = OpenDocumentText() # Styles h1style = style.Style(name=u"Heading 1",family=u"paragraph") h1style.addElement(style.TextProperties(attributes={'fontsize':u"24pt", 'fontweight':u"bold"})) d.styles.addElement(h1style) boldstyle = style.Style(name=u"Bold",family=u"text") boldstyle.addElement(style.TextProperties(attributes={'fontweight':u"bold"})) d.automaticstyles.addElement(boldstyle) # Text h = H(outlinelevel=1, stylename=h1style, text=u"Simple test document") d.text.addElement(h) p = P(text=u"The earth's climate has not changed many times in the course of its long history. ") d.text.addElement(p) boldpart = Span(stylename=boldstyle, text=u"This part is bold. ") p.addElement(boldpart) p.addText(u"This is after bold.") d.save(u"TEST.odt")
def parse(): file = open("in.srt", "r") skip = False; statement = False; cur_text = "" doc = OpenDocumentText() for line in file: line = line.strip('\n').strip('\n').strip(' ') if skip: skip = False statement = True continue if len(line) == 0: p = P(text = cur_text) p1 = P(text = " ") doc.text.addElement(p) doc.text.addElement(p1) cur_text = "" statement = False continue lst = re.findall(r'\d+', line) if (len(lst) > 0): skip = True continue if statement == True: # Appending a line to text cur_text = cur_text + " " + line continue doc.save("out.odt")
def odfRender(dic_slides_odf, nomePrj): lista_slides = dic_slides_odf.keys() lista_slides.sort() manualODF = OpenDocumentText() outline = {'outlinelevel': 1} for x in lista_slides[1:]: titulo = dic_slides_odf[x]["titulo"] h = H( text=titulo, attributes=outline) manualODF.text.addElement(h) lista_conteudo = dic_slides_odf[x]['conteudo'].keys() lista_conteudo.sort() for num in lista_conteudo: if dic_slides_odf[x]['conteudo'][num]['tipo'] == 'par': texto_capitulo = dic_slides_odf[x]['conteudo'][num]['valor'] if dic_slides_odf[x]['conteudo'][num]['tipo'] == 'ite': texto_capitulo = " - " + dic_slides_odf[x]['conteudo'][num]['valor'] if dic_slides_odf[x]['conteudo'][num]['tipo'] == 'img': texto_capitulo = "Figura: " + dic_slides_odf[x]['conteudo'][num]['valor'] p = P(text=texto_capitulo) manualODF.text.addElement(p) manualODF.save("%s/%s" % (nomePrj,nomePrj), True) return "ok"
uf = UserFieldDecls() textdoc.text.addElement(uf) # Add user fields for id, transunit in body_info.items(): uf.addElement(UserFieldDecl(name=id, valuetype="string", stringvalue=transunit["target"])) # Start the table, and describe the columns mytable = table.Table(protected="true") mytable.addElement(table.TableColumn(numbercolumnsrepeated=2, stylename=widthwide)) for id, transunit in body_info.items(): tr = table.TableRow() mytable.addElement(tr) tc = table.TableCell(stylename=tcstyle, qattributes={(TABLENS, "protected"): "true"}) tr.addElement(tc) p = P(stylename=tablecontents, text=transunit["source"]) tc.addElement(p) tc = table.TableCell(qattributes={(TABLENS, "protected"): "true"}) tr.addElement(tc) p = P(stylename=tablecontents) tc.addElement(p) f = UserFieldInput(name=id, description="Enter translation") p.addElement(f) textdoc.text.addElement(mytable) textdoc.save("translations.odt")
class Doc(object): def __init__(self, matchobj): self.__doc = OpenDocumentText() self.__createStyles() self.__createHeading(matchobj) self.__createContent(matchobj) def __createHeading(self, matchobj): HdgTxt = '{0:d} words, Solved \'{1:s}\' in {2:.3f} seconds'.format( len(matchobj.match), matchobj.chars.upper(), matchobj.completeTime) self.__doc.text.addElement(H(outlinelevel = 1, text=HdgTxt)) txt=P(text='Check the results, some may be acronyms, names or slang terms.') self.__doc.text.addElement(txt) def __wordHeading(self, wordlist): return '{0:d} - {1:d} Letter words'.format(len(wordlist), len(wordlist[0])) def __createContent(self, words): splitList = splitbylength(words.match) for wordlist in splitList: self.__doc.text.addElement(H(outlinelevel = 2, text=self.__wordHeading(wordlist))) self.__doc.text.addElement(P(text=', '.join(word for word in wordlist))) self.__doc.text.addElement(P(text='\n\nhttps://github.com/WillBickerstaff/sundial')) def __createStyles(self): self.__addFonts self.__setDefaultStyle() self.__setHeadingStyle() def __setHeadingStyle(self): HdgStyle = Style(name="Heading", family='paragraph', parentstylename="Standard") HdgStyle.addElement(TextProperties( fontweight='bold', fontfamily='FreeSans', fontsize='120%')) self.__doc.styles.addElement(HdgStyle) ''' Heading 1 ''' HdgStyle = Style(name="Heading_20_1", family='paragraph', parentstylename="Heading") HdgStyle.addElement(TextProperties(fontsize='120%')) self.__doc.styles.addElement(HdgStyle) ''' Heading 2 ''' HdgStyle = Style(name='Heading_20_2', family='paragraph', parentstylename='Heading') HdgStyle.addElement(TextProperties(fontsize='110%', color='#808080')) self.__doc.styles.addElement(HdgStyle) def __setDefaultStyle(self): DefaultStyle = Style(name="Standard", family='paragraph') DefaultStyle.addElement(TextProperties( fontfamily='FreeSans', fontsize='10pt')) DefaultStyle.addElement(ParagraphProperties( margintop='0.423cm', marginbottom='0.212cm')) self.__doc.styles.addElement(DefaultStyle) ''' Text Body ''' txt = Style(name='text_20_body', family='paragraph', parentstylename='Standard') self.__doc.styles.addElement(txt) def __addFonts(self): self.__doc.fontfacedecls.addElement((FontFace( name="FreeSans",fontfamily="FreeSans", fontfamilygeneric="swiss",fontpitch="variable"))) self.__doc.fontfacedecls.addElement((FontFace( name="Nimbus Mono", fontfamily="'Nimbus Mono L&apos", fontfamilygeneric="modern", fontpitch="fixed"))) def write(self, filename): self.__doc.save(filename)
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2007 Søren Roug, European Environment Agency # # This is free software. You may redistribute it under the terms # of the Apache license and the GNU General Public License Version # 2 or at your option any later version. # # This program is distributed in the hope that it will be useful, # 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): # Raymond Yee # # Probably the shortest script possible from odf.opendocument import OpenDocumentText from odf.text import P textdoc = OpenDocumentText() p = P(text="Hello World!") textdoc.text.addElement(p) textdoc.save("helloworld", True)
def generate_odf_plan_document(plan_pk, file_path): # Neues Textdokument erstellen document = OpenDocumentText() # # Styles definieren # center_bold = Style(name="Center Bold", family="paragraph") center_bold.addElement(ParagraphProperties(textalign="center")) center_bold.addElement(TextProperties(fontweight="bold")) document.styles.addElement(center_bold) center = Style(name="Center", family="paragraph") center.addElement(ParagraphProperties(textalign="center")) document.styles.addElement(center) left = Style(name="Left", family="paragraph") left.addElement(ParagraphProperties(numberlines="false", linenumber="0", textalign="left")) document.styles.addElement(left) bold_style = Style(name="Bold", family="text") bold_style.addElement(TextProperties(fontweight="bold")) document.styles.addElement(bold_style) # # Breite der Spaleten in den Tabellen setzen # width_short = Style(name="Wshort", family="table-column") width_short.addElement(TableColumnProperties(columnwidth="3.0cm")) document.automaticstyles.addElement(width_short) width_medium = Style(name="Wmedium", family="table-column") width_medium.addElement(TableColumnProperties(columnwidth="4.0cm")) document.automaticstyles.addElement(width_medium) width_wide = Style(name="Wwide", family="table-column") width_wide.addElement(TableColumnProperties(columnwidth="10.59cm")) document.automaticstyles.addElement(width_wide) # Tabelle mit zwei schmalen und einer breiten Spalte erstellen table = Table() table.addElement(TableColumn(numbercolumnsrepeated=1, stylename=width_short)) table.addElement(TableColumn(numbercolumnsrepeated=1, stylename=width_medium)) table.addElement(TableColumn(numbercolumnsrepeated=1, stylename=width_wide)) # Generiert eine Zeile in der Tabelle def generate_row(datetime, location, extra, acolytes): # Datum und Uhrzeit formatieren date_string = datetime.strftime("%d.%m.%Y") time_string = datetime.strftime("%H:%M") # Neue TableRow erstellen und einfügen row = TableRow() table.addElement(row) # Datum - Zeit Zelle anlegen date_time_cell = TableCell() date_time_cell.addElement(P(stylename=center, text=date_string)) date_time_cell.addElement(P(stylename=center_bold, text=time_string)) # Ort - Information Zelle anlegen location_extra_cell = TableCell() location_extra_cell.addElement(P(stylename=center_bold, text=location)) location_extra_cell.addElement(P(stylename=center, text=extra)) # Messdiener Zelle anlegen acolytes_cell = TableCell() # Messdiener nach Rolle sortiert auflisten for role_name in acolytes: p = P(stylename=left) p.addElement(Span(stylename=bold_style, text=f"{role_name}: ")) p.addText(text=', '.join(acolytes[role_name])) acolytes_cell.addElement(p) # Zellen zur TableRow hinzufügen row.addElement(date_time_cell) row.addElement(location_extra_cell) row.addElement(acolytes_cell) # TableRow zurückgeben return row # Durch die Messen nach Zeit sortiert iterieren for mass in Mass.objects.filter(plan=plan_pk).order_by('time'): # Acolyte dict mit einer leeren Liste als default value anlegen acolytes_list = defaultdict(list) # Durch die MassAcolyteRoles nach Rolle sortiert iterieren for mar in mass.massacolyterole_set.order_by('role__roleName'): # Wenn Messdiener keine Rolle hat "Messdiener" als Rolle eintragen role = "Messdiener" # Wenn Messdiener Rolle hat, dann zur Liste der Messdiener dieser Rolle hinzufügen if mar.role is not None: role = mar.role.roleName # Acolyte Namen setzen. Wenn extra Wert hat, dann in Klammern dahinter setzen acolyte_name = f"{mar.acolyte.firstName} {mar.acolyte.lastName}" if mar.acolyte.extra: acolyte_name = f"{mar.acolyte.firstName} {mar.acolyte.lastName} ({mar.acolyte.extra})" acolytes_list[role].append(acolyte_name) # Zeit der Messe zur lokalen Zeit konvertieren utc = mass.time.replace(tzinfo=pytz.UTC) localtime = utc.astimezone(timezone.get_current_timezone()) # Row generieren und zur Tabelle hinzufügen table.addElement(generate_row( localtime, mass.location.locationName, mass.extra, acolytes_list )) # Leere Row für die Übersicht einfügen table.addElement(TableRow()) # Tabelle zum Dokument hinzufügen document.text.addElement(table) # Dokument speichern document.save(file_path)
def odtResponse(eci, horaires, noninscrits, cci=None): """ fabrique un objet de type HttpResponse qui comporte un tableur au format ODT, avec les exportations d'une "barrette" d'AP. @param eci un dictionnaire de dictionnaires enseignant => cours => inscriptions @param horaires les horaires existant dans la "barrette" @param noninscrits une liste d'Etudiants @param cci dictionnaire cop -> coursOrientation -> inscriptionOrientations @return un objet de type HttpResponse """ ## détermine d'abord s'il y a des séances d'orientation, pour la dernière ## ouverture en date. yaCop est un booléen vrai si les COP interviennent. yaCop=len(Orientation.objects.filter( ouverture=Ouverture.objects.last() )) > 0 response = HttpResponse(content_type='application/vnd.oasis.opendocument.text') now=timezone.now() filename="aperho-{}.odt".format(now.strftime("%Y%m%d-%H%M")) response['Content-Disposition'] = 'attachment; filename={}'.format(filename) textdoc = OpenDocumentText() tablecontents = Style(name="Table Contents", family="paragraph") tablecontents.addElement(ParagraphProperties(numberlines="false", linenumber="0")) tablecontents.addElement(TextProperties(fontweight="bold")) textdoc.styles.addElement(tablecontents) w=[] # styles de largeurs de colonnes w1 = Style(name="Wwide1", family="table-column") w1.addElement(TableColumnProperties(columnwidth="0.5in")) textdoc.automaticstyles.addElement(w1) w.append(w1) w2 = Style(name="Wwide2", family="table-column") w2.addElement(TableColumnProperties(columnwidth="2in")) textdoc.automaticstyles.addElement(w2) w.append(w2) w3 = Style(name="Wwide3", family="table-column") w3.addElement(TableColumnProperties(columnwidth="1.5in")) textdoc.automaticstyles.addElement(w3) w.append(w3) w4 = Style(name="Wwide4", family="table-column") w4.addElement(TableColumnProperties(columnwidth="1in")) textdoc.automaticstyles.addElement(w4) w.append(w4) w5 = Style(name="Wwide5", family="table-column") w5.addElement(TableColumnProperties(columnwidth="4in")) textdoc.automaticstyles.addElement(w5) w.append(w5) withbreak = Style(name="WithBreak", parentstylename="Standard", family="paragraph") withbreak.addElement(ParagraphProperties(breakbefore="page")) textdoc.automaticstyles.addElement(withbreak) for e,ci in eci.items(): # e est un enseignant, ci est un dictionnaire p = P(stylename=withbreak,text="") # saut de page manuel textdoc.text.addElement(p) for c,inscriptions in ci.items(): titre="{} {} ({}, {}h, {})".format(c.horaire, c.enseignant.nom, c.enseignant.salle, c.formation.duree, c.formation.titre) textdoc.text.addElement(H(text=titre, outlinelevel=1)) ### on début un tableau n°, Nom, prénom, classe pour les élèves table = Table() nbCol=4 if yaCop: nbCol=5 for i in range(nbCol): table.addElement(TableColumn(stylename=w[i])) textdoc.text.addElement(table) n=1 tr = TableRow() table.addElement(tr) colTitres=("n°","Nom","Prénom","Classe") if yaCop: colTitres=("n°","Nom","Prénom","Classe", "Séance COP") for val in colTitres: tc = TableCell() tr.addElement(tc) p = P(stylename=tablecontents,text=str(val)) tc.addElement(p) for i in inscriptions: tr = TableRow() table.addElement(tr) for val in [n, i.etudiant.nom, i.etudiant.prenom, i.etudiant.classe]: tc = TableCell() tr.addElement(tc) p = P(text=val) tc.addElement(p) if yaCop: tc = TableCell() tr.addElement(tc) p = P(text=rdvOrientation(i)) tc.addElement(p) n+=1 #après chaque enseignant, on passe une page. p = P(stylename=withbreak,text="") # saut de page manuel textdoc.text.addElement(p) titre="Élèves non encore inscrits" textdoc.text.addElement(H(text=titre, outlinelevel=1)) ni=list(noninscrits) ni.sort(key=lambda e: (e.classe, e.nom, e.prenom)) for e in ni: ligne="{} {} {}".format(e.classe, e.nom, e.prenom) textdoc.text.addElement(P(text=ligne)) if cci: for cop, ci in cci.items(): titre="Conseillère d'orientation : {}".format(cop.nom) for cours, inscr in ci.items(): p = P(stylename=withbreak,text="") # saut de page manuel textdoc.text.addElement(p) textdoc.text.addElement(H(text=titre, outlinelevel=1)) titre2="{} {} avec {}".format(localtime(cours.debut).strftime("%d/%m/%Y %H%M"), cours.choice, cours.prof) textdoc.text.addElement(H(text=titre2, outlinelevel=2)) ### on débute un tableau n°, Nom, prénom, classe pour les élèves table = Table() nbCol=4 for i in range(nbCol): table.addElement(TableColumn(stylename=w[i])) textdoc.text.addElement(table) tr = TableRow() table.addElement(tr) colTitres=("n°","Nom","Prénom","Classe") for val in colTitres: tc = TableCell() tr.addElement(tc) p = P(stylename=tablecontents,text=str(val)) tc.addElement(p) ### compteur d'élèves au minimum ... n=1 ### puis on ajoute une ligne par inscription for i in inscr: tr = TableRow() table.addElement(tr) for val in [n, i.etudiant.nom, i.etudiant.prenom, i.etudiant.classe]: tc = TableCell() tr.addElement(tc) p = P(text=val) tc.addElement(p) n+=1 output=BytesIO() textdoc.save(output) response.write(output.getvalue()) return response
observaciones = do_query ("SELECT observaciones from facturas where id='" + factura_id + "';", link) for fila in observaciones: # + Para salto de linea y * para tabulacion enter = fila[0].strip().split("\n") y = P(stylename=style_texto4) for val in enter: tabulacion = val.strip().split("\t") for val in tabulacion: y.addElement (Span(text=val)) doc.text.addElement(y) y.addElement (Tab()) doc.text.addElement(y) y.addElement (LineBreak()) doc.text.addElement (y) # Insertamos el total insertar_total = do_query ("UPDATE facturas SET total='" + str (total_euros) + "' WHERE id='" + factura_id + "';", link) # cerramos la conexión cerrar_conexion (link) print "factura" + factura_id + ".odt" doc.save("factura" + factura_id + ".odt")
class DocumentGenerator: def __init__( self, template=None ): if not template: self.doc = OpenDocumentText() else: self.doc = load( template ) self.cur_par = None self._create_styles() def _create_styles( self ): #Creating new ruby style self.ruby_style_name = "RubyMy" my_ruby_style = Style( name=self.ruby_style_name, family="ruby" ) my_ruby_style.addElement( RubyProperties( rubyalign = "center", rubyposition = "above" ) ) self.doc.automaticstyles.addElement( my_ruby_style ) #Create dotted style self.dot_style_name = "DottedMy" my_dotted_style = Style( name = self.dot_style_name, family="text" ) my_dotted_style.addElement( TextProperties( textemphasize="dot above" ) ) self.doc.automaticstyles.addElement( my_dotted_style ) def _ensure_cur_par( self ): if self.cur_par == None: self.cur_par = P() def add_text( self, text ): self._ensure_cur_par() self.cur_par.addText( text ) def add_text_dotted( self, text ): self._ensure_cur_par() self.cur_par.addElement( Span( stylename=self.dot_style_name, text = text ) ) def new_paragraph( self ): if self.cur_par: self.doc.text.addElement( self.cur_par ) self.cur_par = None else: self.doc.text.addElement( P() ) def new_page( self ): #TODO self.new_paragraph() def add_rubied_text( self, text, ruby ): self._ensure_cur_par() ruby_elt = Ruby( stylename= self.ruby_style_name ) ruby_elt.addElement( RubyBase( text = text ) ) ruby_elt.addElement( RubyText( text = ruby ) ) self.cur_par.addElement( ruby_elt ) def end( self ): if self.cur_par: self.doc.text.addElement( self.cur_par ) self.cur_par = None def save( self, fname ): if self.cur_par: self.end() self.doc.save( fname, not fname.endswith( ".odt" ) )
class ODFTable: PWENC = "utf-8" def __init__(self, outputFilename, orderType='p'): self.outputFilename = outputFilename self.orderType = orderType self.table = None self.finding = 1 self.initializeDocument() def initializeDocument( self ): self.textdoc = OpenDocumentText() # Create a style for the table content. One we can modify # later in the word processor. self.tablecontents = Style(name="Table Contents", family="paragraph") self.tablecontents.addElement(ParagraphProperties(numberlines="false", linenumber="0")) self.textdoc.styles.addElement(self.tablecontents) # ----------------- define a few styles -------------------- # a Bold style self.BoldStyle = Style(name="Bold", family="paragraph") self.BoldProp = TextProperties(fontweight="bold") self.BoldStyle.addElement(self.BoldProp) self.textdoc.automaticstyles.addElement(self.BoldStyle) # for Critical findings self.CriticalStyle = Style(name="Critical Findings", family="paragraph") self.CriticalStyleProp = TextProperties(fontweight="bold", color="#FF0000") self.CriticalStyle.addElement(self.CriticalStyleProp) self.textdoc.automaticstyles.addElement(self.CriticalStyle) # for High findings self.HighStyle = Style(name="High Findings", family="paragraph") self.HighStyleProp = TextProperties(fontweight="bold", color="#FF2400") self.HighStyle.addElement(self.HighStyleProp) self.textdoc.automaticstyles.addElement(self.HighStyle) # for Moderate findings self.ModerateStyle = Style(name="Moderate Findings", family="paragraph") self.ModerateStyleProp = TextProperties(fontweight="bold", color="#FF7F00") self.ModerateStyle.addElement(self.ModerateStyleProp) self.textdoc.automaticstyles.addElement(self.ModerateStyle) # for Low findings self.LowStyle = Style(name="Low Findings", family="paragraph") self.LowStyleProp = TextProperties(fontweight="bold", color="#007FFF") self.LowStyle.addElement(self.LowStyleProp) self.textdoc.automaticstyles.addElement(self.LowStyle) # for 'None' or 'Info' or 'Note' findings self.NoteStyle = Style(name="Note Findings", family="paragraph") self.NoteStyleProp = TextProperties(fontweight="bold") self.NoteStyle.addElement(self.NoteStyleProp) self.textdoc.automaticstyles.addElement(self.NoteStyle) # nessus plugins can give widely inconsistent ratings: serious/high, medium/moderate, info/note/none... self.riskFactorsDict = { 'critical':self.CriticalStyle, 'high':self.HighStyle, 'serious':self.HighStyle, 'medium':self.ModerateStyle, 'moderate':self.ModerateStyle, 'low':self.LowStyle, 'info':self.NoteStyle, 'note':self.NoteStyle, 'none':self.NoteStyle } # 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")) self.textdoc.automaticstyles.addElement(widthshort) widthwide = Style(name="Wwide", family="table-column") widthwide.addElement(TableColumnProperties(columnwidth="1.5in")) self.textdoc.automaticstyles.addElement(widthwide) # hard-code columns styles, per column widthwide = Style(name="Wwide", family="table-column") widthwide.addElement(TableColumnProperties(columnwidth="1.5in")) self.textdoc.automaticstyles.addElement(widthwide) # Start the table and describe the columns self.table = Table() if self.orderType=='p': self.table.addElement(TableColumn(numbercolumnsrepeated=7,stylename=widthwide)) # populate columns with headers... tr = TableRow() self.table.addElement(tr) # declare necessary vars tc1 = TableCell(); tc2 = TableCell(); tc3 = TableCell(); tc4 = TableCell(); tc5 = TableCell(); tc6 = TableCell(); tc7 = TableCell(); addElem = lambda cell, text, s=self: cell.addElement(ODFParagraph(stylename=self.BoldStyle, text=unicode(text, ODFTable.PWENC))) # Add Column 1: Finding Number addElem(tc1, 'Finding Number') tr.addElement(tc1) # Add Column 2: Vulnerability Name addElem(tc2, 'Vulnerability Name') tr.addElement(tc2) # Add Column 3: NIST 800-53 Mapping addElem(tc3, '800-53 Mapping') tr.addElement(tc3) # Add Column 4: Description addElem(tc4, 'Description') tr.addElement(tc4) # Add Column 5: Recommendation addElem(tc5, 'Recommendation') tr.addElement(tc5) # Add Column 6: CVE addElem(tc6, 'CVE') tr.addElement(tc6) # Add Column 6: Hosts Affected addElem(tc7, 'IP Address (Sample of hosts effected)') tr.addElement(tc7) # Print a single entry def printEntry( self, options, result, _ipList=[], count=1 ): if _ipList==[]: ipList=[result.getIP()] else: ipList = ipsort(_ipList) # print header tr = TableRow() self.table.addElement(tr) ''' Finding Number Vulnerability Name 800-53 Mapping Description Recommendation CVE IP Address (Sample of hosts effected) ''' tc1 = TableCell(); tc2 = TableCell(); tc3 = TableCell(); tc4 = TableCell(); tc5 = TableCell(); tc6 = TableCell(); tc7 = TableCell(); addElem = lambda cell, text, s=self: cell.addElement(ODFParagraph(stylename=s.tablecontents, text=text.encode(ODFTable.PWENC))) riskFactor = result.getRiskFactor() # ---- Populate Column 1: Finding Number ---- addElem(tc1, '') addElem(tc1, str(count)) tr.addElement(tc1) # increment the findings count (goes into first column) # self.finding+=1 # ---- Populate Column 2: Vulnerability Description (prepended with port# and service name) ---- # grab the portnum portString='\n%s/%s (%s)' % (result.getPort(), result.getProtocol().upper(), result.getServiceName().upper()) # grab the first sentence of the synopsis (this forms a concise one-line description). vulnerabilityString = unicode(result.getSynopsis().split('.',1)[0].replace('\\n', "\n") + '.') po = result.getPluginOutput() if po is not '': pluginOutput = '\n\nPlugin output:\n\n' + po else: pluginOutput = '' tc2.addElement( ODFParagraph(stylename=self.BoldStyle, text=(vulnerabilityString.decode("iso8859-8") + '\n' + portString).encode(ODFTable.PWENC))) tr.addElement(tc2) # ---- Populate Column 3: NIST 800-53 Mapping ---- tc3.addElement( ODFParagraph(stylename=self.BoldStyle, text=''.encode(ODFTable.PWENC)) ) tr.addElement(tc3) # ---- Populate Column 4: Implication ---- descString = ''.join(result.getDescription().replace('\\n', '\n')) # + pluginOutput.replace('\\n', '\n')) addElem(tc4, descString.strip() ) tc4.addElement( ODFParagraph(stylename=self.BoldStyle, text="\n\n RISK RATING: ".encode(ODFTable.PWENC))) tc4.addElement( ODFParagraph(stylename=self.riskFactorsDict[riskFactor], text=riskFactor.encode(ODFTable.PWENC))) tr.addElement(tc4) # Populate Column 5: Recomendation _recText = result.getRecommendation().replace('\\n', '\n') seeAlsoText = result.getSeeAlso().replace('\\n', '\n') solutionText = result.getSolution() if seeAlsoText is not '' or solutionText is not '': recText = '\n'.join([_recText, '\n\n See also: ', seeAlsoText]) else: recText = _recText addElem(tc5, recText) tr.addElement(tc5) # Column 6: CVE _cveText = result.getCVE() addElem(tc6, _cveText.encode("utf-8")) tr.addElement(tc6) # Populate Column 7: IP Address (Sample of hosts affected) addElem(tc7, '\n'.join(ipsort(uniq(ipList)))) tr.addElement(tc7) def saveAndClose( self ): self.textdoc.text.addElement( self.table ) self.textdoc.save(self.outputFilename)
textStyleB = Style(name="textstyleB", family="paragraph") tpB = TextProperties(fontsize="16pt", fontfamily="diluvienne") textStyleB.addElement(tpB) frameA = Frame(stylename=graphicStyleA, height="15cm", width="10cm") frameB = Frame(stylename=graphicStyleB, height="10cm", width="15cm") doc.styles.addElement(graphicStyleA) doc.styles.addElement(textStyleA) doc.styles.addElement(graphicStyleB) doc.styles.addElement(textStyleB) textboxA = TextBox() textboxB = TextBox() frameA.addElement(textboxA) frameB.addElement(textboxB) pA = P(stylename="textstyleA", text="aaaaaah") pB = P(stylename="textstyleB", text="bbbbbah") textboxA.addElement(pA) textboxB.addElement(pB) doc.text.addElement(frameA) doc.text.addElement(frameB) doc.save("ab", True)
def setUp(self): textdoc = OpenDocumentText() p = P(text="Hello World!") textdoc.text.addElement(p) textdoc.save("TEST.odt") self.saved = True
# This program is distributed in the hope that it will be useful, # 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")
def doit(args): logfile = args.logger if args.report: logfile.loglevel = args.report try: root = ET.parse(args.input).getroot() except: logfile.log("Error parsing FTML input", "S") if args.font: # font(s) specified on command line fontlist = getfonts(args.font, logfile) else: # get font spec from FTML fontsrc element fontlist = getfonts([root.find("./head/fontsrc").text], logfile, False) #fontlist = getfonts( [fs.text for fs in root.findall("./head/fontsrc")], False ) ### would allow multiple fontsrc elements numfonts = len(fontlist) if numfonts == 0: logfile.log("No font(s) specified", "S") if numfonts > 1: formattedfontnum = ["{0:02d}".format(n) for n in range(numfonts)] else: formattedfontnum = [""] logfile.log("Font(s) specified:", "V") for n, (fontname, bold, italic, embeddedfont) in enumerate(fontlist): logfile.log( " " + formattedfontnum[n] + " " + fontname + BoldItalic(bold, italic) + " " + str(embeddedfont), "V") # get optional fontscale; compute pointsize as int(12*fontscale/100). If result xx is not 12, then add "fo:font-size=xxpt" in Px styles pointsize = 12 fontscaleel = root.find("./head/fontscale") if fontscaleel != None: fontscale = fontscaleel.text try: pointsize = int(int(fontscale) * 12 / 100) except ValueError: # any problem leaves pointsize 12 logfile.log("Problem with fontscale value; defaulting to 12 point", "W") # Get FTML styles and generate LO writer styles # P2 is paragraph style for string element when no features specified # each Px (for P3...) corresponds to an FTML style, which specifies lang or feats or both # if numfonts > 1, two-digit font number is appended to make an LO writer style for each FTML style + font combo # When LO writer style is used with attribute rtl="True", "R" appended to style name LOstyles = {} ftmlstyles = {} Pstylenum = 2 LOstyles["P2"] = ("", None, None) ftmlstyles[0] = "P2" for s in root.findall("./head/styles/style"): Pstylenum += 1 Pnum = "P" + str(Pstylenum) featstring = "" if s.get('feats'): featstring = parsefeats(s.get('feats')) langname = None countryname = None lang = s.get('lang') if lang != None: x = re.match(langcode, lang) langname = x.group('langname') countryname = x.group('countryname') # FTML <test> element @stylename attribute references this <style> element @name attribute ftmlstyles[s.get('name')] = Pnum LOstyles[Pnum] = (featstring, langname, countryname) # create LOwriter file and construct styles for tables, column widths, etc. LOdoc = OpenDocumentText() init(LOdoc, numfonts) # Initialize sequence counters sds = SequenceDecls() sd = sds.addElement( SequenceDecl(displayoutlinelevel='0', name='Illustration')) sd = sds.addElement(SequenceDecl(displayoutlinelevel='0', name='Table')) sd = sds.addElement(SequenceDecl(displayoutlinelevel='0', name='Text')) sd = sds.addElement(SequenceDecl(displayoutlinelevel='0', name='Drawing')) LOdoc.text.addElement(sds) # Create Px style for each (featstring, langname, countryname) tuple in LOstyles # and for each font (if >1 font, append to Px style name a two-digit number corresponding to the font in fontlist) # and (if at least one rtl attribute) suffix of nothing or "R" # At the same time, collect info for creating FontFace elements (and any embedded fonts) suffixlist = ["", "R" ] if root.find(".//test/[@rtl='True']") != None else [""] fontfaces = {} for p in sorted(LOstyles, key=lambda x: int(x[1:]) ): # key = lambda x : int(x[1:]) corrects sort order featstring, langname, countryname = LOstyles[p] for n, (fontname, bold, italic, embeddedfont) in enumerate( fontlist): # embeddedfont = None if no embedding needed fontnum = formattedfontnum[n] # Collect fontface info: need one for each font family + feature combination # Put embedded font in list only under fontname with empty featstring if (fontname, featstring) not in fontfaces: fontfaces[(fontname, featstring)] = [] if embeddedfont: if (fontname, "") not in fontfaces: fontfaces[(fontname, "")] = [] if embeddedfont not in fontfaces[(fontname, "")]: fontfaces[(fontname, "")].append(embeddedfont) # Generate paragraph styles for s in suffixlist: pstyle = Style(name=p + fontnum + s, family="paragraph") if s == "R": pstyle.addElement( ParagraphProperties(textalign="end", justifysingleword="false", writingmode="rl-tb")) pstyledic = {} pstyledic['fontnamecomplex'] = \ pstyledic['fontnameasian'] =\ pstyledic['fontname'] = fontname + featstring pstyledic['fontsizecomplex'] = \ pstyledic['fontsizeasian'] = \ pstyledic['fontsize'] = str(pointsize) + "pt" if bold: pstyledic['fontweightcomplex'] = \ pstyledic['fontweightasian'] = \ pstyledic['fontweight'] = 'bold' if italic: pstyledic['fontstylecomplex'] = \ pstyledic['fontstyleasian'] = \ pstyledic['fontstyle'] = 'italic' if langname != None: pstyledic['languagecomplex'] = \ pstyledic['languageasian'] = \ pstyledic['language'] = langname if countryname != None: pstyledic['countrycomplex'] = \ pstyledic['countryasian'] = \ pstyledic['country'] = countryname pstyle.addElement(TextProperties(attributes=pstyledic)) # LOdoc.styles.addElement(pstyle) ### tried this, but when saving the generated odt, LO changed them to automatic styles LOdoc.automaticstyles.addElement(pstyle) fontstoembed = [] for fontname, featstring in sorted( fontfaces ): ### Or find a way to keep order of <style> elements from original FTML? ff = FontFace(name=fontname + featstring, fontfamily=fontname + featstring, fontpitch="variable") LOdoc.fontfacedecls.addElement(ff) if fontfaces[(fontname, featstring)]: # embedding needed for this combination for fontfile in fontfaces[(fontname, featstring)]: fontstoembed.append(fontfile) # make list for embedding ffsrc = FontFaceSrc() ffuri = FontFaceUri( **{ 'href': "Fonts/" + os.path.basename(fontfile), 'type': "simple" }) ffformat = FontFaceFormat(**{'string': 'truetype'}) ff.addElement(ffsrc) ffsrc.addElement(ffuri) ffuri.addElement(ffformat) basename = "Table1.B" colorcount = 0 colordic = { } # record color #rrggbb as key and "Table1.Bx" as stylename (where x is current color count) tablenum = 0 # get title and comment and use as title and subtitle titleel = root.find("./head/title") if titleel != None: LOdoc.text.addElement( H(outlinelevel=1, stylename="Title", text=titleel.text)) commentel = root.find("./head/comment") if commentel != None: LOdoc.text.addElement(P(stylename="Subtitle", text=commentel.text)) # Each testgroup element begins a new table for tg in root.findall("./testgroup"): # insert label attribute of testgroup element as subtitle tglabel = tg.get('label') if tglabel != None: LOdoc.text.addElement( H(outlinelevel=1, stylename="Subtitle", text=tglabel)) # insert text from comment subelement of testgroup element tgcommentel = tg.find("./comment") if tgcommentel != None: #print("commentel found") LOdoc.text.addElement(P(text=tgcommentel.text)) tgbg = tg.get( 'background') # background attribute of testgroup element tablenum += 1 table = Table(name="Table" + str(tablenum), stylename="Table1") table.addElement(TableColumn(stylename="Table1.A")) for n in range(numfonts): table.addElement(TableColumn(stylename="Table1.B")) table.addElement(TableColumn(stylename="Table1.A")) table.addElement(TableColumn(stylename="Table1.D")) for t in tg.findall("./test"): # Each test element begins a new row # stuff to start the row labeltext = t.get('label') stylename = t.get('stylename') stringel = t.find('./string') commentel = t.find('./comment') rtlsuffix = "R" if t.get('rtl') == 'True' else "" comment = commentel.text if commentel != None else None colBstyle = "Table1.A1" tbg = t.get( 'background' ) # get background attribute of test group (if one exists) if tbg == None: tbg = tgbg if tbg != None: # if background attribute for test element (or background attribute for testgroup element) if tbg not in colordic: # if color not found in color dic, create new style colorcount += 1 newname = basename + str(colorcount) colordic[tbg] = newname tb1style = Style(name=newname, family="table-cell") tb1style.addElement( TableCellProperties( attributes={ 'padding': "0.0382in", 'border': "0.05pt solid #000000", 'backgroundcolor': tbg })) LOdoc.automaticstyles.addElement(tb1style) colBstyle = colordic[tbg] row = TableRow() table.addElement(row) # fill cells # column A (label) cell = TableCell(stylename="Table1.A1", valuetype="string") if labeltext: cell.addElement( P(stylename="Table_20_Contents", text=labeltext)) row.addElement(cell) # column B (string) for n in range(numfonts): Pnum = ftmlstyles[stylename] if stylename != None else "P2" Pnum = Pnum + formattedfontnum[n] + rtlsuffix ### not clear if any of the following can be moved outside loop and reused cell = TableCell(stylename=colBstyle, valuetype="string") par = P(stylename=Pnum) if len(stringel) == 0: # no <em> subelements par.addText(re.sub(backu, hextounichr, stringel.text)) else: # handle <em> subelement(s) if stringel.text != None: par.addElement( Span(stylename="T1", text=re.sub(backu, hextounichr, stringel.text))) for e in stringel.findall("em"): if e.text != None: par.addText(re.sub(backu, hextounichr, e.text)) if e.tail != None: par.addElement( Span(stylename="T1", text=re.sub(backu, hextounichr, e.tail))) cell.addElement(par) row.addElement(cell) # column C (comment) cell = TableCell(stylename="Table1.A1", valuetype="string") if comment: cell.addElement(P(stylename="Table_20_Contents", text=comment)) row.addElement(cell) # column D (stylename) cell = TableCell(stylename="Table1.A1", valuetype="string") if comment: cell.addElement( P(stylename="Table_20_Contents", text=stylename)) row.addElement(cell) LOdoc.text.addElement(table) LOdoc.text.addElement(P(stylename="Subtitle", text="")) # Empty paragraph to end ### necessary? try: if fontstoembed: logfile.log("Embedding fonts in document", "V") for f in fontstoembed: LOdoc._extra.append( OpaqueObject( filename="Fonts/" + os.path.basename(f), mediatype= "application/x-font-ttf", ### should be "application/font-woff" or "/font-woff2" for WOFF fonts, "/font-opentype" for ttf content=io.open(f, "rb").read())) ci = ConfigItem(**{ 'name': 'EmbedFonts', 'type': 'boolean' }) ### (name = 'EmbedFonts', type = 'boolean') ci.addText('true') cis = ConfigItemSet(**{'name': 'ooo:configuration-settings' }) ### (name = 'ooo:configuration-settings') cis.addElement(ci) LOdoc.settings.addElement(cis) except: logfile.log("Error embedding fonts in document", "E") logfile.log("Writing output file: " + args.output, "P") LOdoc.save(unicode(args.output)) return
def create_odt0(self): propinsi = str(self.propinsi.GetValue()) kabupaten = str(self.kabupaten.GetValue()) kecamatan = str(self.kecamatan.GetValue()) desa = str(self.desa.GetValue()) alamat = str(self.alamat_kantor.GetValue()) telp = str(self.no_telp.GetValue()) kades = str(self.nama_kades.GetValue()) kode = str(self.nokode.GetValue()) camat = str(self.nama_camat.GetValue()) #perbesarhuruf kab = kabupaten.upper() kec = kecamatan.upper() des = desa.upper() textdoc = OpenDocumentText() a = P(text='PEMERINTAH KABUPATEN ' + (kab)) b = P(text='KECAMATAN ' + (kec)) c = P(text='DESA ' + (des)) d = P(text='Alamat ' + (alamat) + (telp)) e = P(text='No Kode Desa/Kelurahan ' + (kode)) f = P(text='Surat ') g = P(text='Nomor : ') h = P(text='Yang bertanda tangan dibawah ini, menerangkan bahwa : ') i = P(text='1. Nama :') j = P(text='2. Tempat & Tanggal Lahir :') k = P(text='3. Kewarganegaraan & Agama :') l = P(text='4. Pekerjaan :') m = P( text='5. Tempat Tinggal : RT.. RW.. Desa .. Kec. ... ' ) n = P(text=' Kabupaten : ..... Propinsi....') o = P(text='6. Surat Bukti Diri : KTP No.... KK No... ') p = P(text='7. Keperluan : ') q = P(text='8. Berlaku Mulai : Tgl s/d Selesai ') r = P( text= '9. Keterangan Lain-lain : Orang Tersebut benar-benar Penduduk Desa .... ' ) s = P(text='Demikian untuk menjadi malum bagi yang berkepentingan') t = P( text= ' Desa ............ ' ) u = P( text= 'Tanda Tangan Pemegang Mengetahui Kepala Desa... ' ) a1 = P(text='') a2 = P(text='') a3 = P(text='') a4 = P( text= '--------------------- Camat Kepala Desa ') textdoc.text.addElement(a) textdoc.text.addElement(b) textdoc.text.addElement(c) textdoc.text.addElement(d) textdoc.text.addElement(e) textdoc.text.addElement(f) textdoc.text.addElement(g) textdoc.text.addElement(h) textdoc.text.addElement(i) textdoc.text.addElement(j) textdoc.text.addElement(k) textdoc.text.addElement(l) textdoc.text.addElement(m) textdoc.text.addElement(n) textdoc.text.addElement(o) textdoc.text.addElement(p) textdoc.text.addElement(q) textdoc.text.addElement(r) textdoc.text.addElement(s) textdoc.text.addElement(t) textdoc.text.addElement(u) textdoc.text.addElement(a1) textdoc.text.addElement(a2) textdoc.text.addElement(a3) textdoc.save("/opt/sidesa/test", True)
def doit(args) : logfile = args.logger if args.report: logfile.loglevel = args.report try: root = ET.parse(args.input).getroot() except: logfile.log("Error parsing FTML input", "S") if args.font: # font(s) specified on command line fontlist = getfonts( args.font, logfile ) else: # get font spec from FTML fontsrc element fontlist = getfonts( [root.find("./head/fontsrc").text], logfile, False ) #fontlist = getfonts( [fs.text for fs in root.findall("./head/fontsrc")], False ) ### would allow multiple fontsrc elements numfonts = len(fontlist) if numfonts == 0: logfile.log("No font(s) specified", "S") if numfonts > 1: formattedfontnum = ["{0:02d}".format(n) for n in range(numfonts)] else: formattedfontnum = [""] logfile.log("Font(s) specified:", "V") for n, (fontname, bold, italic, embeddedfont) in enumerate(fontlist): logfile.log(" " + formattedfontnum[n] + " " + fontname + BoldItalic(bold, italic) + " " + str(embeddedfont), "V") # get optional fontscale; compute pointsize as int(12*fontscale/100). If result xx is not 12, then add "fo:font-size=xxpt" in Px styles pointsize = 12 fontscaleel = root.find("./head/fontscale") if fontscaleel != None: fontscale = fontscaleel.text try: pointsize = int(int(fontscale)*12/100) except ValueError: # any problem leaves pointsize 12 logfile.log("Problem with fontscale value; defaulting to 12 point", "W") # Get FTML styles and generate LO writer styles # P2 is paragraph style for string element when no features specified # each Px (for P3...) corresponds to an FTML style, which specifies lang or feats or both # if numfonts > 1, two-digit font number is appended to make an LO writer style for each FTML style + font combo # When LO writer style is used with attribute rtl="True", "R" appended to style name LOstyles = {} ftmlstyles = {} Pstylenum = 2 LOstyles["P2"] = ("", None, None) ftmlstyles[0] = "P2" for s in root.findall("./head/styles/style"): Pstylenum += 1 Pnum = "P" + str(Pstylenum) featstring = "" if s.get('feats'): featstring = parsefeats(s.get('feats')) langname = None countryname = None lang = s.get('lang') if lang != None: x = re.match(langcode, lang) langname = x.group('langname') countryname = x.group('countryname') # FTML <test> element @stylename attribute references this <style> element @name attribute ftmlstyles[s.get('name')] = Pnum LOstyles[Pnum] = (featstring, langname, countryname) # create LOwriter file and construct styles for tables, column widths, etc. LOdoc = OpenDocumentText() init(LOdoc, numfonts) # Initialize sequence counters sds = SequenceDecls() sd = sds.addElement(SequenceDecl(displayoutlinelevel = '0', name = 'Illustration')) sd = sds.addElement(SequenceDecl(displayoutlinelevel = '0', name = 'Table')) sd = sds.addElement(SequenceDecl(displayoutlinelevel = '0', name = 'Text')) sd = sds.addElement(SequenceDecl(displayoutlinelevel = '0', name = 'Drawing')) LOdoc.text.addElement(sds) # Create Px style for each (featstring, langname, countryname) tuple in LOstyles # and for each font (if >1 font, append to Px style name a two-digit number corresponding to the font in fontlist) # and (if at least one rtl attribute) suffix of nothing or "R" # At the same time, collect info for creating FontFace elements (and any embedded fonts) suffixlist = ["", "R"] if root.find(".//test/[@rtl='True']") != None else [""] fontfaces = {} for p in sorted(LOstyles, key = lambda x : int(x[1:])): # key = lambda x : int(x[1:]) corrects sort order featstring, langname, countryname = LOstyles[p] for n, (fontname, bold, italic, embeddedfont) in enumerate(fontlist): # embeddedfont = None if no embedding needed fontnum = formattedfontnum[n] # Collect fontface info: need one for each font family + feature combination # Put embedded font in list only under fontname with empty featstring if (fontname, featstring) not in fontfaces: fontfaces[ (fontname, featstring) ] = [] if embeddedfont: if (fontname, "") not in fontfaces: fontfaces[ (fontname, "") ] = [] if embeddedfont not in fontfaces[ (fontname, "") ]: fontfaces[ (fontname, "") ].append(embeddedfont) # Generate paragraph styles for s in suffixlist: pstyle = Style(name=p+fontnum+s, family="paragraph") if s == "R": pstyle.addElement(ParagraphProperties(textalign="end", justifysingleword="false", writingmode="rl-tb")) pstyledic = {} pstyledic['fontnamecomplex'] = \ pstyledic['fontnameasian'] =\ pstyledic['fontname'] = fontname + featstring pstyledic['fontsizecomplex'] = \ pstyledic['fontsizeasian'] = \ pstyledic['fontsize'] = str(pointsize) + "pt" if bold: pstyledic['fontweightcomplex'] = \ pstyledic['fontweightasian'] = \ pstyledic['fontweight'] = 'bold' if italic: pstyledic['fontstylecomplex'] = \ pstyledic['fontstyleasian'] = \ pstyledic['fontstyle'] = 'italic' if langname != None: pstyledic['languagecomplex'] = \ pstyledic['languageasian'] = \ pstyledic['language'] = langname if countryname != None: pstyledic['countrycomplex'] = \ pstyledic['countryasian'] = \ pstyledic['country'] = countryname pstyle.addElement(TextProperties(attributes=pstyledic)) # LOdoc.styles.addElement(pstyle) ### tried this, but when saving the generated odt, LO changed them to automatic styles LOdoc.automaticstyles.addElement(pstyle) fontstoembed = [] for fontname, featstring in sorted(fontfaces): ### Or find a way to keep order of <style> elements from original FTML? ff = FontFace(name=fontname + featstring, fontfamily=fontname + featstring, fontpitch="variable") LOdoc.fontfacedecls.addElement(ff) if fontfaces[ (fontname, featstring) ]: # embedding needed for this combination for fontfile in fontfaces[ (fontname, featstring) ]: fontstoembed.append(fontfile) # make list for embedding ffsrc = FontFaceSrc() ffuri = FontFaceUri( **{'href': "Fonts/" + os.path.basename(fontfile), 'type': "simple"} ) ffformat = FontFaceFormat( **{'string': 'truetype'} ) ff.addElement(ffsrc) ffsrc.addElement(ffuri) ffuri.addElement(ffformat) basename = "Table1.B" colorcount = 0 colordic = {} # record color #rrggbb as key and "Table1.Bx" as stylename (where x is current color count) tablenum = 0 # get title and comment and use as title and subtitle titleel = root.find("./head/title") if titleel != None: LOdoc.text.addElement(H(outlinelevel=1, stylename="Title", text=titleel.text)) commentel = root.find("./head/comment") if commentel != None: LOdoc.text.addElement(P(stylename="Subtitle", text=commentel.text)) # Each testgroup element begins a new table for tg in root.findall("./testgroup"): # insert label attribute of testgroup element as subtitle tglabel = tg.get('label') if tglabel != None: LOdoc.text.addElement(H(outlinelevel=1, stylename="Subtitle", text=tglabel)) # insert text from comment subelement of testgroup element tgcommentel = tg.find("./comment") if tgcommentel != None: #print("commentel found") LOdoc.text.addElement(P(text=tgcommentel.text)) tgbg = tg.get('background') # background attribute of testgroup element tablenum += 1 table = Table(name="Table" + str(tablenum), stylename="Table1") table.addElement(TableColumn(stylename="Table1.A")) for n in range(numfonts): table.addElement(TableColumn(stylename="Table1.B")) table.addElement(TableColumn(stylename="Table1.A")) table.addElement(TableColumn(stylename="Table1.D")) for t in tg.findall("./test"): # Each test element begins a new row # stuff to start the row labeltext = t.get('label') stylename = t.get('stylename') stringel = t.find('./string') commentel = t.find('./comment') rtlsuffix = "R" if t.get('rtl') == 'True' else "" comment = commentel.text if commentel != None else None colBstyle = "Table1.A1" tbg = t.get('background') # get background attribute of test group (if one exists) if tbg == None: tbg = tgbg if tbg != None: # if background attribute for test element (or background attribute for testgroup element) if tbg not in colordic: # if color not found in color dic, create new style colorcount += 1 newname = basename + str(colorcount) colordic[tbg] = newname tb1style = Style(name=newname, family="table-cell") tb1style.addElement(TableCellProperties(attributes={'padding':"0.0382in", 'border':"0.05pt solid #000000", 'backgroundcolor':tbg})) LOdoc.automaticstyles.addElement(tb1style) colBstyle = colordic[tbg] row = TableRow() table.addElement(row) # fill cells # column A (label) cell = TableCell(stylename="Table1.A1", valuetype="string") if labeltext: cell.addElement(P(stylename="Table_20_Contents", text = labeltext)) row.addElement(cell) # column B (string) for n in range(numfonts): Pnum = ftmlstyles[stylename] if stylename != None else "P2" Pnum = Pnum + formattedfontnum[n] + rtlsuffix ### not clear if any of the following can be moved outside loop and reused cell = TableCell(stylename=colBstyle, valuetype="string") par = P(stylename=Pnum) if len(stringel) == 0: # no <em> subelements par.addText(re.sub(backu, hextounichr, stringel.text)) else: # handle <em> subelement(s) if stringel.text != None: par.addElement(Span(stylename="T1", text = re.sub(backu, hextounichr, stringel.text))) for e in stringel.findall("em"): if e.text != None: par.addText(re.sub(backu, hextounichr, e.text)) if e.tail != None: par.addElement(Span(stylename="T1", text = re.sub(backu, hextounichr, e.tail))) cell.addElement(par) row.addElement(cell) # column C (comment) cell = TableCell(stylename="Table1.A1", valuetype="string") if comment: cell.addElement(P(stylename="Table_20_Contents", text = comment)) row.addElement(cell) # column D (stylename) cell = TableCell(stylename="Table1.A1", valuetype="string") if comment: cell.addElement(P(stylename="Table_20_Contents", text = stylename)) row.addElement(cell) LOdoc.text.addElement(table) LOdoc.text.addElement(P(stylename="Subtitle", text="")) # Empty paragraph to end ### necessary? try: if fontstoembed: logfile.log("Embedding fonts in document", "V") for f in fontstoembed: LOdoc._extra.append( OpaqueObject(filename = "Fonts/" + os.path.basename(f), mediatype = "application/x-font-ttf", ### should be "application/font-woff" or "/font-woff2" for WOFF fonts, "/font-opentype" for ttf content = io.open(f, "rb").read() )) ci = ConfigItem(**{'name':'EmbedFonts', 'type': 'boolean'}) ### (name = 'EmbedFonts', type = 'boolean') ci.addText('true') cis=ConfigItemSet(**{'name':'ooo:configuration-settings'}) ### (name = 'ooo:configuration-settings') cis.addElement(ci) LOdoc.settings.addElement(cis) except: logfile.log("Error embedding fonts in document", "E") logfile.log("Writing output file: " + args.output, "P") LOdoc.save(unicode(args.output)) return
def odtwrite(data, dictwire, savepath, plot_flag = True): def ent(h,n): for k in range(0,n,1): lb = LineBreak() h.addElement(lb) return h def headerwire(): h = H(outlinelevel=1, stylename=h1style) ent(h,13) h.addText(text = wire) ent(h,12) return h def ttb(style, intext): tc = TableCell() p = P(stylename = style, text = intext) tc.addElement(p) return tc def picprint(num): picref = textdoc.addPictureFromFile(data[num].picpath) fftpicref = textdoc.addPictureFromFile(data[num].fftpicpath) pf = Frame(width="8cm", height="6cm", x="0cm", y="0cm") pf2 = Frame(width="8cm", height="6cm", x="10cm", y="0cm") p = P(stylename=picturetext) pf.addElement(Image(href = picref)) pf2.addElement(Image(href = fftpicref)) p.addElement(pf) p.addElement(pf2) ent(p,1) p.addText(u"Рис." + str(picnum) + u' ' + data[num].params['measure'] + u" от времени и его амплитудно-частотная характеристика" ) ent(p,1) return p def pictable(num): table = Table() table.addElement(TableColumn(numbercolumnsrepeated=2,stylename=tablestyle)) for word in data[num].params.keys(): if word in transword and data[num].params[word] != None: tr = TableRow() tr.addElement(ttb(tabletext, transword[word])) tr.addElement(ttb(tabletext, data[num].params[word])) table.addElement(tr) return table def sumtable(): ad = {u"Напряжение" : u' (В)', u"Ток" : u' (А)', u"Мощность" : u' (Вт/c)'} table = Table() table.addElement(TableColumn(numbercolumnsrepeated = len(ampl)+1, stylename = tablestyle)) tr = TableRow() tc = TableCell() tr.addElement(tc) for a in ampl: tr.addElement(ttb(tabletextbold, a)) table.addElement(tr) for antenna in sorted(dictwire[wire].keys()): tr = TableRow() tr.addElement(ttb(tabletextbold, antenna)) table.addElement(tr) for port in sorted(dictwire[wire][antenna].keys()): for m in [u"Напряжение", u"Ток", u"Мощность"]: tr = TableRow() tr.addElement(ttb(tabletextbold, m+ad[m])) if port is not None: tr.addElement(ttb(tabletextbold, port)) table.addElement(tr) for rg in sorted(dictwire[wire][antenna][port].keys()): for k in dictwire[wire][antenna][port][rg].keys(): if k != None: b = sorted(dictwire[wire][antenna][port][rg].keys(), key = len) else: b = dictwire[wire][antenna][port][rg].keys() for distance in b: tr = TableRow() tc = TableCell() try: p = P(text = distance + ', ' + rg) except: p = P(text = rg) tc.addElement(p) tr.addElement(tc) for amplitude in ampl: try: if m == u"Мощность": a = data[dictwire[wire][antenna][port][rg][distance][amplitude][u"Напряжение"]] amu = a.energy((0,len(a.xvalue)), bytime = True) amu = '{0:.03e}'.format(amu) wiretype = a.params['wiretype'] else: a = data[dictwire[wire][antenna][port][rg][distance][amplitude][m]] amu = a.max() amu = '{0:.03f}'.format(amu) wiretype = a.params['wiretype'] except KeyError: amu = u'--' tr.addElement(ttb(tabletext, amu)) table.addElement(tr) return [table, wiretype] for wire in sorted(dictwire.keys()): picnum = 1 transword = {'wire':u'Кабель', 'antenna':u'Антенна', 'port':u'Порт', 'distance':u'Дальность', 'range':u'Расстояние'} ampl = [u'9кВ', u'12кВ', u'15кВ', u'18кВ', u'20кВ'] textdoc = OpenDocumentText() h1style = Style(name = "Heading 1", family = "paragraph") h1style.addElement(TextProperties(attributes = {'fontfamily':"Times New Roman", 'fontsize':"24pt",'fontweight':"bold"})) h1style.addElement(ParagraphProperties(attributes = {'textalign':"center"})) textdoc.styles.addElement(h1style) t1style = Style(name = "Text 1", family = "paragraph") t1style.addElement(TextProperties(attributes = {'fontfamily':"Times New Roman", 'fontsize':"14pt"})) textdoc.styles.addElement(t1style) prepicturetext = Style(name = "Pre Picture Text", family = "paragraph") prepicturetext.addElement(TextProperties(attributes = {'fontfamily':"Times New Roman", 'fontsize':"12pt",'fontstyle':"italic"})) prepicturetext.addElement(ParagraphProperties(attributes = {'textalign':"right"})) textdoc.styles.addElement(prepicturetext) picturetext = Style(name = "Picture Text", family = "paragraph") picturetext.addElement(TextProperties(attributes = {'fontfamily':"Times New Roman", 'fontsize':"10pt",'fontstyle':"italic"})) picturetext.addElement(ParagraphProperties(attributes = {'textalign':"center"})) textdoc.styles.addElement(picturetext) tabletextbold = Style(name = "Table Text 2", family = "paragraph") tabletextbold.addElement(TextProperties(attributes = {'fontfamily':"Times New Roman", 'fontsize':"14pt", 'fontweight':"bold"})) tabletextbold.addElement(ParagraphProperties(numberlines = "false", linenumber = "0")) textdoc.styles.addElement(tabletextbold) tabletext = Style(name = "Table Text", family = "paragraph") tabletext.addElement(TextProperties(attributes = {'fontfamily':"Times New Roman", 'fontsize':"12pt"})) tabletext.addElement(ParagraphProperties(numberlines = "false", linenumber = "0")) textdoc.styles.addElement(tabletext) tablestyle = Style(name = "Table", family = "table-column") textdoc.automaticstyles.addElement(tablestyle) textdoc.text.addElement(headerwire()) [st,wiretype] = sumtable() textdoc.text.addElement(st) p = P(stylename=picturetext) textdoc.text.addElement(p) if plot_flag == True: # amplitude = u'20кВ' for antenna in sorted(dictwire[wire].keys()): for port in sorted(dictwire[wire][antenna].keys()): maxnum = {} for rg in sorted(dictwire[wire][antenna][port].keys()): for distance in sorted(dictwire[wire][antenna][port][rg].keys()): num = [] for amplitude in sorted(dictwire[wire][antenna][port][rg][distance].keys()): for units in sorted(dictwire[wire][antenna][port][rg][distance][amplitude].keys()): num.append(dictwire[wire][antenna][port][rg][distance][amplitude][units]) maxnum[data[num[0]].max()] = num mn = maxnum[numpy.max(maxnum.keys())] textdoc.text.addElement(pictable(mn[0])) p = P(stylename=picturetext) textdoc.text.addElement(p) for num in mn: textdoc.text.addElement(picprint(num)) picnum += 1 sp = savepath + os.sep + wiretype if not os.path.exists(sp): os.mkdir(sp) textdoc.save(sp + os.sep + wire, True)
""" <text:h text:outline-level="1">An Image</text:h> <text:p> <draw:frame draw:name="graphics1" text:anchor-type="paragraph" svg:width="5in" svg:height="6.6665in" draw:z-index="0"> <draw:image xlink:href="Pictures/campanile_fog.jpg" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad"/> </draw:frame> </text:p> """ textdoc.text.addElement(H(outlinelevel=1,text='An Image')) p = P() textdoc.text.addElement(p) # add the image # img_path is the local path of the image to include ##img_path = r'C:\Users\Utilisateur\Documents\GitHub\python_planning\PHOTOS 028.jpg' ###img_path = 'D:\Document\PersonalInfoRemixBook\examples\ch17\campanile_fog.jpg' ##href = textdoc.addPicture(img_path) ##f = Frame(name="graphics1", anchortype="paragraph", width="5in", height="6.6665in", ##zindex="0") ##p.addElement(f) ###img = Image(href=href, type="simple", show="embed", actuate="onLoad") ###f.addElement(img) # save the document textdoc.save(fname)
listStyle = easyliststyle.styleFromString('bullet1', bulletListSpec, ',', '0.6cm', easyliststyle.SHOW_ONE_LEVEL) s.addElement(listStyle) listElement = createList(itemList, '>', 'bullet1') textdoc.text.addElement(listElement) para = P(text="-----------------------"); textdoc.text.addElement(para) listStyle = easyliststyle.styleFromList('num1', numberListSpecArray, '0.25in', easyliststyle.SHOW_ALL_LEVELS) s.addElement(listStyle) listElement = createList(itemList, '>', 'num1') textdoc.text.addElement(listElement) para = P(text="-----------------------"); textdoc.text.addElement(para) listStyle = easyliststyle.styleFromString('mix1', mixedListSpec, '!', '0.8cm', easyliststyle.SHOW_ONE_LEVEL) s.addElement(listStyle) listElement = createList(itemList, '>', 'mix1') textdoc.text.addElement(listElement) textdoc.save("easylist_odfpy.odt") # vim: set expandtab sw=4 :
'D': ['Batx.2H', 'Batx.2I'] } }) courses = [ '1 ESO', '2 ESO', '2º PMAR', '3 ESO', '3º PMAR', '4 ESO', '1º Bach.', '2º Bach.' ] #courses = ['2º Bach.'] for k in courses: coursePage(k, coursegroups[k], lang) title = H(stylename=h1style, text="Promoción", outlinelevel=1) textdoc.text.addElement(title) for k in courses: p = P() textdoc.text.addElement(p) img_path = path + k + "-allgroupsprom.png" href = textdoc.addPicture(img_path) f = Frame(name=k, anchortype="paragraph", width="17cm", height="7.5cm", zindex="0") p.addElement(f) img = Image(href=href, type="simple", show="embed", actuate="onLoad") f.addElement(img) textdoc.save(period + year + "/report-" + period + year + "-" + lang + ".odt")
class OdtGenerator(DocumentGenerator): 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 addText(self, data_box): text = data_box.getText() frame_style = Style(name="FrameStyle", family="graphic") debug("Angle: ", 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 addImage(self, data_box): format = "PNG" image_file = tempfile.mkstemp(suffix="." + format)[1] data_box.image.save(image_file, format=format) x, y, width, height = data_box.getBoundsPrintSize(self.current_page_resolution) photo_frame = Frame( stylename=self.photo_style, x="%sin" % x, y="%sin" % y, width="%sin" % width, height="%sin" % height, anchortype="paragraph", ) self.current_page.addElement(photo_frame) location = self.document.addPicture(image_file) photo_frame.addElement(Image(href=location)) self.temp_images.append(image_file) 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 addPage(self, page_data): self.current_page = self.newPage(page_data) self.current_page_resolution = page_data.resolution self.addBoxes(page_data.data_boxes) def save(self): name = self.name if not name.lower().endswith(".odt"): name += ".odt" self.document.save(name) for image in self.temp_images: try: os.unlink(image) except: debug("Error removing image: %s" % image) def __handlePageMaster(self, page_data): layout_name = "Page%s%s" % (page_data.width, page_data.height) if not layout_name in self.page_layouts: page_layout = PageLayout(name=layout_name) page_layout.addElement( PageLayoutProperties( margintop="0in", marginbottom="0in", marginleft="0in", marginright="0in", pagewidth="%sin" % page_data.width, pageheight="%sin" % page_data.height, ) ) self.document.automaticstyles.addElement(page_layout) self.page_layouts.append(layout_name) master_name = layout_name + "Master" if not master_name in self.page_masters: master_page = MasterPage(name=master_name, pagelayoutname=layout_name) self.document.masterstyles.addElement(master_page) self.page_masters.append(master_name) return master_name def __handleFrameStyle(self, text_data): style_name = "box%s%s%s%s%s" % ( 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.styles.addElement(frame_style) self.font_styles.append(style_name) return style_name 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 convertFontStyle(self, style): if style == STYLE_OBLIQUE: return "oblique" elif style == STYLE_ITALIC: return "italic" return "normal" def convertFontWeight(self, weight): if weight == WEIGHT_BOLD: return "bold" return "normal"
usage() sys.exit(2) inputfile = args[0] if outputfile is None: outputfile = inputfile[:inputfile.rfind('.')] + ".odt" spreadsheetdoc = load(inputfile) textdoc = OpenDocumentText() # Need to make a copy of the list because addElement unlinks from the original for meta in spreadsheetdoc.meta.childNodes[:]: textdoc.meta.addElement(meta) for font in spreadsheetdoc.fontfacedecls.childNodes[:]: textdoc.fontfacedecls.addElement(font) for style in spreadsheetdoc.styles.childNodes[:]: textdoc.styles.addElement(style) for autostyle in spreadsheetdoc.automaticstyles.childNodes[:]: textdoc.automaticstyles.addElement(autostyle) for sheet in spreadsheetdoc.getElementsByType(Table): textdoc.text.addElement(sheet) textdoc.text.addElement(P()) textdoc.Pictures = spreadsheetdoc.Pictures textdoc.save(outputfile)
elif allowed_attrs is (): info = "No attribute is allowed" else: allowed_args = [a[1].lower().replace("-", "") for a in allowed_attrs] allowed_args.sort() info = ", ".join(allowed_args) p.addElement(text.Span(stylename=attrliststyle, text=info)) p.addText(".") section.addElement(p) # PARENTS p = text.P(text="These elements contain %s: " % classname) i = text.Span(stylename=elmliststyle) p.addElement(i) listofelements(i, parents.get(element), "This is a toplevel element", "This is a toplevel element") section.addElement(p) # CHILDREN p = text.P(text="The following elements occur in %s: " % classname) i = text.Span(stylename=elmliststyle) p.addElement(i) listofelements(i, children, "Any element is allowed", "No element is allowed") section.addElement(p) # boldpart = text.Span(stylename="Bold",text="This part is bold. ") # p.addElement(boldpart) # p.addText("This is after bold.") # print d.contentxml() doc.save("manual.odt")