def addTableOnBookmark(self, bookmarkName, tableData, enumerated=False):
        '''Вставка таблицы перед закладкой
		'''
        table_columns = 3 if enumerated else 2
        #Создание и заполнение таблицы
        table = Table()
        table.addElement(TableColumn(numbercolumnsrepeated=table_columns))
        for index, row in enumerate(tableData):
            tr = TableRow()
            table.addElement(tr)
            if enumerated:
                tc = TableCell()
                tr.addElement(tc)
                tc.addElement(P(text=str(index + 1)))
            for item in row:
                tc = TableCell()
                tr.addElement(tc)
                tc.addElement(
                    P(text=str(item) if type(item) != QVariant else ''))
        bookmarks = self.doc.getElementsByType(BookmarkStart)
        #Вставка таблицы в content.xml
        for bookmark in bookmarks:
            if bookmark.getAttribute("name") == bookmarkName:
                bookmark.parentNode.parentNode.insertBefore(
                    table, bookmark.parentNode)
                bookmark.parentNode.parentNode.insertBefore(
                    P(text=""), bookmark.parentNode)
        self.doc.save(root + r"/releasedDocs/Документ", True)
Exemple #2
0
 def addTable(self,tabledata,headers,formater=None):
     if formater and len(formater)!=len(tabledata):
         raise ValueError
     if formater is None:
         formater = [[""]*len(tabledata[0])]*len(tabledata)
     table = Table()
     columns = len(headers)
     table.addElement(TableColumn(numbercolumnsrepeated=columns))
     tr = TableRow()
     table.addElement(tr)
     for header in headers:
         tc = TableCell(stylename="Table")
         tr.addElement(tc)
         p = P(stylename=self.tableheaders,text=header)
         tc.addElement(p)
     for line,formats in zip(tabledata,formater):
         tr = TableRow()
         table.addElement(tr)
         for column,cformat in zip(line,formats):
             if cformat == "centerred":
                 cellformat = self.tablecontentscenter
             elif cformat == "center":
                 cellformat = self.tablecontentscenterred
             else:
                 cellformat = self.tablecontents
             tc = TableCell(stylename="Table")
             tr.addElement(tc)
             p = P(stylename=cellformat,text=column)
             tc.addElement(p)
     self.textdoc.text.addElement(table)
Exemple #3
0
def create_odf_table(name, data):
    """
    returns an odf table object that has been added a first row containing
    the columns' title

    """
    table = Table(name=name)

    # we need to add columns. The columns itself do not contain the data
    # though. So, we add them only for the first row.
    for c in range(len(data[0])):
        # add table columns
        col = TableColumn(numbercolumnsrepeated=1, stylename="wCol0")
        table.addElement(col)

    for i, item in enumerate(data):

        # the first row contains the table heading, which is colored
        # differently from the rest of the table. Additionally,
        style = "bgrOrange" if i == 0 else None

        logger.debug("row content:%s", item)
        tr = create_odf_table_row(item, style)
        table.addElement(tr)

    return table
Exemple #4
0
def generate_ods(data):
    """
    Generate a ODS file.
    :param data: list-like of dict with the data.
    :return:
    """
    doc = OpenDocumentSpreadsheet()
    table = Table()
    tr = TableRow()
    colautowidth = Style(name="co1", family="table-column")
    colautowidth.addElement(TableColumnProperties(useoptimalcolumnwidth=True))
    doc.automaticstyles.addElement(colautowidth)
    for column in data[0].keys():
        table.addElement(TableColumn(stylename=colautowidth))
        tc = TableCell(valuetype="string", value=column)
        tc.addElement(P(text=column))
        tr.addElement(tc)
    table.addElement(tr)
    for row in data:
        tr = TableRow()
        for column in row.keys():
            tc = TableCell(valuetype="string", value=row[column])
            tc.addElement(P(text=row[column]))
            tr.addElement(tc)
        table.addElement(tr)
    file = os.path.join(
        tempfile.gettempdir(),
        'SIGE' + datetime.now().strftime('%Y%m%d%H%M%S%f') + '.ods')
    doc.spreadsheet.addElement(table)
    print(doc.automaticstyles.childNodes[0].attributes)
    doc.save(file)
    return file
Exemple #5
0
    def addtable(self, name, hdr): 
        self.table = Table(name=str(name))
        self.doc.spreadsheet.addElement(self.table)

        for h in hdr[:-2]:
            tcol = TableColumn(stylename=self.colStyle30)
            self.table.addElement(tcol)
        tcol = TableColumn(stylename=self.colStyle40)
        self.table.addElement(tcol)
        tcol = TableColumn(stylename=self.colStyle200)
        self.table.addElement(tcol)

        self.exrow=1
        tr = TableRow()
        for item in hdr:
            tc = TableCell(stylename="hdrStyle") #empty cell
            tr.addElement(tc)
            p = P(text=item)
            tc.addElement(p)
        self.table.addElement(tr)
        return
Exemple #6
0
 def as_table(self):
     """Convert to a odf.table.Table object"""
     t = Table(name=self.name)
     # Find out max row and col
     maxcol = max(col for col, row in self._contents.keys())
     maxrow = max(row for col, row in self._contents.keys())
     # Add column styles
     for c in range(0, maxcol + 1):
         s = self._columnstyles.get(c, None)
         if s:
             t.addElement(TableColumn(stylename=s))
         else:
             t.addElement(TableColumn())
     for row in range(0, maxrow + 1):
         tr = TableRow()
         t.addElement(tr)
         for col in range(0, maxcol + 1):
             cell = self._contents.get((col, row), None)
             if cell:
                 tr.addElement(cell)
             else:
                 tr.addElement(TableCell())
     return t
Exemple #7
0
def convert_FFPtable_USO(path):
    name = "FFPtable.uso"
    table = Table(name=name)
    with open(path) as fin:
        for i in range(2):
            table.addElement(TableColumn())

        for line in fin.readlines():
            line = line.split()
            row = TableRow()
            for item in line:
                cell = TableCell(valuetype="float", value=item)
                row.addElement(cell)
            table.addElement(row)
    return table
Exemple #8
0
 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)
Exemple #9
0
def inittable(textdoc):
    # Create a style for the table content. One we can modify
    # later in the word processor.
    tablecontents = Style(name="Table Contents", family="paragraph")
    tablecontents.addElement(
        ParagraphProperties(numberlines="false", linenumber="0"))
    tablecontents.addElement(TextProperties(fontweight="bold"))
    textdoc.styles.addElement(tablecontents)
    widewidth = Style(name="co1", family="table-column")
    widewidth.addElement(
        TableColumnProperties(columnwidth="9", breakbefore="auto"))
    textdoc.automaticstyles.addElement(widewidth)
    textdoc.styles.addElement(widewidth)
    table = Table(name='test')
    table.addElement(
        TableColumn(stylename=widewidth, defaultcellstylename="ce1"))
    return table, tablecontents, textdoc
Exemple #10
0
def convert_FFPtable_day(path):
    name = "FFPtable.day"

    table = Table(name=name)
    with open(path) as fin:
        line = fin.readline().split()[2:]
        row = TableRow()
        for year in line:
            table.addElement(TableColumn())
            cell = TableCell(valuetype="float", value=year)
            row.addElement(cell)
        table.addElement(row)

        for line in fin.readlines():
            line = line.split()[2:]
            row = TableRow()
            for item in line:
                cell = TableCell(valuetype="float", value=item)
                row.addElement(cell)
            table.addElement(row)
    return table
