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 __init__(self, env=None, status_callback=None, language="en", namespace="en.wikipedia.org", creator="", license="GFDL"): self.env = env self.status_callback = status_callback self.language = language self.namespace = namespace self.references = [] self.doc = OpenDocumentText() style.applyStylesToDoc(self.doc) self.text = self.doc.text self.namedLinkCount = 0 self.conf = odfconf.OdfConf if creator: self.doc.meta.addElement(meta.InitialCreator(text=creator)) self.doc.meta.addElement(dc.Creator(text=creator)) if language is not None: self.doc.meta.addElement(dc.Language(text=language)) if license is not None: self.doc.meta.addElement( meta.UserDefined(name="Rights", text=license))
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())
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 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 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 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_style(self): """ Get an automatic style with getStyleByName """ textdoc = OpenDocumentText() boldstyle = style.Style(name='Bold', family="text") boldstyle.addElement(style.TextProperties(fontweight="bold")) textdoc.automaticstyles.addElement(boldstyle) s = textdoc.getStyleByName('Bold') self.assertEquals((u'urn:oasis:names:tc:opendocument:xmlns:style:1.0', 'style'), s.qname)
def test_style(self): """ Get a common style with getStyleByName """ textdoc = OpenDocumentText() tablecontents = style.Style(name=u"Table Contents", family=u"paragraph") tablecontents.addElement(style.ParagraphProperties(numberlines=u"false", linenumber=u"0")) textdoc.styles.addElement(tablecontents) s = textdoc.getStyleByName(u'Table Contents') self.assertEqual((u'urn:oasis:names:tc:opendocument:xmlns:style:1.0', 'style'), s.qname)
def test_style(self): """ Get an automatic style with getStyleByName """ textdoc = OpenDocumentText() boldstyle = style.Style(name=u'Bold', family=u"text") boldstyle.addElement(style.TextProperties(fontweight=u"bold")) textdoc.automaticstyles.addElement(boldstyle) s = textdoc.getStyleByName(u'Bold') self.assertEqual((u'urn:oasis:names:tc:opendocument:xmlns:style:1.0', 'style'), s.qname)
def test_style(self): """ Get a common style with getStyleByName """ textdoc = OpenDocumentText() tablecontents = style.Style(name="Table Contents", family="paragraph") tablecontents.addElement(style.ParagraphProperties(numberlines="false", linenumber="0")) textdoc.styles.addElement(tablecontents) s = textdoc.getStyleByName('Table Contents') self.assertEquals((u'urn:oasis:names:tc:opendocument:xmlns:style:1.0', 'style'), s.qname)
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 testAddPicture(self): """ Check that AddPicture works""" THUMBNAILNAME = "thumbnail.png" icon = thumbnail.thumbnail() f = open(THUMBNAILNAME, "wb") f.write(icon) f.close() textdoc = OpenDocumentText() textdoc.addPicture(THUMBNAILNAME) os.unlink(THUMBNAILNAME)
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 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 write_odt(text: str) -> BytesIO: """Функция создания odt документа и записи в него данного текста, после чего документ возвращается байтовый поток документа""" textdoc = OpenDocumentText() paragraph_element = P() teletype.addTextToElement(paragraph_element, text) textdoc.text.addElement(paragraph_element, text) target_stream = BytesIO() textdoc.write(target_stream) target_stream.seek(0) return target_stream
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 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")
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>"""))
def testAttributeForeign(self): """ Test that you can add foreign attributes """ textdoc = OpenDocumentText() standard = style.Style(name="Standard", family="paragraph") p = style.ParagraphProperties(qattributes={(u'http://foreignuri.com',u'enable-numbering'):'true'}) standard.addElement(p) textdoc.styles.addElement(standard) s = unicode(textdoc.stylesxml(),'UTF-8') s.index(u"""<?xml version='1.0' encoding='UTF-8'?>\n""") s.index(u'xmlns:ns30="http://foreignuri.com"') s.index(u'<style:paragraph-properties ns30:enable-numbering="true"/>') s.index(u'<office:styles><style:style style:name="Standard" style:display-name="Standard" style:family="paragraph">')
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 test_list(self): textdoc = OpenDocumentText() s = textdoc.styles listStyle = easyliststyle.styleFromString(u'bullet1', bulletListSpec, u',', u'0.6cm', easyliststyle.SHOW_ONE_LEVEL) s.addElement(listStyle) result = textdoc.stylesxml() self.assertNotEqual(-1, result.find(u'''style:name="bullet1"''')) self.assertNotEqual(-1, result.find(u'''text:bullet-char="*"''')) self.assertNotEqual(-1, result.find(u'''text:level="1"''')) self.assertNotEqual(-1, result.find(u'''style:list-level-properties''')) #<text:list-style style:name="bullet1" style:display-name="bullet1"> #<text:list-level-style-bullet text:bullet-char="*" text:level="1"> #<style:list-level-properties text:min-label-width="0.6cm" text:space-before="0.6cm"/> #</text:list-level-style-bullet> #<text:list-level-style-bullet text:bullet-char=">" text:level="2"> #<style:list-level-properties text:min-label-width="0.6cm" text:space-before="1.2cm"/> #</text:list-level-style-bullet> #<text:list-level-style-bullet text:bullet-char="#" text:level="3"> #<style:list-level-properties text:min-label-width="0.6cm" text:space-before="1.8cm"/> #</text:list-level-style-bullet> #<text:list-level-style-bullet text:bullet-char="%" text:level="4"> #<style:list-level-properties text:min-label-width="0.6cm" text:space-before="2.4cm"/> listElement = self.createList(itemList, u'>', u'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 = self.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 = self.createList(itemList, '>', 'mix1') textdoc.text.addElement(listElement)
def export_to_odt(self, data): document = OpenDocumentText() # Styles s = document.styles h1style = Style(name="Heading 1", family="paragraph") h1style.addElement( TextProperties(attributes={ 'fontsize': "24pt", 'fontweight': "bold" })) s.addElement(h1style) h2style = Style(name="Heading 2", family="paragraph") h2style.addElement( TextProperties(attributes={ 'fontsize': "16pt", 'fontweight': "bold" })) s.addElement(h2style) h3style = Style(name="Heading 3", family="paragraph") h3style.addElement( TextProperties(attributes={ 'fontsize': "12pt", 'fontweight': "bold" })) s.addElement(h3style) h4style = Style(name="Heading 4", family="paragraph") h4style.addElement(TextProperties(attributes={'fontsize': "8pt"})) s.addElement(h4style) # Text h = H(outlinelevel=1, stylename=h1style, text="Data of AtmoStation") document.text.addElement(h) h = H(outlinelevel=1, stylename=h2style, text=str(datetime.datetime.now())) document.text.addElement(h) for k, v in data.items(): h = H(outlinelevel=1, stylename=h2style, text=k) document.text.addElement(h) for v1 in v: h = H(outlinelevel=2, stylename=h3style, text="Item") document.text.addElement(h) for v2 in v1: h = H(outlinelevel=3, stylename=h4style, text=str(v2) + ": " + str(v1[v2])) document.text.addElement(h) document.save('templates\\formated_data\\data.odt')
def test_write(self): """ document's write method """ outfp = io.BytesIO() textdoc = OpenDocumentText() p = P(text=u"Æblegrød") p.addText(u' Blåbærgrød') textdoc.text.addElement(p) textdoc.write(outfp) outfp.seek(0) # outfp now contains the document. z = zipfile.ZipFile(outfp, "r") self.assertEqual(None, z.testzip()) outfp.close()
def test_write(self): """ document's write method """ outfp = cStringIO.StringIO() textdoc = OpenDocumentText() p = P(text=u"Æblegrød") p.addText(u' Blåbærgrød') textdoc.text.addElement(p) textdoc.write(outfp) outfp.seek(0) # outfp now contains the document. z = zipfile.ZipFile(outfp,"r") self.assertEqual(None, z.testzip()) outfp.close()
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/>')
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"'))
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 __init__(self, filename): self.filename = filename self.doc = OpenDocumentText() # font self.doc.fontfacedecls.addElement((FontFace(name="Arial", fontfamily="Arial", fontsize="10", fontpitch="variable", fontfamilygeneric="swiss"))) # styles style_standard = Style(name="Standard", family="paragraph", attributes={"class": "text"}) style_standard.addElement( ParagraphProperties(punctuationwrap="hanging", writingmode="page", linebreak="strict")) style_standard.addElement(TextProperties(fontname="Arial", fontsize="10pt", fontsizecomplex="10pt", fontsizeasian="10pt")) self.doc.styles.addElement(style_standard) # automatic styles style_normal = Style(name="ResumeText", parentstylename="Standard", family="paragraph") self.doc.automaticstyles.addElement(style_normal) style_bold_text = Style( name="ResumeBoldText", parentstylename="Standard", family="text") style_bold_text.addElement(TextProperties(fontweight="bold", fontweightasian="bold", fontweightcomplex="bold")) self.doc.automaticstyles.addElement(style_bold_text) style_list_text = ListStyle(name="ResumeListText") style_list_bullet = ListLevelStyleBullet(level="1", stylename="ResumeListTextBullet", numsuffix=".", bulletchar=u'\u2022') style_list_bullet.addElement(ListLevelProperties(spacebefore="0.1in", minlabelwidth="0.2in")) style_list_text.addElement(style_list_bullet) self.doc.automaticstyles.addElement(style_list_text) style_bold_para = Style(name="ResumeH2", parentstylename="Standard", family="paragraph") style_bold_para.addElement(TextProperties(fontweight="bold", fontweightasian="bold", fontweightcomplex="bold")) self.doc.automaticstyles.addElement(style_bold_para) style_bold_center = Style(name="ResumeH1", parentstylename="Standard", family="paragraph") style_bold_center.addElement(TextProperties(fontweight="bold", fontweightasian="bold", fontweightcomplex="bold")) style_bold_center.addElement(ParagraphProperties(textalign="center")) self.doc.automaticstyles.addElement(style_bold_center)
def test_simple_link(self): """ Create a link """ textdoc = OpenDocumentText() para = text.P() anchor = text.A(href="http://www.com/", type="simple", text="A link label") para.addElement(anchor) textdoc.text.addElement(para)
def __init__(self, strMode): """ Initialise highlighter: strMode = language (PYTHON, C, CPP, PHP, HTML) """ self.textdoc = OpenDocumentText() self.textdoc.fontfacedecls.addElement(self.courierfont) self.textdoc.styles.addElement(self.programliststyle) self.textdoc.styles.addElement(self.puncstyle) self.textdoc.styles.addElement(self.numberstyle) self.textdoc.styles.addElement(self.keywordstyle) self.textdoc.styles.addElement(self.variablestyle) self.textdoc.styles.addElement(self.tagstyle) self.textdoc.styles.addElement(self.attrstyle) self.textdoc.styles.addElement(self.stringstyle) self.textdoc.styles.addElement(self.commentstyle) self.textdoc.styles.addElement(self.preprocstyle) self.strSpanStyle = None self.currPara = P(stylename=self.programliststyle) self.textdoc.text.addElement(self.currPara) self.currSpan = None if strMode == 'CPP': strMode = 'C' self.strSuppressTokens = [] elif strMode == 'C': self.strSuppressTokens = ['CPPKEYWORD'] else: self.strSuppressTokens = [] self.strMode = strMode
def test_topnode(self): """ Check that topnode is correct """ textdoc = OpenDocumentText() self.assertEqual(8, len(textdoc.topnode.childNodes)) self.assertEqual(textdoc, textdoc.topnode.ownerDocument) self.assertEqual(textdoc, textdoc.styles.ownerDocument) self.assertEqual(textdoc, textdoc.settings.ownerDocument)
def __init__( self, template=None ): if not template: self.doc = OpenDocumentText() else: self.doc = load( template ) self.cur_par = None self._create_styles()
def testMasterWithHeader(self): """ Create a text document with a page layout called "pagelayout" Add a master page Check that pagelayout is listed in styles.xml """ textdoc = OpenDocumentText() pl = style.PageLayout(name="pagelayout") textdoc.automaticstyles.addElement(pl) mp = style.MasterPage(name="Standard", pagelayoutname=pl) textdoc.masterstyles.addElement(mp) h = style.Header() hp = text.P(text="header try") h.addElement(hp) mp.addElement(h) s = unicode(textdoc.stylesxml(),'UTF-8') self.assertContains(s, u'<office:automatic-styles><style:page-layout style:name="pagelayout"/></office:automatic-styles>')
def create_doc(self): doc = OpenDocumentText() # Page layout: A4 pagelayout = PageLayout(name="A4") doc.automaticstyles.addElement(pagelayout) pagelayout.addElement( PageLayoutProperties(margin="2cm", pageheight="297mm", pagewidth="210mm", printorientation="portrait")) # Use page layout on master page, to set it: masterpage = MasterPage(name="Standard", pagelayoutname="A4") doc.masterstyles.addElement(masterpage) # Styles s = doc.styles self.h1style = Style(name="Heading 1", family="paragraph") self.h1style.addElement( TextProperties(attributes={ 'fontsize': "24pt", 'fontweight': "bold" })) s.addElement(self.h1style) return doc
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 test_list(self): textdoc = OpenDocumentText() s = textdoc.styles listStyle = easyliststyle.styleFromString(u'bullet1', bulletListSpec, u',', u'0.6cm', easyliststyle.SHOW_ONE_LEVEL) s.addElement(listStyle) result = textdoc.stylesxml() self.assertNotEqual(-1, result.find(u'''style:name="bullet1"''')) self.assertNotEqual(-1, result.find(u'''text:bullet-char="*"''')) self.assertNotEqual(-1, result.find(u'''text:level="1"''')) self.assertNotEqual(-1, result.find(u'''style:list-level-properties''')) #<text:list-style style:name="bullet1" style:display-name="bullet1"> #<text:list-level-style-bullet text:bullet-char="*" text:level="1"> #<style:list-level-properties text:min-label-width="0.6cm" text:space-before="0.6cm"/> #</text:list-level-style-bullet> #<text:list-level-style-bullet text:bullet-char=">" text:level="2"> #<style:list-level-properties text:min-label-width="0.6cm" text:space-before="1.2cm"/> #</text:list-level-style-bullet> #<text:list-level-style-bullet text:bullet-char="#" text:level="3"> #<style:list-level-properties text:min-label-width="0.6cm" text:space-before="1.8cm"/> #</text:list-level-style-bullet> #<text:list-level-style-bullet text:bullet-char="%" text:level="4"> #<style:list-level-properties text:min-label-width="0.6cm" text:space-before="2.4cm"/> listElement = self.createList(itemList, u'>', u'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 = self.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 = self.createList(itemList, '>', 'mix1') textdoc.text.addElement(listElement)
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)
def testAutomaticStyles(self): """ Create a text document with a page layout called "pagelayout" Add a master page Add an automatic style for the heading Check that pagelayout is listed in styles.xml under automatic-styles Check that the heading style is NOT listed in styles.xml Check that the pagelayout is NOT listed in content.xml """ textdoc = OpenDocumentText() parastyle = style.Style(name="Para", family="paragraph") parastyle.addElement( style.ParagraphProperties(numberlines="false", linenumber="0")) parastyle.addElement( style.TextProperties(fontsize="24pt", fontweight="bold")) textdoc.automaticstyles.addElement(parastyle) hpstyle = style.Style(name="HeaderPara", family="paragraph") hpstyle.addElement(style.ParagraphProperties(linenumber="0")) hpstyle.addElement( style.TextProperties(fontsize="18pt", fontstyle="italic")) textdoc.automaticstyles.addElement(hpstyle) pl = style.PageLayout(name="pagelayout") textdoc.automaticstyles.addElement(pl) mp = style.MasterPage(name="Standard", pagelayoutname=pl) textdoc.masterstyles.addElement(mp) h = style.Header() hp = text.P(text="header content", stylename=hpstyle) h.addElement(hp) mp.addElement(h) textdoc.text.addElement(text.P(text="Paragraph 1", stylename=parastyle)) # Check styles.xml s = textdoc.stylesxml() self.assertContains(s, u'<style:page-layout style:name="pagelayout"/>') self.assertContains(s, u'style:name="HeaderPara"') self.assertNotContains(s, u'style:name="Para" ') # Check content.xml s = textdoc.contentxml() # contentxml is supposed to yed a byts self.assertNotContains( s, b'<style:page-layout style:name="pagelayout"/>') self.assertContains(s, b'style:name="Para"')
def testAttributeForeign(self): """ Test that you can add foreign attributes """ textdoc = OpenDocumentText() standard = style.Style(name=u"Standard", family=u"paragraph") p = style.ParagraphProperties(qattributes={(u'http://foreignuri.com','enable-numbering'):u'true'}) standard.addElement(p) textdoc.styles.addElement(standard) s = textdoc.stylesxml() s.index(u"""<?xml version='1.0' encoding='UTF-8'?>\n""") s.index(u'xmlns:ns41="http://foreignuri.com"') s.index(u'<style:paragraph-properties ns41:enable-numbering="true"/>') e = ElementParser(s,u'style:style') # e = ElementParser('<style:style style:name="Standard" style:display-name="Standard" style:family="paragraph">') self.assertEqual(e.element,u'style:style') self.assertTrue(e.has_value(u"style:display-name","Standard")) self.assertTrue(e.has_value(u"style:name","Standard")) self.assertTrue(e.has_value(u"style:family","paragraph"))
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 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 testAutomaticStyles(self): """ Create a text document with a page layout called "pagelayout" Add a master page Add an automatic style for the heading Check that pagelayout is listed in styles.xml under automatic-styles Check that the heading style is NOT listed in styles.xml Check that the pagelayout is NOT listed in content.xml """ textdoc = OpenDocumentText() parastyle = style.Style(name="Para", family="paragraph") parastyle.addElement(style.ParagraphProperties(numberlines="false", linenumber="0")) parastyle.addElement(style.TextProperties(fontsize="24pt", fontweight="bold")) textdoc.automaticstyles.addElement(parastyle) hpstyle = style.Style(name="HeaderPara", family="paragraph") hpstyle.addElement(style.ParagraphProperties(linenumber="0")) hpstyle.addElement(style.TextProperties(fontsize="18pt", fontstyle="italic")) textdoc.automaticstyles.addElement(hpstyle) pl = style.PageLayout(name="pagelayout") textdoc.automaticstyles.addElement(pl) mp = style.MasterPage(name="Standard", pagelayoutname=pl) textdoc.masterstyles.addElement(mp) h = style.Header() hp = text.P(text="header content", stylename=hpstyle) h.addElement(hp) mp.addElement(h) textdoc.text.addElement(text.P(text="Paragraph 1", stylename=parastyle)) # Check styles.xml s = unicode(textdoc.stylesxml(),'UTF-8') self.assertContains(s, u'<style:page-layout style:name="pagelayout"/>') self.assertContains(s, u'style:name="HeaderPara"') self.assertNotContains(s, u'style:name="Para" ') # Check content.xml s = unicode(textdoc.contentxml(),'UTF-8') self.assertNotContains(s, u'<style:page-layout style:name="pagelayout"/>') self.assertContains(s, u'style:name="Para" ')
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 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 ') e = ElementParser(c, 'draw:frame') # e = ElementParser('<draw:frame svg:width="476pt" text:anchor-type="paragraph" svg:height="404pt">') self.assertTrue(e.has_value('svg:width',"476pt")) self.assertTrue(e.has_value('svg:height',"404pt")) self.assertTrue(e.has_value('text:anchor-type',"paragraph")) self.assertFalse(e.has_value('svg:height',"476pt")) c.index(u'<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 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"
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/>')
def __init__(self, env=None, status_callback=None, language="en", namespace="en.wikipedia.org", creator="", license="GFDL"): self.env = env self.status_callback = status_callback self.language = language self.namespace = namespace self.references = [] self.doc = OpenDocumentText() style.applyStylesToDoc(self.doc) self.text = self.doc.text self.namedLinkCount = 0 self.conf = odfconf.OdfConf if creator: self.doc.meta.addElement(meta.InitialCreator(text=creator)) self.doc.meta.addElement(dc.Creator(text=creator)) if language is not None: self.doc.meta.addElement(dc.Language(text=language)) if license is not None: self.doc.meta.addElement(meta.UserDefined(name="Rights", text=license))
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)