Beispiel #1
0
 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())
Beispiel #2
0
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
Beispiel #3
0
    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')
Beispiel #4
0
 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>"""
         ))
Beispiel #5
0
    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")
Beispiel #6
0
 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 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")
Beispiel #8
0
 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/>')
Beispiel #9
0
def h3(doc, text, bookmark=None):
    e = H(outlinelevel=3)
    if bookmark is not None:
        e.addElement(BookmarkStart(name=bookmark))
    e.addText(text)
    if bookmark is not None:
        e.addElement(BookmarkEnd(name=bookmark))
    doc.text.addElement(e)
Beispiel #10
0
 def render_subblock(self, doc, num, problems, text, show_solution):
     base = (num - 1) * 10 + 1
     doc.text.addElement(
         H(outlinelevel=1,
           stylename=self.h1style,
           text="{} Teil {}".format(text, num)))
     for i, p in enumerate(problems):
         p = P(text="{}) {}".format(base + i, p.render(show_solution)))
         doc.text.addElement(p)
     doc.text.addElement(P())
Beispiel #11
0
 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/>')
Beispiel #12
0
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_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/>')
Beispiel #14
0
    def _addSubSubSection(self, title, text):
        # Adding second heading
        mysecondheading_element = H(outlinelevel=2, stylename=self._h3style)
        mysecondheading_text = title
        teletype.addTextToElement(mysecondheading_element,
                                  mysecondheading_text)
        self._textdoc.text.addElement(mysecondheading_element)

        if text != '':
            # Adding a paragraph
            paragraph_element = P(stylename=self._justifystyle)
            paragraph_text = text
            teletype.addTextToElement(paragraph_element, paragraph_text)
            self._textdoc.text.addElement(paragraph_element, paragraph_text)
Beispiel #15
0
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")
Beispiel #16
0
 def addTitle3(self,text,newpage=False):
     if newpage:
         title = H(stylename=self.h3bstyle,text=text,outlinelevel=3)
     else:
         title = H(stylename=self.h3style,text=text,outlinelevel=3)
     self.textdoc.text.addElement(title)
Beispiel #17
0
def coursePage(coursename, data, lang):
    coursetitle = H(stylename=h2style, text=coursename, outlinelevel=2)
    textdoc.text.addElement(coursetitle)
    blankline = P(text="")
    textdoc.text.addElement(blankline)

    for diagramtype in [pie, percent]:
        p = P()
        textdoc.text.addElement(p)
        img_path = path + coursename + "-All" + diagramtype
        href = textdoc.addPicture(img_path)
        f = Frame(name=coursename + diagramtype,
                  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)

    if lang == "eu":
        subjectsp = P(text="%70 baino gainditu gutxiago duten ikasgaiak:")
    else:
        subjectsp = P(text="Asignaturas con menos del %70 de aprobados:")
    textdoc.text.addElement(subjectsp)
    blankline = P(text="")
    textdoc.text.addElement(blankline)
    textList = List(stylename="L1")

    file = path + "ehunekoak-" + period + "-" + year + "-" + coursename + "None.csv"
    with open(file, 'r', encoding="UTF-8") as results:
        reader = csv.reader(results)
        headers = next(reader, None)  # get first row with headers
        for row in reader:
            if float(row[1]) < 70 and row[0] != "All":
                item = ListItem()
                if lang == "eu":
                    item.addElement(
                        P(text=row[0] + ": " + "{:.2f}".format(float(row[1])) +
                          "%"))
                else:
                    item.addElement(
                        P(text=ikasgai[row[0]] + ": " +
                          "{:.2f}".format(float(row[1])) + "%"))
                textList.addElement(item)
                textdoc.text.addElement(textList)

    for courselang in data.keys():
        coursetitle = H(stylename=h2style,
                        text=coursename + "-" + courselang,
                        outlinelevel=2)
        textdoc.text.addElement(coursetitle)
        blankline = P(text="")
        textdoc.text.addElement(blankline)

        for diagramtype in [pie, percent]:
            p = P()
            textdoc.text.addElement(p)
            img_path = path + coursename + "-" + courselang + diagramtype
            href = textdoc.addPicture(img_path)
            f = Frame(name=coursename + diagramtype + courselang,
                      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)

        blankline = P(text="")
        textdoc.text.addElement(blankline)

        if lang == "eu":
            subjectsp = P(text="%70 baino gainditu gutxiago duten ikasgaiak:")
        else:
            subjectsp = P(text="Asignaturas con menos del %70 de aprobados:")
        textdoc.text.addElement(subjectsp)
        blankline = P(text="")
        textdoc.text.addElement(blankline)
        textList = List(stylename="L1")

        file = path + "ehunekoak-" + period + "-" + year + "-" + coursename + courselang + ".csv"
        with open(file, 'r', encoding="UTF-8") as results:
            reader = csv.reader(results)
            headers = next(reader, None)  # get first row with headers
            for row in reader:
                if float(row[1]) < 70 and row[0] != "All":
                    item = ListItem()
                    if lang == "eu":
                        item.addElement(
                            P(text=row[0] + ": " +
                              "{:.2f}".format(float(row[1])) + "%"))
                    else:
                        item.addElement(
                            P(text=ikasgai[row[0]] + ": " +
                              "{:.2f}".format(float(row[1])) + "%"))
                    textList.addElement(item)
                    textdoc.text.addElement(textList)

        for group in data[courselang]:
            if group in ["Bil", "Plur"]:
                #1 ESO-AG-AGBil - 2. Ebaluazioa (2019-2020) -percent-es
                g = coursename + "-" + courselang + "-" + courselang + group
                grouptitle = H(stylename=h3style,
                               text=translation[group][lang],
                               outlinelevel=3)
                textdoc.text.addElement(grouptitle)
                blankline = P(text="")
                textdoc.text.addElement(blankline)
                for diagramtype in [mean, percent]:  #,name2]:
                    p = P()
                    textdoc.text.addElement(p)
                    img_path = path + g + diagramtype
                    href = textdoc.addPicture(img_path)
                    f = Frame(name=group + diagramtype,
                              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)
            else:
                groupPage(group, lang)
Beispiel #18
0
def groupPage(group, lang):
    grouptitle = H(stylename=h3style, text=group, outlinelevel=3)
    textdoc.text.addElement(grouptitle)
    blankline = P(text="")
    textdoc.text.addElement(blankline)

    if td != '':
        table = Table()
        table.addElement(TableColumn(numbercolumnsrepeated=2))
        headers = [
            translation['part'][lang], '2 ' + translation['period'][lang]
        ]  #,"2. Ebaluazioa","Azken Ebaluazioa"]
        tr = TableRow()
        table.addElement(tr)
        for val in headers:
            tc = TableCell(stylename="Table")
            tr.addElement(tc)
            p = P(stylename=tableheaders, text=val)
            tc.addElement(p)
        #f = [["garbitasuna",3,6],["materiala",6,8],["Adostasuna", "Ez konforme","konforme"],["Harremanak1",7,8],["Harremanak2",6,7],["Adostasuna", "konforme","konforme"]]
        g = group.replace(". ", "")
        g = g.replace("º ", "")
        g = g.replace(".", "")
        g = g.replace("º", "")
        g = g.replace("° ", "")
        g = g.replace("°", "")
        g = g.replace(" ", "")
        g = g.replace("Bach1", "5")
        g = g.replace("Bach2", "6")
        g = g.replace("Batx1", "5")
        g = g.replace("Batx2", "6")
        f = td[g]
        for line in f:
            if "group" in line:  #FIXME: If not all group tables contain a row with the group name (also in text header...)
                continue
            tr = TableRow()
            table.addElement(tr)
            for i, val in enumerate(line):
                if i == 0:
                    tc = TableCell(stylename="Table")
                    tr.addElement(tc)
                    p = P(stylename=tablecontents, text=translation[val][lang])
                elif val == "EzKonforme":
                    tc = TableCell(stylename="Table")
                    tr.addElement(tc)
                    p = P(stylename=tablecontentscenterred,
                          text=translation[val][lang])
                elif val == "Konforme":
                    tc = TableCell(stylename="Table")
                    tr.addElement(tc)
                    p = P(stylename=tablecontentscenter,
                          text=translation[val][lang])
                else:
                    tc = TableCell(stylename="Table")
                    tr.addElement(tc)
                    if isinstance(val, numbers.Number):
                        val = round(val, 1)
                    p = P(stylename=tablecontentscenter, text=val)
                tc.addElement(p)

        textdoc.text.addElement(table)

        blankline = P(text="")
        textdoc.text.addElement(blankline)
    if lang == "eu":
        subjectsp = P(text="%70 baino gainditu gutxiago duten ikasgaiak:")
    else:
        subjectsp = P(text="Asignaturas con menos del %70 de aprobados:")
    textdoc.text.addElement(subjectsp)
    blankline = P(text="")
    textdoc.text.addElement(blankline)
    textList = List(stylename="L1")

    file = path + "ehunekoak-" + period + "-" + year + "-" + group + ".csv"
    with open(file, 'r', encoding="UTF-8") as results:
        reader = csv.reader(results)
        headers = next(reader, None)  # get first row with headers
        for row in reader:
            if float(row[1]) < 70 and row[0] != "All":
                item = ListItem()
                if lang == "eu":
                    item.addElement(
                        P(text=row[0] + ": " + "{:.2f}".format(float(row[1])) +
                          "%"))
                else:
                    item.addElement(
                        P(text=ikasgai[row[0]] + ": " +
                          "{:.2f}".format(float(row[1])) + "%"))
                textList.addElement(item)
                textdoc.text.addElement(textList)

    breakpage = P(stylename=withbreak, text="")
    textdoc.text.addElement(breakpage)

    for diagramtype in [pie, percent]:  #,name2]:
        p = P()
        textdoc.text.addElement(p)
        img_path = path + group + diagramtype
        href = textdoc.addPicture(img_path)
        f = Frame(name=group + diagramtype,
                  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)
Beispiel #19
0
    }
}

#pl = PageLayout(name="pagelayout")
#textdoc.automaticstyles.addElement(pl)

#mp = MasterPage(name="Standard", pagelayoutname=pl)
#textdoc.masterstyles.addElement(mp)
#h = Header()
#img_path = "/home/asier/Hezkuntza/SGCC/PR04 Gestion documental/Plantillas - Logos - Encabezados/membrete.png"
#href = textdoc.addPicture(img_path)
#img = Image(href=href, type="simple", show="embed", actuate="onLoad")
#h.addElement(img)
#mp.addElement(h)

title = H(stylename=h1style, text="Taldeen adostasun maila", outlinelevel=1)
textdoc.text.addElement(title)


def groupPage(group, lang):
    grouptitle = H(stylename=h3style, text=group, outlinelevel=3)
    textdoc.text.addElement(grouptitle)
    blankline = P(text="")
    textdoc.text.addElement(blankline)

    if td != '':
        table = Table()
        table.addElement(TableColumn(numbercolumnsrepeated=2))
        headers = [
            translation['part'][lang], '2 ' + translation['period'][lang]
        ]  #,"2. Ebaluazioa","Azken Ebaluazioa"]
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
Beispiel #21
0
def add_header(doc, text, level):
    """ add odf header object """
    header = H(outlinelevel=level, text=text, stylename="header.%s" % level)
    doc.add(header)
Beispiel #22
0
from odf.opendocument import OpenDocumentText
from odf.style import Style, TextProperties, ParagraphProperties
from odf.text import P, H

textdoc = OpenDocumentText()

H1WithBreak = Style(name="H1WithBreak", parentstylename="Standard", family="paragraph")
H1WithBreak.addElement(ParagraphProperties(breakbefore="page",textalign="center"))
H1WithBreak.addElement(TextProperties(fontsize="20pt",fontweight="bold" ))
textdoc.styles.addElement(H1WithBreak)

boldstyle = Style(name="Bold", family="paragraph")
boldstyle.addElement(TextProperties(fontsize="6pt",fontweight="bold" ))
textdoc.automaticstyles.addElement(boldstyle)

h = H(outlinelevel=1,stylename=H1WithBreak)
h.addText('This is header 1')
textdoc.text.addElement(h)

p = P(stylename=boldstyle)
p.addText('This is bold text')
textdoc.text.addElement(p)

textdoc.save("style", True)
Beispiel #23
0
fontweightcomplex="bold"))
textdoc.automaticstyles.addElement(T2style)

# T5
"""
  <style:style style:name="T5" style:family="text">
     <style:text-properties fo:color="#ff0000" style:font-name="Arial"/>
   </style:style>