Exemple #11
0
def save(telephoneDir, subdivision, collaborator, number, telephoneType):
    textdoc = OpenDocumentSpreadsheet()

    tablecontents = Style(name="Table Contents", family="paragraph")
    tablecontents.addElement(
        ParagraphProperties(numberlines="false", linenumber="0"))
    textdoc.styles.addElement(tablecontents)

    style2 = Style(name="style2", family="table-column")
    style2.addElement(TableColumnProperties(columnwidth="2cm"))
    textdoc.automaticstyles.addElement(style2)

    style6 = Style(name="style6", family="table-column")
    style6.addElement(TableColumnProperties(columnwidth="6cm"))
    textdoc.automaticstyles.addElement(style6)

    table = Table(name=u"Подразделения")
    table.addElement(TableColumn(numbercolumnsrepeated=2, stylename=style6))

    def row(rec):
        tr = TableRow()
        table.addElement(tr)
        for r in rec:
            tc = TableCell()
            tr.addElement(tc)
            p = P(stylename=tablecontents, text=r)
            tc.addElement(p)

    row((u"подразделение", u"головное подразделение"))
    row((telephoneDir.subdivision.name.decode("utf-8"), ""))

    def write(subdivision):
        for s in subdivision.subdivisions:
            row((s.name.decode("utf-8"), subdivision.name.decode("utf-8")))
            write(s)

    write(telephoneDir.subdivision)

    textdoc.spreadsheet.addElement(table)

    table = Table(name=u"Телефонный справочник")
    table.addElement(TableColumn(numbercolumnsrepeated=2, stylename=style2))
    table.addElement(TableColumn(numbercolumnsrepeated=4, stylename=style6))

    row((u"телефон", u"код сотр.", u"фамилия", u"имя", u"отчество",
         u"подразделение", u"тип тел."))

    def find(c, subdivision):
        if c in subdivision.collaborators:
            return subdivision.name.decode("utf-8")
        else:
            for s in subdivision.subdivisions:
                r = find(c, s)
                if r:
                    return r

    subdivision = int(subdivision)
    telephoneType = int(telephoneType)
    collaborator = collaborator.encode('utf-8')
    number = number.encode('utf-8')
    if not subdivision:
        lambdaSubdivision = lambda rec: True
    else:
        subdivisions = list(sorted(telephoneDir.subdivision.iterSubdivision()))
        subdivisions.insert(0, 'все')
        s = subdivisions[subdivision]
        lambdaSubdivision = lambda rec: rec.collaborator in s
    if not collaborator:
        lambdaCollaborator = lambda rec: True
    else:
        lambdaCollaborator = lambda rec: str(rec.collaborator)[0:len(
            collaborator)] == collaborator
    if not number:
        lambdaNumber = lambda rec: True
    else:
        lambdaNumber = lambda rec: str(rec.telephone.number)[0:len(number)
                                                             ] == number
    if not telephoneType:
        lambdaTelephoneType = lambda rec: True
    else:
        telephoneTypes = list(sorted(telephoneDir.telephones.telephoneTypes))
        telephoneTypes.insert(0, 'все')
        t = telephoneTypes[telephoneType]
        lambdaTelephoneType = lambda rec: rec.telephone.type == t
    tmpDir = list(sorted(telephoneDir))
    tmpDir = filter(lambda telephone: lambdaSubdivision(telephone) and \
                                                     lambdaCollaborator(telephone) and \
                                                     lambdaNumber(telephone) and \
                                                     lambdaTelephoneType(telephone), tmpDir)
    print subdivision, telephoneType, collaborator, number
    for r in tmpDir:
        row((r.telephone.number, r.collaborator.code,
             r.collaborator.family.decode("utf-8"),
             r.collaborator.name.decode("utf-8"),
             r.collaborator.patronym.decode("utf-8"),
             find(r.collaborator, telephoneDir.subdivision),
             r.telephone.type.name.decode("utf-8")))

    textdoc.spreadsheet.addElement(table)
    textdoc.save("telephonedir.ods")
Exemple #12
0
def getRsltTable(testType, results, tdfBugs):

    targetAppsSel = results[testType].keys()

    # Start the table, and describe the columns
    table = Table(name=testType)
    table.addElement(
        TableColumn(numbercolumnsrepeated=1, stylename="nameColStyle"))
    table.addElement(TableColumn(stylename="linkColStyle"))
    if checkOdf:
        table.addElement(
            TableColumn(numbercolumnsrepeated=3, stylename="rankColStyle"))
    else:
        table.addElement(
            TableColumn(numbercolumnsrepeated=4, stylename="rankColStyle"))

    for i in targetAppsSel:
        for i in range(len(testLabelsShort) - 1):
            table.addElement(TableColumn(stylename="valColStyle"))
            table.addElement(TableColumn(stylename="linkColStyle"))
        table.addElement(TableColumn(stylename="rankColStyle"))
        table.addElement(TableColumn(stylename="linkColStyle"))
    table.addElement(TableColumn(stylename="rankColStyle"))
    table.addElement(TableColumn(stylename="tagColStyle"))
    table.addElement(TableColumn(stylename="tagColStyle"))
    table.addElement(TableColumn(stylename="tagColStyle"))

    #First row: application names
    tr = TableRow()
    table.addElement(tr)
    tc = TableCell()  #empty cell
    tr.addElement(tc)
    tc = TableCell()  #empty cell
    tr.addElement(tc)
    tc = TableCell()  #empty cell
    tr.addElement(tc)
    tc = TableCell()  #empty cell
    tr.addElement(tc)
    tc = TableCell()  #empty cell
    tr.addElement(tc)
    appcolumns = len(testLabelsShort)
    for a in targetAppsSel:
        tc = TableCell(numbercolumnsspanned=2 * (appcolumns - 1),
                       stylename="THstyle")
        tr.addElement(tc)
        p = P(stylename="tablecontents",
              text="Target: " + results[testType][a]['path'])
        tc.addElement(p)
        for i in range(2 * (appcolumns - 1) -
                       1):  # create empty cells for the merged one
            tc = TableCell()
            tr.addElement(tc)
        tc = TableCell(stylename="Csepstyle")
        tr.addElement(tc)
    #Second row: test names
    tr = TableRow()
    table.addElement(tr)
    tc = TableCell(stylename="THstyle")  #empty cell
    tr.addElement(tc)
    p = P(stylename="tablecontents", text="Test case")
    tc.addElement(p)
    tc = TableCell(stylename="THstyle")  #empty cell
    tr.addElement(tc)
    if not checkOdf:
        tc = TableCell(stylename="THstyle")  #empty cell
        tr.addElement(tc)
        p = P(stylename="tablecontents", text="P/R")
        tc.addElement(p)
        tc.addElement(
            addAnn(
                "Negative: progression, positive: regression, 0: no change"))
    tc = TableCell(stylename="THstyle")  #empty cell
    tr.addElement(tc)
    p = P(stylename="tablecontents", text="Max last")
    tc.addElement(p)
    tc.addElement(addAnn("Max grade for the last LO version"))
    tc = TableCell(stylename="THstyle")  #empty cell
    tr.addElement(tc)
    p = P(stylename="tablecontents", text="Sum last")
    tc.addElement(p)
    tc.addElement(addAnn("Sum of grades for the last LO version"))
    tc = TableCell(stylename="THstyle")  #empty cell
    tr.addElement(tc)
    p = P(stylename="tablecontents", text="Sum all")
    tc.addElement(p)
    tc.addElement(addAnn("Sum of grades for all tested versions"))

    for a in targetAppsSel:
        for tl in range(1,
                        len(testLabelsShort)):  # we do not show the PPOI value
            tc = TableCell(numbercolumnsspanned=2, stylename="THstyle")
            tr.addElement(tc)
            p = P(stylename="tablecontents", text=testLabelsShort[-tl])
            tc.addElement(p)
            tc.addElement(addAnn(testAnnotation[testLabelsShort[-tl]]))
            tc = TableCell()  #the merged cell
            tr.addElement(tc)
        tc = TableCell(stylename="Csepstyle")
        tr.addElement(tc)
        tc = TableCell(stylename="THstyle")
        tr.addElement(tc)

    total = 0
    totalRegressions = 0
    totalEmpty = 0
    totalTimeOut = 0
    for testcase in sorted(results[testType]['new']['tests'].keys()):
        try:
            agrades = np.array([
                valToGrade(results[testType][a]['tests'][testcase][1:])
                for a in targetAppsSel
            ])
            if np.array_equal(agrades[0], [8, 8, 8, 8]):
                continue
            lastgrade = agrades[-1]
            maxgrade = agrades.max(axis=0)
            mingrade = agrades.min(axis=0)
        except KeyError:
            # In case a testcase is in the first csv but not in the second one
            continue
        total += 1

        #identify regressions and progressions
        progreg = 'x'

        if (lastgrade > mingrade).any():  #We have regression
            progreg = str(sum(lastgrade - mingrade))
        else:
            progreg = str(sum(lastgrade - maxgrade))

        if checkRegressions and (int(progreg) >= -1 and
                                 not np.array_equal(agrades[0], [7, 7, 7, 7])):
            continue

        #Looking for improvements, we only care about fdo bugs
        if checkImprovements and ( int(progreg) < 1 or \
                ((not re.search('fdo[0-9]*-[0-9].', testcase) or \
                testType == 'import' and testcase.split('fdo')[1].split('-')[0] not in tdfBugs['import'] or \
                testType == 'export' and testcase.split('fdo')[1].split('-')[0] not in tdfBugs['export']) and
                (not re.search('tdf[0-9]*-[0-9].', testcase) or \
                testType == 'import' and testcase.split('tdf')[1].split('-')[0] not in tdfBugs['import'] or \
                testType == 'export' and testcase.split('tdf')[1].split('-')[0] not in tdfBugs['export']))):
            continue

        if checkOdf:
            allsum = sum([
                sum(valToGrade(results[testType][a]['tests'][testcase][1:]))
                for a in targetAppsSel
            ])
            if allsum <= 5:
                continue

        name = testcase.split("/", 1)[-1].split(".")[0]

        #Avoid showing import regressions as export regressions
        if checkRegressions:
            if testType == "import":
                lImportReg.append(name)
            elif testType == "export" and not np.array_equal(
                    agrades[0], [7, 7, 7, 7]):
                if name in lImportReg or name in lExportReg:
                    continue
                lExportReg.append(name)

        if int(progreg) < 0:
            totalRegressions += 1
        elif np.array_equal(agrades[0], [6, 6, 6, 6]):
            totalEmpty += 1
        elif np.array_equal(agrades[0], [7, 7, 7, 7]):
            totalTimeOut += 1

        #testcase=testcase.split('/')[1]
        tr = TableRow()
        table.addElement(tr)
        tc = TableCell()
        tr.addElement(tc)
        p = P(stylename="tablecontents")
        #TODO: Fix doc link in roundtrip
        if re.search('fdo[0-9]*-[0-9].', testcase):
            ref = 'https://bugs.documentfoundation.org/show_bug.cgi?id=' + str(
                testcase.split('fdo')[1].split('-')[0])
            link = A(type="simple", href="%s" % ref, text=testcase)
        elif re.search('tdf[0-9]*-[0-9].', testcase):
            ref = 'https://bugs.documentfoundation.org/show_bug.cgi?id=' + str(
                testcase.split('tdf')[1].split('-')[0])
            link = A(type="simple", href="%s" % ref, text=testcase)
        elif re.search('ooo[0-9]*-[0-9].', testcase):
            ref = 'https://bz.apache.org/ooo/show_bug.cgi?id=' + str(
                testcase.split('ooo')[1].split('-')[0])
            link = A(type="simple", href="%s" % ref, text=testcase)
        elif re.search('abi[0-9]*-[0-9].', testcase):
            ref = 'https://bugzilla.abisource.com/show_bug.cgi?id=' + str(
                testcase.split('abi')[1].split('-')[0])
            link = A(type="simple", href="%s" % ref, text=testcase)
        elif re.search('kde[0-9]*-[0-9].', testcase):
            ref = 'https://bugs.kde.org/show_bug.cgi?id=' + str(
                testcase.split('kde')[1].split('-')[0])
            link = A(type="simple", href="%s" % ref, text=testcase)
        elif re.search('moz[0-9]*-[0-9].', testcase):
            ref = 'https://bugzilla.mozilla.org/show_bug.cgi?id=' + str(
                testcase.split('moz')[1].split('-')[0])
            link = A(type="simple", href="%s" % ref, text=testcase)
        elif re.search('gentoo[0-9]*-[0-9].', testcase):
            ref = 'https://bugs.gentoo.org/show_bug.cgi?id=' + str(
                testcase.split('gentoo')[1].split('-')[0])
            link = A(type="simple", href="%s" % ref, text=testcase)
        else:
            link = A(type="simple",
                     href="%s" % ('../' + testcase),
                     text=testcase)
        p.addElement(link)
        tc.addElement(p)

        tComparison = TableCell(stylename="THstyle")
        tr.addElement(tComparison)

        if not checkOdf:
            tc = TableCell(valuetype="float", value=progreg)
            tr.addElement(tc)

        # max last
        lastmax = max([
            valToGrade(results[testType][a]['tests'][testcase][1:])
            for a in targetAppsSel
        ][-1])
        tc = TableCell(valuetype="float", value=str(lastmax))
        tr.addElement(tc)

        # sum last
        lastsum = sum([
            valToGrade(results[testType][a]['tests'][testcase][1:])
            for a in targetAppsSel
        ][-1])
        tc = TableCell(valuetype="float", value=str(lastsum))
        tr.addElement(tc)

        # sum all
        allsum = sum([
            sum(valToGrade(results[testType][a]['tests'][testcase][1:]))
            for a in targetAppsSel
        ])
        tc = TableCell(valuetype="float", value=str(allsum))
        tr.addElement(tc)

        for a in targetAppsSel:
            grades = valToGrade(results[testType][a]['tests'][testcase][1:])
            pdfPath = os.path.join(results[testType][a]['path'], testcase)

            if not checkOdf and a == 'new':
                oldFile = os.path.join(results[testType]['old']['path'],
                                       testcase).split('-pair.pdf')[0]
                if os.path.exists(oldFile):
                    newFile = os.path.join(results[testType]['new']['path'],
                                           testcase).split('-pair.pdf')[0]
                    if os.path.exists(newFile):
                        outputFile = oldFile + '-comparison.pdf'
                        if not os.path.exists(outputFile):
                            print("Creating " + outputFile)
                            create_overlayPDF(oldFile, newFile, outputFile)

                        p = P(stylename="tablecontents", text="")
                        comparisonLink = A(type="simple",
                                           href='../' + outputFile,
                                           text=">")
                        p.addElement(comparisonLink)
                        tComparison.addElement(p)

            # Add link only once
            linkAdded = False
            for grade in reversed(grades):  # we do not show the PPOI value
                if max(grades) > 1:
                    tc = TableCell(valuetype="float",
                                   value=str(grade),
                                   stylename='C' + str(int(grade)) + 'style')
                else:
                    tc = TableCell(valuetype="float",
                                   value=str(grade),
                                   stylename='CBstyle')
                tr.addElement(tc)
                tc = TableCell(stylename="THstyle")
                tr.addElement(tc)
                p = P(stylename="tablecontents")

                if not linkAdded and os.path.exists(pdfPath):
                    linkAdded = True
                    link = A(type="simple", href='../' + pdfPath, text=">")
                    p.addElement(link)
                    tc.addElement(p)
                    if checkOdf:
                        pComparison = P(stylename="tablecontents")
                        linkComparison = A(type="simple",
                                           href='../' + pdfPath,
                                           text=">")
                        pComparison.addElement(linkComparison)
                        tComparison.addElement(pComparison)

            tc = TableCell(stylename="THstyle")

            sumall = sum(
                valToGrade(results[testType][a]['tests'][testcase][1:]))
            if grades == [7, 7, 7, 7]:
                p = P(stylename="tablecontents", text="timeout")
                if testType == "export":
                    gradesPrint = valToGrade(values[testcase][a.replace(
                        testType, 'print')][1:])
                    if gradesPrint != [7, 7, 7, 7]:
                        p = P(stylename="tablecontents", text="corrupted")
            elif grades == [6, 6, 6, 6]:
                p = P(stylename="tablecontents", text="empty")
            elif sumall <= 8:
                if testType == "import":
                    goodDocuments.append(testcase)
                    p = P(stylename="tablecontents", text="good import")
                elif testType == "export":
                    if testcase in goodDocuments:
                        p = P(stylename="tablecontents",
                              text="good import, good export")
                    elif testcase in badDocuments:
                        p = P(stylename="tablecontents",
                              text="bad import, good export")
            elif sumall <= 20:
                if testType == "export":
                    if testcase in goodDocuments:
                        p = P(stylename="tablecontents",
                              text="good import, bad export")
                        badDocuments.append(testcase)
                    elif testcase in badDocuments:
                        p = P(stylename="tablecontents",
                              text="bad import, bad export")
                elif testType == "import":
                    badDocuments.append(testcase)
                    p = P(stylename="tablecontents", text="bad import")
            else:
                p = P(stylename="tablecontents", text="")

            tc.addElement(p)
            tr.addElement(tc)
            tc = TableCell(stylename="THstyle")
            tr.addElement(tc)

    tr = TableRow()
    table.addElement(tr)
    tr = TableRow()
    table.addElement(tr)
    tc = TableCell()
    tr.addElement(tc)
    p = P(stylename="tablecontents", text="Total compared bugs: " + str(total))
    tc.addElement(p)

    tr = TableRow()
    table.addElement(tr)
    tc = TableCell()
    tr.addElement(tc)
    p = P(stylename="tablecontents",
          text="Total number of regressions: " + str(totalRegressions))
    tc.addElement(p)

    tr = TableRow()
    table.addElement(tr)
    tc = TableCell()
    tr.addElement(tc)
    p = P(stylename="tablecontents",
          text="Total number of empty files: " + str(totalEmpty))
    tc.addElement(p)

    tr = TableRow()
    table.addElement(tr)
    tc = TableCell()
    tr.addElement(tc)
    p = P(stylename="tablecontents",
          text="Total number of Timeouts: " + str(totalTimeOut))
    tc.addElement(p)

    return table
Exemple #13
0
        'fontsize': "10pt",
        'fontweight': "bold",
        'color': "#000000"
    }))
cs4.addElement(
    TableCellProperties(backgroundcolor="#C0C0C0",
                        border="0.74pt solid #000000"))
textdoc.automaticstyles.addElement(cs4)

# Start the table, and describe the columns
table = Table(name="KeyMatrix")

for col in xrange(1, MSIZE + 1):
    # Create a column (same as <col> in HTML) Make all cells in column default to currency
    table.addElement(
        TableColumn(stylename=widewidth, defaultcellstylename="ce1"))

for row in xrange(1, MSIZE + 1):
    # Create a row (same as <tr> in HTML)
    tr = TableRow()
    table.addElement(tr)

    for col in xrange(1, MSIZE + 1):
        if (col == row):
            cell = TableCell(valuetype="string", stylename="cs1")
            cell.addElement(P(text=u"X"))  # The current displayed value
        elif (col < row):
            cell = TableCell(formula=u"=%s%s" % (lit(row), col),
                             valuetype="string",
                             stylename="cs2")
        else:
Exemple #14
0
def generate_odf_plan_document(plan_pk, file_path):
    # Neues Textdokument erstellen
    document = OpenDocumentText()

    #
    # Styles definieren
    #
    center_bold = Style(name="Center Bold", family="paragraph")
    center_bold.addElement(ParagraphProperties(textalign="center"))
    center_bold.addElement(TextProperties(fontweight="bold"))
    document.styles.addElement(center_bold)

    center = Style(name="Center", family="paragraph")
    center.addElement(ParagraphProperties(textalign="center"))
    document.styles.addElement(center)

    left = Style(name="Left", family="paragraph")
    left.addElement(ParagraphProperties(numberlines="false", linenumber="0", textalign="left"))
    document.styles.addElement(left)

    bold_style = Style(name="Bold", family="text")
    bold_style.addElement(TextProperties(fontweight="bold"))
    document.styles.addElement(bold_style)

    #
    # Breite der Spaleten in den Tabellen setzen
    #
    width_short = Style(name="Wshort", family="table-column")
    width_short.addElement(TableColumnProperties(columnwidth="3.0cm"))
    document.automaticstyles.addElement(width_short)

    width_medium = Style(name="Wmedium", family="table-column")
    width_medium.addElement(TableColumnProperties(columnwidth="4.0cm"))
    document.automaticstyles.addElement(width_medium)

    width_wide = Style(name="Wwide", family="table-column")
    width_wide.addElement(TableColumnProperties(columnwidth="10.59cm"))
    document.automaticstyles.addElement(width_wide)

    # Tabelle mit zwei schmalen und einer breiten Spalte erstellen
    table = Table()
    table.addElement(TableColumn(numbercolumnsrepeated=1, stylename=width_short))
    table.addElement(TableColumn(numbercolumnsrepeated=1, stylename=width_medium))
    table.addElement(TableColumn(numbercolumnsrepeated=1, stylename=width_wide))

    # Generiert eine Zeile in der Tabelle
    def generate_row(datetime, location, extra, acolytes):

        # Datum und Uhrzeit formatieren
        date_string = datetime.strftime("%d.%m.%Y")
        time_string = datetime.strftime("%H:%M")

        # Neue TableRow erstellen und einfügen
        row = TableRow()
        table.addElement(row)

        # Datum - Zeit Zelle anlegen
        date_time_cell = TableCell()
        date_time_cell.addElement(P(stylename=center, text=date_string))
        date_time_cell.addElement(P(stylename=center_bold, text=time_string))

        # Ort - Information Zelle anlegen
        location_extra_cell = TableCell()
        location_extra_cell.addElement(P(stylename=center_bold, text=location))
        location_extra_cell.addElement(P(stylename=center, text=extra))

        # Messdiener Zelle anlegen
        acolytes_cell = TableCell()

        # Messdiener nach Rolle sortiert auflisten
        for role_name in acolytes:
            p = P(stylename=left)
            p.addElement(Span(stylename=bold_style, text=f"{role_name}: "))
            p.addText(text=', '.join(acolytes[role_name]))
            acolytes_cell.addElement(p)

        # Zellen zur TableRow hinzufügen
        row.addElement(date_time_cell)
        row.addElement(location_extra_cell)
        row.addElement(acolytes_cell)

        # TableRow zurückgeben
        return row

    # Durch die Messen nach Zeit sortiert iterieren
    for mass in Mass.objects.filter(plan=plan_pk).order_by('time'):
        # Acolyte dict mit einer leeren Liste als default value anlegen
        acolytes_list = defaultdict(list)

        # Durch die MassAcolyteRoles nach Rolle sortiert iterieren
        for mar in mass.massacolyterole_set.order_by('role__roleName'):
            # Wenn Messdiener keine Rolle hat "Messdiener" als Rolle eintragen
            role = "Messdiener"

            # Wenn Messdiener Rolle hat, dann zur Liste der Messdiener dieser Rolle hinzufügen
            if mar.role is not None:
                role = mar.role.roleName

            # Acolyte Namen setzen. Wenn extra Wert hat, dann in Klammern dahinter setzen
            acolyte_name = f"{mar.acolyte.firstName} {mar.acolyte.lastName}"

            if mar.acolyte.extra:
                acolyte_name = f"{mar.acolyte.firstName} {mar.acolyte.lastName} ({mar.acolyte.extra})"

            acolytes_list[role].append(acolyte_name)

        # Zeit der Messe zur lokalen Zeit konvertieren
        utc = mass.time.replace(tzinfo=pytz.UTC)
        localtime = utc.astimezone(timezone.get_current_timezone())

        # Row generieren und zur Tabelle hinzufügen
        table.addElement(generate_row(
            localtime,
            mass.location.locationName,
            mass.extra,
            acolytes_list
        ))

        # Leere Row für die Übersicht einfügen
        table.addElement(TableRow())

    # Tabelle zum Dokument hinzufügen
    document.text.addElement(table)

    # Dokument speichern
    document.save(file_path)
Exemple #15
0
def write_sheet():
    wide = Style(name="Wide", family="table-column")
    wide.addElement(TableColumnProperties(columnwidth="10cm"))
    ods.automaticstyles.addElement(wide)
    table.addElement(TableColumn(stylename='Wide'))
    ods.spreadsheet.addElement(table)
    def create_column(self, **kwargs):
        column = TableColumn(**kwargs)

        self._table.addElement(column)
Exemple #17
0
def colloscope_odf(request, classe):
	"""
	Affichage du colloscope d'une classe au format OpenDocument
	"""
	semaines = classe.semaine_set.order_by('debut')
	creneaux = classe.creneau_set.order_by('enseignement', 'jour', 'debut')
	colles = classe.colle_set.filter(semaine__in=semaines,
			creneau__in=creneaux)

	# On crée le dictionnaire qui à chaque créneau puis à chaque semaine
	# associe les groupes de colle
	colloscope = defaultdict(lambda: defaultdict(list))
	for colle in colles:
		colloscope[colle.creneau][colle.semaine].append(colle)

	ods = OpenDocumentSpreadsheet()
	# Styles
	style_entete = Style(parent=ods.automaticstyles,
			name='cell_entete', family='table-cell')
	TextProperties(parent=style_entete, fontweight='bold')
	style_col_semaine = Style(parent=ods.automaticstyles,
			name='col_semaine', family='table-column')
	TableColumnProperties(parent=style_col_semaine, columnwidth='1cm')
	style_col_matiere = Style(parent=ods.automaticstyles,
			name='col_matiere', family='table-column')
	TableColumnProperties(parent=style_col_matiere, columnwidth='5cm')
	style_col_colleur = Style(parent=ods.automaticstyles,
			name='col_colleur', family='table-column')
	TableColumnProperties(parent=style_col_colleur, columnwidth='5cm')
	style_col_salle = Style(parent=ods.automaticstyles,
			name='col_salle', family='table-column')
	TableColumnProperties(parent=style_col_salle, columnwidth='2cm')

	table = Table(name=str(classe), parent=ods.spreadsheet)

	# Ajout des colonnes d'en-tête fixes
	entetes_fixes = ("ID", "Matière", "Colleur", "Jour", "Horaire", "Salle")
	table.addElement(TableColumn(stylename=style_col_semaine)) # ID
	table.addElement(TableColumn(stylename=style_col_matiere)) # Matière
	table.addElement(TableColumn(stylename=style_col_colleur)) # Colleur
	table.addElement(TableColumn()) # Jour
	table.addElement(TableColumn()) # Horaire
	table.addElement(TableColumn(stylename=style_col_salle)) # Salle

	# Ajout des colonnes d'en-tête des semaines
	for _ in semaines:
		table.addElement(TableColumn(stylename=style_col_semaine))

	# Container pour les lignes d'en-tête
	th = TableHeaderRows(parent=table)
	# Ligne d'en-tête avec les semestres au-dessus des semaines
	tr = TableRow(parent=th)
	for entete in entetes_fixes:
		P(parent=TableCell(parent=tr, valuetype='string',
			numberrowsspanned=2, numbercolumnsspanned=1,
			stylename=style_entete), text=entete)

	# On doit savoir combien de semaines se trouvent sur chaque période
	# pour afficher les en-têtes sur le bon nombre de colonnes
	nb_semaines = dict([
		(
			periode[0],
			0,
		)
		for periode in constantes.PERIODE_CHOICES
	])
	for semaine in semaines:
		nb_semaines[semaine.periode] += 1

	# Insertion des titres des périodes
	for periode_id, periode_nom in constantes.PERIODE_CHOICES:
		if nb_semaines[periode_id] > 0:
			P(parent=TableCell(parent=tr, valuetype='string',
				numbercolumnsspanned=nb_semaines[periode_id],
				numberrowsspanned=1,
				stylename=style_entete), text=periode_nom.capitalize())
			CoveredTableCell(parent=tr,
					numbercolumnsrepeated=nb_semaines[periode_id] - 1)

	tr = TableRow(parent=th)
	# Ligne d'en-tête avec seulement les semaines
	# On doit placer des cellules vides pour les case d'en-tête situées
	# avant les semaines
	CoveredTableCell(parent=tr, numbercolumnsrepeated=len(entetes_fixes))
	# Puis on ajoute les semaines
	for semaine in semaines:
		P(parent=TableCell(parent=tr, valuetype='string',
			stylename=style_entete), text=semaine.numero)

	# Colles par créneau
	for creneau in creneaux:
		tr = TableRow(parent=table)
		P(parent=TableCell(parent=tr, valuetype='float', value=creneau.pk),
			text=creneau.pk)
		P(parent=TableCell(parent=tr, valuetype='string'),
				text=creneau.matiere)
		P(parent=TableCell(parent=tr, valuetype='string'),
				text=creneau.colleur)
		P(parent=TableCell(parent=tr, valuetype='string'),
				text=creneau.get_jour_display())
		P(parent=TableCell(parent=tr, valuetype='time',
				timevalue=creneau.debut.strftime("PT%HH%MM%SS")),
				text=creneau.debut.strftime("%H:%M"))
		P(parent=TableCell(parent=tr, valuetype='string'),
				text=creneau.salle)
		for semaine in semaines:
			groupes_texte = ','.join([str(c.groupe) for c in
					colloscope[creneau][semaine] if c.groupe])
			cell = TableCell(parent=tr)
			if groupes_texte:
				cell.valuetype="string"
				P(parent=cell, text=groupes_texte)

	return OdfResponse(ods, filename="colloscope_{}.ods".format(classe.slug))