"""
T5style = Style(name="T5", family="text")
T5style.addElement(TextProperties(color="#ff0000",fontname="Arial"))
textdoc.automaticstyles.addElement(T5style)

# now construct what goes into <office:text>

h=H(outlinelevel=1, text='Purpose (Heading 1)')
textdoc.text.addElement(h)
p = P(text="The following sections illustrate various possibilities in ODF Text",
      stylename='Text_20_body')
textdoc.text.addElement(p)

textdoc.text.addElement(H(outlinelevel=2,text='A simple series of paragraphs (Heading 2)'))
textdoc.text.addElement(P(text="This section contains a series of paragraphs.", 
stylename='Text_20_body'))
textdoc.text.addElement(P(text="This is a second paragraph.", 
stylename='Text_20_body'))
textdoc.text.addElement(P(text="And a third paragraph.", stylename='Text_20_body'))

textdoc.text.addElement(H(outlinelevel=2,text='A section with lists (Heading 2)'))
textdoc.text.addElement(P(text="Elements to illustrate:"))
Beispiel #24
0
 def addTitle(self,text):
     title = H(stylename=self.h1style,text=text,outlinelevel=1)
     self.textdoc.text.addElement(title)
Beispiel #25
0
    def generate(self):
        self._textdoc = OpenDocumentText()

        # Creating different style used in the document
        s = self._textdoc.styles

        # For Level-1 Headings that are centerd
        h1style = Style(name="BsHeading 1", family="paragraph")
        h1style.addElement(
            ParagraphProperties(attributes={"textalign": "center"}))
        h1style.addElement(
            TextProperties(attributes={
                "fontsize": "18pt",
                "fontweight": "bold"
            }))

        # For Level-2 Headings that are centered
        self._h2style = Style(name="BsHeading 2", family="paragraph")
        self._h2style.addElement(
            ParagraphProperties(attributes={"textalign": "left"}))
        self._h2style.addElement(
            TextProperties(attributes={
                "fontsize": "15pt",
                "fontweight": "bold"
            }))

        # For Level-3 Headings that are centered
        self._h3style = Style(name="BsHeading 3", family="paragraph")
        self._h3style.addElement(
            ParagraphProperties(attributes={"textalign": "left"}))
        self._h3style.addElement(
            TextProperties(attributes={
                "fontsize": "14pt",
                "fontweight": "bold"
            }))

        # For bold text
        boldstyle = Style(name="Bold", family="text")
        boldstyle.addElement(TextProperties(attributes={"fontweight": "bold"}))

        # For numbered list
        numberedliststyle = ListStyle(name="NumberedList")
        level = 1
        numberedlistproperty = ListLevelStyleNumber(level=str(level),
                                                    numsuffix=".",
                                                    startvalue=1)
        numberedlistproperty.setAttribute('numsuffix', ".")
        numberedlistproperty.addElement(
            ListLevelProperties(minlabelwidth="%fcm" % (level - .2)))
        numberedliststyle.addElement(numberedlistproperty)

        # For Bulleted list
        bulletedliststyle = ListStyle(name="BulletList")
        level = 1
        bulletlistproperty = ListLevelStyleBullet(level=str(level),
                                                  bulletchar=u"•")
        bulletlistproperty.addElement(
            ListLevelProperties(minlabelwidth="%fcm" % level))
        bulletedliststyle.addElement(bulletlistproperty)

        # Justified style
        self._justifystyle = Style(name="justified", family="paragraph")
        self._justifystyle.addElement(
            ParagraphProperties(attributes={"textalign": "justify"}))

        # Creating a tabstop at 10cm
        tabstops_style = TabStops()
        tabstop_style = TabStop(position="10cm")
        tabstops_style.addElement(tabstop_style)
        tabstoppar = ParagraphProperties()
        tabstoppar.addElement(tabstops_style)
        tabparagraphstyle = Style(name="Question", family="paragraph")
        tabparagraphstyle.addElement(tabstoppar)
        s.addElement(tabparagraphstyle)

        # Register created styles to styleset
        s.addElement(h1style)
        s.addElement(self._h2style)
        s.addElement(boldstyle)
        s.addElement(numberedliststyle)
        s.addElement(bulletedliststyle)
        s.addElement(self._justifystyle)
        s.addElement(tabparagraphstyle)

        # Adding main heading
        mymainheading_element = H(outlinelevel=1, stylename=h1style)
        mymainheading_text = "Save the Cat Beat Sheet"
        teletype.addTextToElement(mymainheading_element, mymainheading_text)
        self._textdoc.text.addElement(mymainheading_element)

        self._addSubSection('Name', self._data['movie']['name'])
        self._addSubSection('LogLine', self._data['movie']['logline'])
        self._addSubSection('Theme', self._data['movie']['theme'])
        self._addSubSection('Genre', self._data['movie']['genre'])
        self._addSubSection('Author', '')
        self._addParagraph('Nome: ' + self._data['author']['name'])
        self._addParagraph('e-mail: ' + self._data['author']['email'])
        self._addParagraph('Institute: ' + self._data['author']['institute'])

        self._addSubSection('Synopsis', self._data['synopsis'])
        self._addSubSection('Beat Sheet', '')
        for card in self._data[1]['beat-sheet']:
            self._addSubSubSection(card['title'], card['text'])

        self._addSubSection('Plot', self._data['plot'])
        self._addSubSection('Argumento', self._data['argumento'])
        self._addSubSection('Escaleta', self._data['escaleta'])

        # Adding bulleted list
        #        bulletlist = List(stylename=bulletedliststyle)
        #        listitemelement1 = ListItem()
        #        listitemelement1_paragraph = P()
        #        listitemelement1_content = "My first item"
        #        teletype.addTextToElement(listitemelement1_paragraph, listitemelement1_content)
        #        listitemelement1.addElement(listitemelement1_paragraph)
        #        bulletlist.addElement(listitemelement1)
        #        listitemelement2 = ListItem()
        #        listitemelement2_paragraph = P()
        #        listitemelement2_content = "My second item"
        #        teletype.addTextToElement(listitemelement2_paragraph, listitemelement2_content)
        #        listitemelement2.addElement(listitemelement2_paragraph)
        #        bulletlist.addElement(listitemelement2)
        #
        #        self._textdoc.text.addElement(bulletlist)
        #
        #        # Adding numbered list
        #        numberlist = List(stylename=numberedliststyle)
        #        listitemelement1 = ListItem()
        #        listitemelement1_paragraph = P()
        #        listitemelement1_content = "My first item"
        #        teletype.addTextToElement(listitemelement1_paragraph, listitemelement1_content)
        #        listitemelement1.addElement(listitemelement1_paragraph)
        #        numberlist.addElement(listitemelement1)
        #        listitemelement2 = ListItem()
        #        listitemelement2_paragraph = P()
        #        listitemelement2_content = "My second item"
        #        teletype.addTextToElement(listitemelement2_paragraph, listitemelement2_content)
        #        listitemelement2.addElement(listitemelement2_paragraph)
        ##        numberlist.addElement(listitemelement2)
        ##
        #        self._textdoc.text.addElement(numberlist)

        # Adding a tabbed sentence to check tabstop
        #        newtext = "Testing\tTabstops"
        #        tabp = P(stylename=tabparagraphstyle)
        #        teletype.addTextToElement(tabp, newtext)
        #        self._textdoc.text.addElement(tabp)

        self._textdoc.save(u"/tmp/save-the-cat.odt")
Beispiel #26
0
def sols2odt(variables, file_name, user_input):
    '''
    Soluciones a documento Open Document Text
    '''
    from odf.opendocument import OpenDocumentText
    from odf.style import Style, TextProperties
    from odf.text import H, P, Span
    # Comienza la salida:
    textdoc = OpenDocumentText()
    # Styles
    s = textdoc.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': "18pt",
                                                  'fontweight': "bold"}))
    s.addElement(h2style)
    # An automatic style Bold
    boldstyle = Style(name="Bold", family="text")
    boldprop = TextProperties(fontweight="bold")
    boldstyle.addElement(boldprop)
    textdoc.automaticstyles.addElement(boldstyle)
    # Italic
    italicstyle = Style(name="Italic", family="text")
    italicprop = TextProperties(fontstyle="italic")
    italicstyle.addElement(italicprop)
    textdoc.automaticstyles.addElement(italicstyle)
    # Text
    h = H(outlinelevel=1, stylename=h1style, text="Reporte pyENL")
    textdoc.text.addElement(h)
    p = P(text='')
    textdoc.text.addElement(p)
    h = H(outlinelevel=1, stylename=h2style, text="Ecuaciones")
    textdoc.text.addElement(h)
    p = P(text='')
    textdoc.text.addElement(p)
    # Añadimos las ecuaciones:
    for eqn in user_input:
        p = P(text='')
        if '<<' in eqn:
            comentario = eqn
            comentario = comentario.replace('<<', '')
            comentario = comentario.replace('>>', '')
            boldpart = Span(stylename=boldstyle, text=comentario)
            p.addElement(boldpart)
        else:
            italicpart = Span(stylename=italicstyle, text=eqn)
            p.addElement(italicpart)
        textdoc.text.addElement(p)
    # Ahora añadir las soluciones:
    p = P(text='')
    textdoc.text.addElement(p)
    h = H(outlinelevel=1, stylename=h2style, text="Soluciones")
    textdoc.text.addElement(h)
    p = P(text='')
    textdoc.text.addElement(p)

    for variable in variables:
        # Primero insertar el nombre de la variable con su valor y finalmente
        # El comentario de la misma:
        p = P(text=variable.name + ' = ' + str(variable.guess) + ' ' +
              str(variable.units))
        textdoc.text.addElement(p)
        p = P(text=variable.comment)
        textdoc.text.addElement(p)
        p = P(text='')
        textdoc.text.addElement(p)
    # Guardar...
    textdoc.save(file_name)
Beispiel #27
0
def h2(doc, text, bookmark=None):
    e = H(outlinelevel=2, text=text)
    if bookmark is not None:
        e.addElement(Bookmark(name=bookmark))
    doc.text.addElement(e)
Beispiel #28
0
mp = MasterPage(name="Standard", pagelayoutname=pl)
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)

algo = Style(name = "kk")
numeracion = ParagraphProperties(pagenumber = "2")
algo.addElement(numeracion)
textdoc.automaticstyles.addElement(algo)
# 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)
fp = P(stylename=" foot")
pagina = Span(stylename="foot2", text="Página: ")
fp.addElement(pagina)
numero = PageNumber(selectpage="auto")
fp.addElement(numero)
f.addElement(fp)
mp.addElement(f)

textdoc.save("myfirstdocument.odt")