Exemple #18
0
    def insert_table_(self, ar, column_names=None, table_width=180):
        # logger.info("20160330 insert_table(%s)", ar)
        ar.setup_from(self.ar)
        columns, headers, widths = ar.get_field_info(column_names)
        widths = map(int, widths)
        tw = sum(widths)
        # specifying relative widths doesn't seem to work (and that's
        # a pity because absolute widths requires us to know the
        # table_width).
        use_relative_widths = False
        if use_relative_widths:
            width_specs = ["%d*" % (w * 100 / tw) for w in widths]
        else:
            width_specs = ["%dmm" % (table_width * w / tw) for w in widths]

        doc = OpenDocumentText()

        def add_style(**kw):
            st = Style(**cleankw(kw))
            doc.styles.addElement(st)
            self.my_styles.append(st)
            return st

        table_style_name = str(ar.actor)
        st = add_style(name=table_style_name, family="table",
                       parentstylename="Default")
        st.addElement(
            TableProperties(align="margins", maybreakbetweenrows="0"))

        # create some *visible* styles

        st = add_style(name="Table Contents", family="paragraph",
                       parentstylename="Default")
        st.addElement(ParagraphProperties(numberlines="false",
                                          linenumber="0"))

        st = add_style(name="Number Cell", family="paragraph",
                       parentstylename="Table Contents")
        st.addElement(ParagraphProperties(
            numberlines="false",
            textalign="end", justifysingleword="true",
            linenumber="0"))

        dn = "Table Column Header"
        st = self.stylesManager.styles.getStyle(dn)
        if st is None:
            st = add_style(name=dn, family="paragraph",
                           parentstylename="Table Contents")
            st.addElement(
                ParagraphProperties(numberlines="false", linenumber="0"))
            st.addElement(TextProperties(fontweight="bold"))

        dn = "Bold Text"
        st = self.stylesManager.styles.getStyle(dn)
        if st is None:
            st = add_style(name=dn, family="text", parentstylename="Default")
            #~ st = add_style(name=dn, family="text")
            st.addElement(TextProperties(fontweight="bold"))

        if False:
            dn = "L1"
            st = self.stylesManager.styles.getStyle(dn)
            if st is None:
                st = ListStyle(name=dn)
                doc.styles.addElement(st)
                p = ListLevelProperties(
                    listlevelpositionandspacemode="label-alignment")
                st.addElement(p)
                #~ label-followed-by="listtab" text:list-tab-stop-position="1.27cm" fo:text-indent="-0.635cm" fo:margin-left="1.27cm"/>
                p.addElement(ListLevelLabelAlignment(labelfollowedby="listtab",
                                                     listtabstopposition="1.27cm",
                                                     textindent="-0.635cm",
                                                     marginleft="1.27cm"
                                                     ))
                self.my_styles.append(st)

                #~ list_style = add_style(name=dn, family="list")
                bullet = text.ListLevelStyleBullet(
                    level=1, stylename="Bullet_20_Symbols", bulletchar=u"•")
                #~ bullet = text.ListLevelStyleBullet(level=1,stylename="Bullet_20_Symbols",bulletchar=u"*")
                #~ <text:list-level-style-bullet text:level="1" text:style-name="Bullet_20_Symbols" text:bullet-char="•">
                st.addElement(bullet)

        # create some automatic styles

        def add_style(**kw):
            st = Style(**cleankw(kw))
            doc.automaticstyles.addElement(st)
            self.my_automaticstyles.append(st)
            return st

        cell_style = add_style(name="Lino Cell Style", family="table-cell")
        cell_style.addElement(TableCellProperties(
            paddingleft="1mm", paddingright="1mm",
            paddingtop="1mm", paddingbottom="0.5mm",
            border="0.002cm solid #000000"))

        header_row_style = add_style(
            name="Lino Header Row", family="table-row",
            parentstylename=cell_style)
        header_row_style.addElement(
            TableRowProperties(backgroundcolor="#eeeeee"))

        total_row_style = add_style(
            name="Lino Total Row", family="table-row",
            parentstylename=cell_style)
        total_row_style.addElement(
            TableRowProperties(backgroundcolor="#ffffff"))

        table = Table(name=table_style_name, stylename=table_style_name)
        table_columns = TableColumns()
        table.addElement(table_columns)
        table_header_rows = TableHeaderRows()
        table.addElement(table_header_rows)
        table_rows = TableRows()
        table.addElement(table_rows)

        # create table columns and automatic table-column styles
        for i, fld in enumerate(columns):
            #~ print 20120415, repr(fld.name)
            name = str(ar.actor) + "." + str(fld.name)
            cs = add_style(name=name, family="table-column")
            if use_relative_widths:
                cs.addElement(
                    TableColumnProperties(relcolumnwidth=width_specs[i]))
            else:
                cs.addElement(
                    TableColumnProperties(columnwidth=width_specs[i]))
            #~ cs.addElement(TableColumnProperties(useoptimalcolumnwidth='true'))
            #~ k = cs.getAttribute('name')
            #~ renderer.stylesManager.styles[k] = toxml(e)
            #~ doc.automaticstyles.addElement(cs)
            #~ self.my_automaticstyles.append(cs)
            table_columns.addElement(TableColumn(stylename=name))

        def fldstyle(fld):
            #~ if isinstance(fld,ext_store.VirtStoreField):
                #~ fld = fld.delegate
            if isinstance(fld, NumberFieldElement):
                return "Number Cell"
            return "Table Contents"

        def value2cell(ar, i, fld, val, style_name, tc):
            # if i == 0:
            #     logger.info("20160330a value2cell(%s, %s)", fld.__class__, val)
            txt = fld.value2html(ar, val)
            # if i == 0:
            #     logger.info("20160330b value2cell(%s)", E.tostring(txt))

            p = text.P(stylename=style_name)
            html2odf(txt, p)

            try:
                tc.addElement(p)
            except Exception as e:
                dd.logger.warning("20120614 addElement %s %s %r : %s",
                                  i, fld, val, e)
                #~ print 20120614, i, fld, val, e

            #~ yield P(stylename=tablecontents,text=text)

        # create header row
        #~ hr = TableRow(stylename=HEADER_ROW_STYLE_NAME)
        hr = TableRow(stylename=header_row_style)
        table_header_rows.addElement(hr)
        for h in headers:
        #~ for fld in fields:
            #~ tc = TableCell(stylename=CELL_STYLE_NAME)
            tc = TableCell(stylename=cell_style)
            tc.addElement(text.P(
                stylename="Table Column Header",
                #~ text=force_text(fld.field.verbose_name or fld.name)))
                text=force_text(h)))
            hr.addElement(tc)

        sums = [fld.zero for fld in columns]

        for row in ar.data_iterator:
            #~ for grp in ar.group_headers(row):
                #~ raise NotImplementedError()
            tr = TableRow()

            has_numeric_value = False

            for i, fld in enumerate(columns):

                #~ tc = TableCell(stylename=CELL_STYLE_NAME)
                tc = TableCell(stylename=cell_style)
                #~ if fld.field is not None:
                v = fld.field._lino_atomizer.full_value_from_object(row, ar)
                stylename = fldstyle(fld)
                if v is None:
                    tc.addElement(text.P(stylename=stylename, text=''))
                else:
                    value2cell(ar, i, fld, v, stylename, tc)

                    nv = fld.value2num(v)
                    if nv != 0:
                        sums[i] += nv
                        has_numeric_value = True
                    #~ sums[i] += fld.value2num(v)
                tr.addElement(tc)

            if has_numeric_value or not ar.actor.hide_zero_rows:
                table_rows.addElement(tr)

        if not ar.actor.hide_sums:
            if sums != [fld.zero for fld in columns]:
                tr = TableRow(stylename=total_row_style)
                table_rows.addElement(tr)
                sums = {fld.name: sums[i] for i, fld in enumerate(columns)}
                for i, fld in enumerate(columns):
                    tc = TableCell(stylename=cell_style)
                    stylename = fldstyle(fld)
                    p = text.P(stylename=stylename)
                    e = fld.format_sum(ar, sums, i)
                    html2odf(e, p)
                    tc.addElement(p)
                    #~ if len(txt) != 0:
                        #~ msg = "html2odf() returned "
                        #~ logger.warning(msg)
                    #~ txt = tuple(html2odf(fld.format_sum(ar,sums,i),p))
                    #~ assert len(txt) == 1
                    #~ tc.addElement(text.P(stylename=stylename,text=txt[0]))
                    tr.addElement(tc)

        doc.text.addElement(table)
        return toxml(table)
Exemple #19
0
    def initializeDocument(self):

        self.textdoc = OpenDocumentText()

        # Create a style for the table content. One we can modify
        # later in the word processor.
        self.tablecontents = Style(name="Table Contents", family="paragraph")
        self.tablecontents.addElement(
            ParagraphProperties(numberlines="false", linenumber="0"))
        self.textdoc.styles.addElement(self.tablecontents)

        # ----------------- define a few styles --------------------

        # a Bold style
        self.BoldStyle = Style(name="Bold", family="paragraph")
        self.BoldProp = TextProperties(fontweight="bold")
        self.BoldStyle.addElement(self.BoldProp)
        self.textdoc.automaticstyles.addElement(self.BoldStyle)

        # for Critical findings
        self.CriticalStyle = Style(name="Critical Findings",
                                   family="paragraph")
        self.CriticalStyleProp = TextProperties(fontweight="bold",
                                                color="#FF0000")
        self.CriticalStyle.addElement(self.CriticalStyleProp)
        self.textdoc.automaticstyles.addElement(self.CriticalStyle)

        # for High findings
        self.HighStyle = Style(name="High Findings", family="paragraph")
        self.HighStyleProp = TextProperties(fontweight="bold", color="#FF2400")
        self.HighStyle.addElement(self.HighStyleProp)
        self.textdoc.automaticstyles.addElement(self.HighStyle)

        # for Moderate findings
        self.ModerateStyle = Style(name="Moderate Findings",
                                   family="paragraph")
        self.ModerateStyleProp = TextProperties(fontweight="bold",
                                                color="#FF7F00")
        self.ModerateStyle.addElement(self.ModerateStyleProp)
        self.textdoc.automaticstyles.addElement(self.ModerateStyle)

        # for Low findings
        self.LowStyle = Style(name="Low Findings", family="paragraph")
        self.LowStyleProp = TextProperties(fontweight="bold", color="#007FFF")
        self.LowStyle.addElement(self.LowStyleProp)
        self.textdoc.automaticstyles.addElement(self.LowStyle)

        # for 'None' or 'Info' or 'Note' findings
        self.NoteStyle = Style(name="Note Findings", family="paragraph")
        self.NoteStyleProp = TextProperties(fontweight="bold")
        self.NoteStyle.addElement(self.NoteStyleProp)
        self.textdoc.automaticstyles.addElement(self.NoteStyle)

        # nessus plugins can give widely inconsistent ratings: serious/high, medium/moderate, info/note/none...
        self.riskFactorsDict = {
            'critical': self.CriticalStyle,
            'high': self.HighStyle,
            'serious': self.HighStyle,
            'medium': self.ModerateStyle,
            'moderate': self.ModerateStyle,
            'low': self.LowStyle,
            'info': self.NoteStyle,
            'note': self.NoteStyle,
            'none': self.NoteStyle
        }

        # Create automatic styles for the column widths.
        # We want two different widths, one in inches, the other one in metric.
        # ODF Standard section 15.9.1
        widthshort = Style(name="Wshort", family="table-column")
        widthshort.addElement(TableColumnProperties(columnwidth="1.7cm"))
        self.textdoc.automaticstyles.addElement(widthshort)

        widthwide = Style(name="Wwide", family="table-column")
        widthwide.addElement(TableColumnProperties(columnwidth="1.5in"))
        self.textdoc.automaticstyles.addElement(widthwide)

        # hard-code columns styles, per column
        widthwide = Style(name="Wwide", family="table-column")
        widthwide.addElement(TableColumnProperties(columnwidth="1.5in"))
        self.textdoc.automaticstyles.addElement(widthwide)

        # Start the table and describe the columns
        self.table = Table()
        if self.orderType == 'p':
            self.table.addElement(
                TableColumn(numbercolumnsrepeated=7, stylename=widthwide))

    # populate columns with headers...
        tr = TableRow()
        self.table.addElement(tr)

        # declare necessary vars
        tc1 = TableCell()
        tc2 = TableCell()
        tc3 = TableCell()
        tc4 = TableCell()
        tc5 = TableCell()
        tc6 = TableCell()
        tc7 = TableCell()
        addElem = lambda cell, text, s=self: cell.addElement(
            ODFParagraph(stylename=self.BoldStyle,
                         text=unicode(text, ODFTable.PWENC)))

        # Add Column 1: Finding Number
        addElem(tc1, 'Finding Number')
        tr.addElement(tc1)

        # Add Column 2: Vulnerability Name
        addElem(tc2, 'Vulnerability Name')
        tr.addElement(tc2)

        # Add Column 3: NIST 800-53 Mapping
        addElem(tc3, '800-53 Mapping')
        tr.addElement(tc3)

        # Add Column 4: Description
        addElem(tc4, 'Description')
        tr.addElement(tc4)

        # Add Column 5: Recommendation
        addElem(tc5, 'Recommendation')
        tr.addElement(tc5)

        # Add Column 6: CVE
        addElem(tc6, 'CVE')
        tr.addElement(tc6)

        # Add Column 6: Hosts Affected
        addElem(tc7, 'IP Address (Sample of hosts effected)')
        tr.addElement(tc7)
Exemple #20
0
normal_style = textdoc.getStyleByName('本文')
bold_style = textdoc.getStyleByName('強調')
center = textdoc.getStyleByName('置中本文')
centerbold = textdoc.getStyleByName('置中粗體')
center_huge = textdoc.getStyleByName('置中加大')
ver_center = textdoc.getStyleByName('垂直置中')

tbc2 = Style(name="tbc2", family="table-column", parentstylename=normal_style)
tbc2.addElement(TableColumnProperties(columnwidth="2cm"))
textdoc.automaticstyles.addElement(tbc2)
tbc5 = Style(name="tbc5", family="table-column", parentstylename=normal_style)
tbc5.addElement(TableColumnProperties(columnwidth="5cm"))
textdoc.automaticstyles.addElement(tbc5)

mmTable = Table()
mmTable.addElement(TableColumn(defaultcellstylename=ver_center,numbercolumnsrepeated=1,stylename=tbc2))
mmTable.addElement(TableColumn(defaultcellstylename=ver_center,numbercolumnsrepeated=1,stylename=tbc5))
mmTable.addElement(TableColumn(defaultcellstylename=ver_center,numbercolumnsrepeated=1,stylename=tbc2))
mmTable.addElement(TableColumn(defaultcellstylename=ver_center,numbercolumnsrepeated=1,stylename=tbc5))
tr = TableRow()
mmTable.addElement(tr)
put_tc("會議時間",center,tr)
put_tc('2020/4/28',ver_center,tr,3)
tr = TableRow()
mmTable.addElement(tr)
put_tc("會議地點",center,tr)
put_tc("10樓",ver_center,tr,3)
tr = TableRow()
mmTable.addElement(tr)
put_tc("主持人",center,tr)
put_tc("協理",ver_center,tr)
Exemple #21
0
 def _creerNColTableau(self, nb):
     return TableColumn(numbercolumnsrepeated=nb)
textdoc.styles.addElement(tablecontents)

# Create automatic styles for the column widths.
# We want two different widths, one in inches, the other one in metric.
# ODF Standard section 15.9.1
widthshort = Style(name="Wshort", family="table-column")
widthshort.addElement(TableColumnProperties(columnwidth="1.7cm"))
textdoc.automaticstyles.addElement(widthshort)

widthwide = Style(name="Wwide", family="table-column")
widthwide.addElement(TableColumnProperties(columnwidth="1.5in"))
textdoc.automaticstyles.addElement(widthwide)

# Start the table, and describe the columns
table = Table()
table.addElement(TableColumn(numbercolumnsrepeated=4, stylename=widthshort))
table.addElement(TableColumn(numbercolumnsrepeated=3, stylename=widthwide))

f = open('/etc/passwd')
for line in f:
    rec = line.strip().split(":")
    tr = TableRow()
    table.addElement(tr)
    for val in rec:
        tc = TableCell()
        tr.addElement(tc)
        p = P(stylename=tablecontents, text=unicode(val, PWENC))
        tc.addElement(p)

textdoc.text.addElement(table)
textdoc.save("passwd.odt")
Exemple #23
0
def par_classe(classes, fileout):
    ods = OpenDocumentSpreadsheet()

    style_civilite = Style(parent=ods.automaticstyles,
                           name='col_civilite',
                           family='table-column')
    TableColumnProperties(parent=style_civilite, columnwidth='1cm')

    style_nom = Style(parent=ods.automaticstyles,
                      name='col_nom',
                      family='table-column')
    TableColumnProperties(parent=style_nom, columnwidth='4.5cm')

    style_date = Style(parent=ods.automaticstyles,
                       name='col_date',
                       family='table-column')
    TableColumnProperties(parent=style_date, columnwidth='3.2cm')

    style_internat = Style(parent=ods.automaticstyles,
                           name='col_internat',
                           family='table-column')
    TableColumnProperties(parent=style_internat, columnwidth='3.2cm')

    style_classe = Style(parent=ods.automaticstyles,
                         name='col_classe',
                         family='table-column')
    TableColumnProperties(parent=style_classe, columnwidth='3.2cm')

    style_etat_voeu = Style(parent=ods.automaticstyles,
                            name='col_etat_voeu',
                            family='table-column')
    TableColumnProperties(parent=style_etat_voeu, columnwidth='4cm')

    style_titre = Style(parent=ods.automaticstyles,
                        name='cell_titre',
                        family='table-cell')
    TextProperties(parent=style_titre, fontweight='bold', fontsize='14pt')
    ParagraphProperties(parent=style_titre, textalign='center')

    style_ligne_titre = Style(parent=ods.automaticstyles,
                              name='ligne_titre',
                              family='table-row')
    TableRowProperties(parent=style_ligne_titre, rowheight='8mm')

    style_entete = Style(parent=ods.automaticstyles,
                         name='cell_entete',
                         family='table-cell')
    TextProperties(parent=style_entete, fontweight='bold')

    number_style_date_format = odf.number.DateStyle(parent=ods.automaticstyles,
                                                    name='date_number')
    odf.number.Day(parent=number_style_date_format, style='long')
    odf.number.Text(parent=number_style_date_format, text="/")
    odf.number.Month(parent=number_style_date_format, style='long')
    odf.number.Text(parent=number_style_date_format, text="/")
    odf.number.Year(parent=number_style_date_format, style='long')
    style_date_format = Style(parent=ods.automaticstyles,
                              name='cell_date',
                              family='table-cell',
                              datastylename=number_style_date_format)

    for classe in classes:
        table = Table(name=str(classe))
        table.addElement(TableColumn(stylename=style_civilite))  # Sexe
        table.addElement(TableColumn(stylename=style_nom))  # Nom
        table.addElement(TableColumn(stylename=style_nom))  # Prénom
        table.addElement(
            TableColumn(stylename=style_date))  # Date de naissance
        table.addElement(TableColumn(stylename=style_internat))  # Internat
        table.addElement(TableColumn(stylename=style_etat_voeu))  # État vœu
        table.addElement(TableColumn(stylename=style_nom))  # E-mail
        table.addElement(TableColumn(stylename=style_nom))  # Téléphone
        table.addElement(TableColumn(stylename=style_nom))  # Mobile

        # En-tête de la feuille
        tr = TableRow(parent=table, stylename=style_ligne_titre)
        cell = TableCell(parent=tr,
                         numbercolumnsspanned=9,
                         numberrowsspanned=1,
                         valuetype='string',
                         stylename=style_titre)
        cell.addElement(P(text=str(classe)))
        CoveredTableCell(parent=tr, numbercolumnsrepeated=8)

        tr = TableRow(parent=table)
        TableCell(parent=tr)  # Sexe
        P(parent=TableCell(parent=tr,
                           valuetype='string',
                           stylename=style_entete),
          text="Nom")
        P(parent=TableCell(parent=tr,
                           valuetype='string',
                           stylename=style_entete),
          text="Prénom")
        P(parent=TableCell(parent=tr,
                           valuetype='string',
                           stylename=style_entete),
          text="Date de naissance")
        P(parent=TableCell(parent=tr,
                           valuetype='string',
                           stylename=style_entete),
          text="Internat")
        P(parent=TableCell(parent=tr,
                           valuetype='string',
                           stylename=style_entete),
          text="État Parcoursup")
        P(parent=TableCell(parent=tr,
                           valuetype='string',
                           stylename=style_entete),
          text="E-mail")
        P(parent=TableCell(parent=tr,
                           valuetype='string',
                           stylename=style_entete),
          text="Téléphone")
        P(parent=TableCell(parent=tr,
                           valuetype='string',
                           stylename=style_entete),
          text="Mobile")

        for etudiant in classe.admissions().order_by('nom'):
            tr = TableRow()
            table.addElement(tr)

            TableCell(parent=tr, valuetype='string').addElement(
                P(text=etudiant.get_sexe_display()))

            TableCell(parent=tr,
                      valuetype='string').addElement(P(text=etudiant.nom))

            TableCell(parent=tr,
                      valuetype='string').addElement(P(text=etudiant.prenom))

            cell = TableCell(valuetype='date',
                             datevalue=str(etudiant.date_naissance),
                             stylename=style_date_format)
            cell.addElement(P(text=etudiant.date_naissance))
            tr.addElement(cell)

            cell = TableCell(valuetype='string')
            if etudiant.proposition_actuelle.internat:
                cell.addElement(P(text="Interne"))
            tr.addElement(cell)

            TableCell(parent=tr, valuetype='string').addElement(
                P(text=etudiant.proposition_actuelle.get_etat_display()))

            TableCell(parent=tr,
                      valuetype='string').addElement(P(text=etudiant.email))
            TableCell(parent=tr, valuetype='string').addElement(
                P(text=etudiant.telephone))
            TableCell(parent=tr, valuetype='string').addElement(
                P(text=etudiant.telephone_mobile))

        ods.spreadsheet.addElement(table)

    # Liste générale pour l'infirmerie
    table = Table(name="Infirmerie")
    ods.spreadsheet.addElement(table)
    table.addElement(TableColumn(stylename=style_civilite))  # Sexe
    table.addElement(TableColumn(stylename=style_nom))  # Nom
    table.addElement(TableColumn(stylename=style_nom))  # Prénom
    table.addElement(TableColumn(stylename=style_classe))  # Classe
    table.addElement(TableColumn(stylename=style_date))  # Date de naissance
    table.addElement(TableColumn(stylename=style_internat))  # Internat

    # En-tête de la feuille
    tr = TableRow(parent=table, stylename=style_ligne_titre)
    cell = TableCell(parent=tr,
                     numbercolumnsspanned=9,
                     numberrowsspanned=1,
                     valuetype='string',
                     stylename=style_titre)
    cell.addElement(P(text="Liste de tous les étudiants admis"))
    tr = TableRow(parent=table)
    TableCell(parent=tr)  # Sexe
    P(parent=TableCell(parent=tr, valuetype='string', stylename=style_entete),
      text="Nom")
    P(parent=TableCell(parent=tr, valuetype='string', stylename=style_entete),
      text="Prénom")
    P(parent=TableCell(parent=tr, valuetype='string', stylename=style_entete),
      text="Classe")
    P(parent=TableCell(parent=tr, valuetype='string', stylename=style_entete),
      text="Date de naissance")
    P(parent=TableCell(parent=tr, valuetype='string', stylename=style_entete),
      text="Internat")

    for etudiant in Etudiant.objects.filter(
            proposition_actuelle__isnull=False,
            proposition_actuelle__date_demission__isnull=True).order_by(
                'nom', 'prenom'):

        tr = TableRow(parent=table)

        TableCell(parent=tr, valuetype='string').addElement(
            P(text=etudiant.get_sexe_display()))

        TableCell(parent=tr,
                  valuetype='string').addElement(P(text=etudiant.nom))

        TableCell(parent=tr,
                  valuetype='string').addElement(P(text=etudiant.prenom))

        TableCell(parent=tr, valuetype='string').addElement(
            P(text=str(etudiant.proposition_actuelle.classe)))

        cell = TableCell(valuetype='date',
                         datevalue=str(etudiant.date_naissance),
                         stylename=style_date_format)
        cell.addElement(P(text=etudiant.date_naissance))
        tr.addElement(cell)

        cell = TableCell(valuetype='string')
        if etudiant.proposition_actuelle.internat:
            cell.addElement(P(text="Interne"))
        tr.addElement(cell)

    ods.write(fileout)
Exemple #24
0
def do_args(doc, args):
    if args is None:
        return

    table = Table(name="Table 1")
    table.addElement(
        TableColumn(numbercolumnsrepeated='3', stylename='TableAutoWidth'))

    tr = TableRow(stylename='TableAutoWidth')
    table.addElement(tr)

    tc = TableCell(valuetype="string", stylename='Table Heading')
    tc.addElement(P(text='Name'))
    tr.addElement(tc)

    tc = TableCell(valuetype="string", stylename='Table Heading')
    tc.addElement(P(text='Type'))
    tr.addElement(tc)

    tc = TableCell(valuetype="string", stylename='Table Heading')
    tc.addElement(P(text='Description'))
    tr.addElement(tc)

    for t in args.findall('arg'):
        tr = TableRow(stylename='TableAutoWidth')
        table.addElement(tr)

        # Name.
        tc = TableCell(valuetype="string", stylename='Table Contents')
        tc.addElement(P(text=t.attrib['name']))
        tr.addElement(tc)

        # Type.
        tc = TableCell(valuetype="string", stylename='Table Contents')
        tname = t.attrib['type'].strip()
        if tname == 'List':
            refs = []

            for subtype in t.findall('types/type'):
                stname = subtype.attrib['name']
                ref = BookmarkRef(referenceformat='text', refname=stname)
                ref.addText(stname)
                refs.append(ref)

            if len(refs) == 1:
                c = P(text='List of ')
                c.addElement(refs[0])
                tc.addElement(c)
            else:
                c = P(text='List of: ')
                tc.addElement(c)

                lst = List()
                for r in refs:
                    item_p = P()
                    item_p.addElement(r)
                    item = ListItem()
                    item.addElement(item_p)
                    lst.addElement(item)
                tc.addElement(lst)

        else:
            ref = BookmarkRef(referenceformat='text', refname=tname)
            ref.addText(tname)
            c = P()
            c.addElement(ref)
            tc.addElement(c)

        tr.addElement(tc)

        # Description.
        tc = TableCell(valuetype="string", stylename='Table Contents')
        tr.addElement(tc)
        desc = t.find('doc').text
        if 'value' in t.attrib:
            desc += 'This argument has a fixed value of %s.' % t.attrib['value']
        tc.addElement(P(text=desc))

        lst = do_values(doc, t.find('values'))
        if lst is not None:
            tc.addElement(lst)

    doc.text.addElement(table)
Exemple #25
0
link = A(type="simple",href="http://www.flickr.com/services/api", 
text="http://www.flickr.com/services/api")
p.addElement(link)

textdoc.text.addElement(p)

# add the table
"""
<table:table-column table:number-columns-repeated="3"/>
"""

textdoc.text.addElement(H(outlinelevel=1,text='A Table (Heading 1)'))

table = Table(name="Table 1")

table.addElement(TableColumn(numbercolumnsrepeated="3"))

# first row
tr = TableRow()
table.addElement(tr)
tc = TableCell(valuetype="string")
tc.addElement(P(text='Website'))
tr.addElement(tc)
tc = TableCell(valuetype="string")
tc.addElement(P(text='Description'))
tr.addElement(tc)
tc = TableCell(valuetype="string")
tc.addElement(P(text='URL'))
tr.addElement(tc)

# second row
Exemple #26
0
	def save(self, filename, i_max = None, j_max = None):
		''' save table in ods format '''
		
		if not i_max: i_max = self.table.i_max
		if not j_max: j_max = self.table.j_max
		
		# update cells text
		self.table.updateTable(i_max, j_max)
		
		# create new odf spreadsheet
		odfdoc = OpenDocumentSpreadsheet()
		
		# set direction style
		rtl = Style(name = "dir", family = "table")
		if self.table.direction == 'rtl':
			rtl.addElement(TableProperties(writingmode="rl-tb"))
		odfdoc.automaticstyles.addElement(rtl)
		
		# create the table
		table = Table(name = "sheet 1", stylename = 'dir')
		
		# default style
		ts = Style(name = "ts", family = "table-cell")
		ts.addElement(TextProperties(fontfamily = SodsCell().font_family, fontsize = SodsCell().font_size))
		odfdoc.styles.addElement(ts)
		
		# create columns
		for j in range(1, j_max):
			colname = "col" + str(j)
			c = self.table.getCellAt(0, j)
			width = c.column_width
			cs = Style(name = colname, family = "table-column")
			cs.addElement(TableColumnProperties(columnwidth = width, breakbefore = "auto"))
			odfdoc.automaticstyles.addElement(cs)

			table.addElement(TableColumn(stylename = colname, defaultcellstylename = "ts"))
			
		# make sure values are up to date
		# loop and update the cells value
		for i in range(1, i_max):
			# create new ods row
			tr = TableRow()
			table.addElement(tr)
			
			# create default data styles for dates and numbers
			ncs = NumberStyle(name="ncs")
			ncs.addElement(Number(decimalplaces="2", minintegerdigits="1", grouping="true"))
			odfdoc.styles.addElement(ncs)
			
			ncs2 = NumberStyle(name="ncs2")
			ncs2.addElement(Number(decimalplaces="0", minintegerdigits="1", grouping="false"))
			odfdoc.styles.addElement(ncs2)
			
			dcs = DateStyle(name="dcs")
			dcs.addElement(Year(style='long'))
			dcs.addElement(Text(text = '-'))
			dcs.addElement(Month(style='long'))
			dcs.addElement(Text(text = '-'))
			dcs.addElement(Day(style='long'))
			odfdoc.styles.addElement(dcs)
			
			for j in range(1, j_max):
				# update the cell text and condition
				cell = self.table.encodeColName(j) + str(i)
				c = self.table.getCellAt(i, j)
				
				# chose datastylename
				if c.value_type == 'date':
					datastylename = "dcs"
				else:
					if c.format == "":
						datastylename = "ncs2"
					if c.format == "#,##0.00":
						datastylename = "ncs"
					
				# get cell style id
				if (c.condition):
					style_id = (datastylename + c.color + c.font_size + c.font_family + 
						c.background_color + c.border_top + c.border_bottom + 
						c.border_left + c.border_right + 
						c.condition_color + c.condition_background_color)
				else:
					style_id = (datastylename + c.color + c.font_size + c.font_family + 
						c.background_color + c.border_top + c.border_bottom + 
						c.border_left + c.border_right)
				
				# set ods style
				style_name = self.getStyle(c, cell, datastylename, style_id, odfdoc)
				
				# create new ods cell
				if (c.formula and c.formula[0] == '=' and c.formula[:4] != '=uni'):
					if self.table.isFloat(c.value):
						tc = TableCell(valuetype = c.value_type, 
							formula = c.formula, value = float(c.value), stylename = style_name)
					else:
						tc = TableCell(valuetype = c.value_type, 
							formula = c.formula, 
							value = 0, stylename = style_name)
				elif (c.value_type == 'date'):
					tc = TableCell(valuetype = c.value_type, 
						datevalue = c.date_value, stylename = style_name)
				elif (c.value_type == 'float') and self.table.isFloat(c.value):
					tc = TableCell(valuetype = c.value_type, 
						value = float(c.value), stylename = style_name)
				else:
					tc = TableCell(valuetype = 'string', stylename = style_name)
				
				# set ods text
				tc.addElement(P(text = str(escape(c.text), 'utf-8')))
				
				tr.addElement(tc)

		odfdoc.spreadsheet.addElement(table)
		odfdoc.save(filename)
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
Exemple #28
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)
Exemple #29
0
ns2.addElement(Number(decimalplaces="2", minintegerdigits="1",
                      grouping="true"))
ns2.addElement(Map(condition="value()>=0", applystylename="positive-AUD"))
textdoc.styles.addElement(ns2)

# Create automatic style for the price cells.
moneycontents = Style(name="ce1",
                      family="table-cell",
                      parentstylename=tablecontents,
                      datastylename="main-AUD")
textdoc.automaticstyles.addElement(moneycontents)

# Start the table, and describe the columns
table = Table(name="Currency colours")
# Create a column (same as <col> in HTML) Make all cells in column default to currency
table.addElement(TableColumn(stylename=widewidth, defaultcellstylename="ce1"))
# Create a row (same as <tr> in HTML)
tr = TableRow()
table.addElement(tr)
# Create a cell with a negative value. It should show as red.
cell = TableCell(valuetype="currency", currency="AUD", value="-125")
cell.addElement(P(text=u"$-125.00"))  # The current displayed value
tr.addElement(cell)

# Create a row (same as <tr> in HTML)
tr = TableRow()
table.addElement(tr)
# Create another cell but with a positive value. It should show in black
cell = TableCell(valuetype="currency", currency="AUD", value="123")
cell.addElement(P(text=u"$123.00"))  # The current displayed value
tr.addElement(cell)
Exemple #30
0
ParagraphProperties(parent=tablecontents, numberlines='false', linenumber='0')
TextProperties(parent=tablecontents, fontweight='bold')

# Create automatic styles for the column widths.
# We want two different widths, one in inches, the other one in metric.
# ODF Standard section 15.9.1
widthshort = Style(parent=textdoc.automaticstyles,
                   name='Wshort',
                   family='table-column')
TableColumnProperties(parent=widthshort, columnwidth='1.7cm')

widthwide = Style(parent=textdoc.automaticstyles,
                  name='Wwide',
                  family='table-column')
TableColumnProperties(parent=widthwide, columnwidth='1.5in')

# Start the table, and describe the columns
table = Table(parent=textdoc.spreadsheet, name='Password')
TableColumn(parent=table, numbercolumnsrepeated=4, stylename=widthshort)
TableColumn(parent=table, numbercolumnsrepeated=3, stylename=widthwide)

with open('/etc/passwd') as f:
    for line in f:
        rec = line.strip().split(':')
        tr = TableRow(parent=table)
        for val in rec:
            tc = TableCell(parent=tr)
            p = P(parent=tc, stylename=tablecontents, text=val)

textdoc.save('passwd.ods')