Esempio n. 1
0
def set_cell_margins(cell: _Cell, **kwargs):
    """
    cell:  actual cell instance you want to modify

    usage:

        set_cell_margins(cell, top=50, start=50, bottom=50, end=50)

    provided values are in twentieths of a point (1/1440 of an inch).
    read more here: http://officeopenxml.com/WPtableCellMargins.php
    """
    tc = cell._tc
    # accesses the actual element
    tcPr = tc.get_or_add_tcPr()
    # print(dir(tc))
    # i think access the table paragraph element
    tcMar = OxmlElement('w:tcMar')
    # access the table cell margin element

    for m in [
        "top",
        "start",
        "bottom",
        "end",
    ]:
        if m in kwargs:
            node = OxmlElement("w:{}".format(m))
            # w:top
            node.set(qn('w:w'), str(kwargs.get(m)))
            # w:w set kwargs[0]
            node.set(qn('w:type'), 'dxa')
            # w:type set 'dxa'
            tcMar.append(node)

    tcPr.append(tcMar)
Esempio n. 2
0
 def set_table_header_bg_color(cell):
     tc = cell._tc
     tbl_cell_properties = tc.get_or_add_tcPr()
     cl_shading = OxmlElement('w:shd')
     cl_shading.set(qn('w:fill'), "ffffff")
     tbl_cell_properties.append(cl_shading)
     return cell
Esempio n. 3
0
def set_cell_margins(cell: _Cell, **kwargs):
    """
    cell:  actual cell instance you want to modify

    usage:

        set_cell_margins(cell, top=50, start=50, bottom=50, end=50)

    provided values are in twentieths of a point (1/1440 of an inch).
    read more here: http://officeopenxml.com/WPtableCellMargins.php
    """
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()
    tcMar = OxmlElement('w:tcMar')

    for m in [
            "top",
            "start",
            "bottom",
            "end",
    ]:
        if m in kwargs:
            node = OxmlElement("w:{}".format(m))
            node.set(qn('w:w'), str(kwargs.get(m)))
            node.set(qn('w:type'), 'dxa')
            tcMar.append(node)

    tcPr.append(tcMar)
Esempio n. 4
0
    def add_oval_shape(self, fill_hex_color=None):
        """
        https://python-docx.readthedocs.io/en/latest/user/shapes.html
        https://docs.microsoft.com/en-us/windows/win32/vml/web-workshop---specs---standards----how-to-use-vml-on-web-pages
        """
        fill_hex_color = fill_hex_color or '#ffffff'
        color = fill_hex_color
        if '#' != color[0]:
            color = '#' + color

        pict = OxmlElement('w:pict')
        nsmap = dict(v='urn:schemas-microsoft-com:vml')
        oval_attrs = dict(
            id=str(uuid4()),
            style=
            'width:12pt;height:12pt;z-index:-251658240;mso-position-vertical:top;mso-position-horizontal:left',
            fillcolor=color,
        )
        oval = oxml_parser.makeelement('{%s}%s' % (nsmap['v'], 'oval'),
                                       attrib=oval_attrs,
                                       nsmap=nsmap)

        border_attrs = dict(color='gray', joinstyle='round', endcap='flat')
        stroke = oxml_parser.makeelement('{%s}%s' % (nsmap['v'], 'stroke'),
                                         attrib=border_attrs,
                                         nsmap=nsmap)
        oval.append(stroke)
        pict.append(oval)
        self.ref._element.append(pict)
Esempio n. 5
0
def set_cell_margins(cell: _Cell, **kwargs):
    ''' Set cell margins. Provided values are in twentieths of a point (1/1440 of an inch).
        ---
        Args:
          - cell:  actual cell instance you want to modify
          - kwargs: a dict with keys: top, bottom, start, end
        
        Usage:
          - set_cell_margins(cell, top=50, start=50, bottom=50, end=50)
        
        Read more: 
          - https://blog.csdn.net/weixin_44312186/article/details/104944773
          - http://officeopenxml.com/WPtableCellMargins.php
    '''
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()
    tcMar = OxmlElement('w:tcMar')

    for m in ['top', 'start', 'bottom', 'end']:
        if m in kwargs:
            node = OxmlElement("w:{}".format(m))
            node.set(qn('w:w'), str(kwargs.get(m)))
            node.set(qn('w:type'), 'dxa')
            tcMar.append(node)

    tcPr.append(tcMar)
Esempio n. 6
0
def add_table_cell_margins(table, **kwargs):
    """
    table:  actual table instance you want to modify

    usage:

        set_table_cell_margins(table, top=50, bottom=50, start=50, end=50)

    provided values are in twentieths of a point (1/1440 of an inch).
    """
    tblPr = table._tblPr
    tblCellMar = OxmlElement('w:tblCellMar')

    for m in [
            "top",
            "bottom",
            "start",
            "end",
    ]:
        if m in kwargs:
            node = OxmlElement("w:{}".format(m))
            # w:top
            node.set(qn('w:w'), str(kwargs.get(m)))
            # w:w set kwargs[0]
            node.set(qn('w:type'), 'dxa')
            # w:type set 'dxa'
            tblCellMar.append(node)

    tblPr.append(tblCellMar)
Esempio n. 7
0
def rotate_text(cell: _Cell, direction: str):
    # direction: tbRl -- top to bottom, btLr -- bottom to top
    assert direction in ("tbRl", "btLr")
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()
    textDirection = OxmlElement('w:textDirection')
    textDirection.set(qn('w:val'), direction)  # btLr tbRl
    tcPr.append(textDirection)
Esempio n. 8
0
def set_repeat_table_header(row):
    ''' set repeat table row on every new page
    '''
    tr = row._tr
    trPr = tr.get_or_add_trPr()
    tblHeader = OxmlElement('w:tblHeader')
    tblHeader.set(qn('w:val'), "true")
    trPr.append(tblHeader)
    return row
Esempio n. 9
0
    def format(self) -> None:
        # center table within the page
        self.alignment = WD_TABLE_ALIGNMENT.CENTER

        # set column width for the patient details
        # 3cm is a good default width to fit dob and age on one line
        for cell in self.columns[1].cells:
            cell.width = Cm(3)

        # format the rows and cells
        for row in self.rows:
            # format the column headers and set header row to repeat
            if row.cells[0].text.lower() == "bed":
                for cell in row.cells:
                    for paragraph in cell.paragraphs:
                        for run in paragraph.runs:
                            run.underline = True
                tr = row._tr
                trPr = tr.get_or_add_trPr()
                tblHeader = OxmlElement("w:tblHeader")
                tblHeader.set(qn("w:val"), "true")
                trPr.append(tblHeader)

            # format the ward headers
            if row.cells[0].text == row.cells[1].text:
                shading_elm = parse_xml(f'<w:shd {nsdecls("w")} w:fill="EEEEEE"/>')
                for cell in row.cells:
                    cell._tc.get_or_add_tcPr().append(shading_elm)
                    # keep this header row on the same page as the next row
                    for paragraph in cell.paragraphs:
                        paragraph.paragraph_format.keep_with_next = True
                if "birthday" in row.cells[0].text:
                    for cell in row.cells:
                        for para in cell.paragraphs:
                            for run in para.runs:
                                run.italic = True

            # format new patients as bold
            if row._index in self._new_patient_indices:
                for cell in row.cells:
                    for para in cell.paragraphs:
                        for run in para.runs:
                            run.bold = True

            # format all cells in the table
            for cell in row.cells:
                cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
                for paragraph in cell.paragraphs:
                    formatter = paragraph.paragraph_format
                    formatter.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
                    formatter.space_before = Pt(2)
                    formatter.space_after = Pt(2)

            # prevent table rows from splitting across page breaks
            no_split = parse_xml(f"<w:cantSplit {nsdecls('w')}/>")
            row._tr.get_or_add_trPr().append(no_split)
Esempio n. 10
0
def add_bgcolor(cell, element):
    '''
    Adds a background (fill) colour to the given cell based on given element.
    '''
    if element.background_color:
        tc = cell._tc
        tcPr = tc.get_or_add_tcPr()
        tcShd = OxmlElement('w:shd')
        tcShd.set(qn('w:fill'), element.background_color)
        tcPr.append(tcShd)
Esempio n. 11
0
def set_cell_border(cell, **kwargs):
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()

    # check for tag existnace, if none found, then create one
    tcBorders = tcPr.first_child_found_in("w:tcBorders")
    if tcBorders is None:
        tcBorders = OxmlElement('w:tcBorders')
        tcPr.append(tcBorders)

    # list over all available tags
    for edge in ('start', 'top', 'end', 'bottom', 'insideH', 'insideV'):
        edge_data = kwargs.get(edge)
        if edge_data:
            tag = 'w:{}'.format(edge)

            # check for tag existnace, if none found, then create one
            element = tcBorders.find(qn(tag))
            if element is None:
                element = OxmlElement(tag)
                tcBorders.append(element)

            # looks like order of attributes is important
            for key in ["sz", "val", "color", "space", "shadow"]:
                if key in edge_data:
                    element.set(qn('w:{}'.format(key)), str(edge_data[key]))
Esempio n. 12
0
def set_character_scaling(p_run, scale: float = 1.0):
    ''' Set character spacing: scaling. Font | Advanced | Character Spacing | Scaling.
        ---
        Args:
          - p_run: docx.text.run.Run, proxy object wrapping <w:r> element
          - scale: scaling factor
    '''
    # get or create run properties
    properties = p_run._element.xpath('w:rPr')
    if not properties:
        property = OxmlElement('w:rPr')
        p_run._element.append(property)
    else:
        property = properties[0]

    # get or create character scaling under properties
    ws = property.xpath('w:w')
    if not ws:
        w = OxmlElement('w:w')
        property.append(w)
    else:
        w = ws[0]

    # set scaling: percentage
    w.set(qn('w:val'), str(100 * scale))
Esempio n. 13
0
def _set_cell_border(cell, **kwargs):
    """
    This function comes from
    https://www.jianshu.com/p/9ad7db7825ba
    """
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()

    tcBorders = tcPr.first_child_found_in("w:tcBorders")
    if tcBorders is None:
        tcBorders = OxmlElement('w:tcBorders')
        tcPr.append(tcBorders)

    for edge in ('left', 'top', 'right', 'bottom', 'insideH', 'insideV'):
        edge_data = kwargs.get(edge)
        if edge_data:
            tag = 'w:{}'.format(edge)

            element = tcBorders.find(qn(tag))
            if element is None:
                element = OxmlElement(tag)
                tcBorders.append(element)

            for key in ["sz", "val", "color", "space", "shadow"]:
                if key in edge_data:
                    element.set(qn('w:{}'.format(key)), str(edge_data[key]))
Esempio n. 14
0
def set_cell_border(cell: _Cell, **kwargs) -> None:
    """
    Set cell`s border of a Table cell instance.

    Usage:
    set_cell_border(
        cell,
        top={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
        bottom={"sz": 12, "color": "#00FF00", "val": "single"},
        start={"sz": 24, "val": "dashed", "shadow": "true"},
        end={"sz": 12, "val": "dashed"},
    )
    """
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()
    # check for tag existnace, if none found, then create one
    tcBorders = tcPr.first_child_found_in("w:tcBorders")
    if tcBorders is None:
        tcBorders = OxmlElement('w:tcBorders')
        tcPr.append(tcBorders)
    # list over all available tags
    for edge in ('start', 'top', 'end', 'bottom', 'insideH', 'insideV'):
        edge_data = kwargs.get(edge)
        if edge_data:
            tag = 'w:{}'.format(edge)
            # check for tag existnace, if none found, then create one
            element = tcBorders.find(qn(tag))
            if element is None:
                element = OxmlElement(tag)
                tcBorders.append(element)
            # looks like order of attributes is important
            for key in ["sz", "val", "color", "space", "shadow"]:
                if key in edge_data:
                    element.set(qn('w:{}'.format(key)), str(edge_data[key]))
Esempio n. 15
0
def set_cell_vertical_alignment(cell, align="center"):
    try:
        tc = cell._tc
        tcPr = tc.get_or_add_tcPr()
        tcValign = OxmlElement('w:vAlign')
        tcValign.set(qn('w:val'), align)
        tcPr.append(tcValign)
        return True
    except:
        traceback.print_exc()
        return False
Esempio n. 16
0
    def set_session_title_row(self, data):
        """This fills the workspace activity run with some text

        The run is empirically determined by studying the template.
        This is in a paragraph structure before the first table.
        Tou may want to change this if you change the template.
        Be aware that the paragraph is the 2nd only
        after this class is initialized.
        We have 2 fields to fill, all following the same principle
        """

        data["today"] = formatDate(self.request, date.today())

        for row, values in self.session_title_lookup.items():
            for num, settings in values.items():
                self.template.paragraphs[
                    self.paragraphs_offset +
                    row].runs[num].text = api.portal.translate(
                        settings["title"])
                _r = self.template.paragraphs[self.paragraphs_offset + row +
                                              1].runs[num]
                # This run should be set in two paragraphs (which appear clones)
                # One is inside a mc:Choice and the other is inside a mc:Fallback
                for subpar in _r._element.findall(".//%s" % qn("w:p")):
                    subpar.clear_content()
                    subrun = subpar.add_r()
                    subrun.text = data.get(settings.get("fname", ""), "") or ""
                    subrpr = subrun.get_or_add_rPr()
                    subrpr.get_or_add_rFonts()
                    subrpr.get_or_add_rFonts().set(qn("w:ascii"), "CorpoS")
                    subrpr.get_or_add_rFonts().set(qn("w:hAnsi"), "CorpoS")
                    subrpr.get_or_add_sz().set(qn("w:val"), "28")
                    szCs = OxmlElement("w:szCs")
                    szCs.attrib[qn("w:val")] = "14"
                    subrpr.append(szCs)

        if data["comment"]:
            self.template.paragraphs[self.paragraphs_offset + row +
                                     2].insert_paragraph_before(
                                         data["comment"])

        header = self.template.sections[self.sections_offset].header
        header.paragraphs[1].text = "{title}{extra}".format(
            title=data["survey_title"], extra=self.title_extra.strip())

        # And now we handle the document footer
        footer = self.template.sections[self.sections_offset].footer
        # The footer contains a table with 3 columns:
        # left we have a logo, center for text, right for the page numbers
        cell1, cell2, cell3 = footer.tables[0].row_cells(0)
        cell2.paragraphs[0].text = "{}".format(
            date.today().strftime("%d.%m.%Y"))
Esempio n. 17
0
def set_vertical_cell_direction(cell: _Cell, direction: str = 'btLr'):
    '''Set vertical text direction for cell.
        ---
        Args:
          - direction: tbRl -- top to bottom, btLr -- bottom to top
        
        https://stackoverflow.com/questions/47738013/how-to-rotate-text-in-table-cells
    '''
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()
    textDirection = OxmlElement('w:textDirection')
    textDirection.set(qn('w:val'), direction)  # btLr tbRl
    tcPr.append(textDirection)
Esempio n. 18
0
    def add_shading(self, hex_color_string=None):
        """
        XML representation
            <w:shd w:fill="1F497D"/>
        """
        hex_color_string = hex_color_string or '#888888'
        if '#' in hex_color_string:
            hex_color_string = hex_color_string[1:]

        rPr = self.ref._element.get_or_add_rPr()
        ele = OxmlElement('w:shd')
        ele.set(qn('w:fill'), hex_color_string)
        rPr.append(ele)
Esempio n. 19
0
 def _coloring_cells(self, cell, condition):
     if condition == 'Critical':
         color = '#960000'
     elif condition == 'High':
         color = '#fa3434'
     elif condition == 'Medium':
         color = '#ffa929'
     else:
         color = 'ffff40'
     tcPr = cell._tc.get_or_add_tcPr()
     tcVAlign = OxmlElement("w:shd")
     tcVAlign.set(qn("w:fill"), color)
     tcPr.append(tcVAlign)
Esempio n. 20
0
def set_vertical_cell_direction(cell:_Cell, direction:str='btLr'):
    '''Set vertical text direction for cell.

    Reference:
        https://stackoverflow.com/questions/47738013/how-to-rotate-text-in-table-cells
    
    Args:
        direction (str): Either "tbRl" (top to bottom) or "btLr" (bottom to top).
    '''
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()
    textDirection = OxmlElement('w:textDirection')
    textDirection.set(qn('w:val'), direction)  # btLr tbRl
    tcPr.append(textDirection)
Esempio n. 21
0
def set_cell_margins(cell: _Cell, margins):
    """
    margins{top:, start:, bottom:, end:} sizes in Pt
    """
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()
    tcMar = OxmlElement('w:tcMar')

    for k, m in margins.items():
        node = OxmlElement(f'w:{k}')
        node.set(qn('w:w'), str(m))
        node.set(qn('w:type'), 'dxa')
        tcMar.append(node)

    tcPr.append(tcMar)
Esempio n. 22
0
def create_list(paragraph, list_type):
    p = paragraph._p  #access to xml paragraph element
    pPr = p.get_or_add_pPr()  #access paragraph properties
    numPr = OxmlElement('w:numPr')  #create number properties element
    numId = OxmlElement('w:numId')  #create numId element - sets bullet type
    numId.set(qn('w:val'), list_type)  #set list type/indentation
    numPr.append(numId)  #add bullet type to number properties list
    pPr.append(numPr)  #add number properties to paragraph
Esempio n. 23
0
 def put_korean_to_cell(self):
     for i, row in enumerate(self.tabel.rows):
         for j, cell in enumerate(row.cells):
             for paragraph in cell.paragraphs:
                 #####가운데 정렬!!
                 paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
                 index = i * self.width + j
                 if index < len(self.pics):
                     paragraph.add_run(self.korean[index])
                 #####상하 방향에서 가운데 정렬
                 tc = cell._tc
                 tcPr = tc.get_or_add_tcPr()
                 tcVAlign = OxmlElement('w:vAlign')
                 tcVAlign.set(qn('w:val'), "center")
                 tcPr.append(tcVAlign)
Esempio n. 24
0
 def put_pic_to_cell(self):
     for i, row in enumerate(self.tabel.rows):
         for j, cell in enumerate(row.cells):
             for paragraph in cell.paragraphs:
                 #####가운데 정렬!!
                 paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
                 index = i * self.width + j
                 if index < len(self.pics):
                     run = paragraph.add_run()
                     run.add_picture(self.pics[index], width=self.pic_width // 100 * 98, height=self.pic_height // 100 * 90)
                 #####상하 방향에서 가운데 정렬
                 tc = cell._tc
                 tcPr = tc.get_or_add_tcPr()
                 tcVAlign = OxmlElement('w:vAlign')
                 tcVAlign.set(qn('w:val'), "center")
                 tcPr.append(tcVAlign)
Esempio n. 25
0
def _insert_paragraph_after(paragraph):
    """Insert a new paragraph after the given paragraph."""
    new_p = OxmlElement("w:p")
    paragraph._p.addnext(new_p)
    new_para = Paragraph(new_p, paragraph._parent)

    return new_para
Esempio n. 26
0
 def it_adds_additional_namespace_declarations_when_supplied(self):
     ns1 = 'http://schemas.openxmlformats.org/drawingml/2006/main'
     ns2 = 'other'
     element = OxmlElement('a:foo', nsdecls={'a': ns1, 'x': ns2})
     assert len(element.nsmap.items()) == 2
     assert element.nsmap['a'] == ns1
     assert element.nsmap['x'] == ns2
Esempio n. 27
0
def preventDocumentBreak(document):
    tags = document.element.xpath('//w:tr')
    rows = len(tags)
    for row in range(0, rows):
        tag = tags[row]  # Specify which <w:r> tag you want
        child = OxmlElement('w:cantSplit')  # Create arbitrary tag
        tag.append(child)  # Append in the new tag
Esempio n. 28
0
def preventDocumentBreak(document):
    tags = document.element.xpath('//w:tr')
    rows = len(tags)
    for row in range(0, rows):
        tag = tags[row]
        child = OxmlElement('w:cantSplit')
        tag.append(child)
Esempio n. 29
0
def _add_r_before(self):
    """
    Return a new ``<w:r>`` element inserted directly prior to this one.
    """
    new_r = OxmlElement('w:r')
    self.addprevious(new_r)
    return new_r
Esempio n. 30
0
def _add_r_after(self):
    """
    Return a new ``<w:r>`` element inserted directly prior to this one.
    """
    new_r = OxmlElement('w:r')
    self.addnext(new_r)
    return new_r
Esempio n. 31
0
def _add_caption(self, text, sequence_name=None):
    if not sequence_name:
        sequence_name = 'Figure'

    paragraph = self.insert_paragraph_after(text=None, style='Caption')
    paragraph.add_run('%s ' % sequence_name)
    new_fld = OxmlElement('w:fldSimple', attrs={
        qn('w:instr'): r' SEQ %s \* ARABIC ' % sequence_name
    })
    new_r = OxmlElement('w:r')
    new_r.add_t('0')
    new_fld.append(new_r)
    paragraph._p.append(new_fld)
    paragraph.add_run(": %s" % text)

    return paragraph
Esempio n. 32
0
  def __init__(self, fname, lname, cname, date, course, instructor, site, ta, completion):
    
    # Validate required arguments (note cname is not required (can be None))
    x = 0
    for arg in [fname, lname, date, course, instructor, site, ta, completion]:
      x+=1
      if arg is None:
        print(x)
        raise ValueError("Required argument: {} was None.".format(arg))
    
    # Reference only the arguments that will be used outside of the constructor
    self.fname = fname
    self.lname = lname
    self.cname = fname if cname is None else cname
    
    # Create the document
    self.document = Document()
    
    # Set margins
    section = self.document.sections[0]
    section.top_margin = Inches(1.5)
    section.bottom_margin = Inches(.75)
    section.left_margin = Inches(1)
    section.right_margin = Inches(1)
    
    # Title line at the very top
    title = self.document.add_paragraph()
    title.style.font.name = "Times New Roman" # All subsequent text is same font
    title.paragraph_format.space_after = Pt(11)
    title.paragraph_format.alignment = 1 # 1 means center
    title.add_run("CTY SUMMER PROGRAM FINAL EVALUATION").bold = True
        
    # Populate heading information including names, date, site, and course
    heading = self.document.add_paragraph()
    heading.paragraph_format.space_after = Pt(11)
    heading.paragraph_format.line_spacing = 1
    heading.add_run("Student: " + fname + ' ' + lname + '\t')
    heading.add_run("Date: " + date + '\n')
    heading.add_run("Course: " + course + '\t')
    heading.add_run("Instructor: " + instructor + '\n')
    heading.add_run("Site: " + site + '\t')
    heading.add_run("Teaching Assistant: " + ta)

    #TODO I guess there is better API support for tab stops in python-docx now
    # https://python-docx.readthedocs.io/en/latest/dev/analysis/features/text/tab-stops.html
    # Insert a tab stop in the middle of the page for proper heading format.
    # Simplified code from: github.com/python-openxml/python-docx/issues/206
    pTabs = OxmlElement('w:tabs')
    heading.paragraph_format.element.get_or_add_pPr().append(pTabs)
    tab_n = OxmlElement('w:tab')
    tab_n.set(qn('w:val'), "left")
    tab_n.set(qn('w:pos'), '5000')
    pTabs.append(tab_n)
    
    # Setup the intro paragraph
    introText = "Congratulations, " + self.cname + ', '
    introText += "on " + completion + ' ' + course + '. '
    introText += "Please see the enclosed course description for more detailed "
    introText += "information on the course."
    intro = self.document.add_paragraph(introText)
    intro.paragraph_format.space_after = Pt(11)
    
    intro.paragraph_format.line_spacing = 1
    # Keep track of the number of body paragraphs in the document
    self.numParagraphs = 0
Esempio n. 33
0
def create_list(paragraph, list_type):
    p = paragraph._p #access to xml paragraph element
    pPr = p.get_or_add_pPr() #access paragraph properties
    numPr = OxmlElement('w:numPr') #create number properties element
    numId = OxmlElement('w:ilvl') #create numId element - sets bullet type
    numId.set(qn('w:val'), '1') #set list type/indentation
    numPr.append(numId) #add bullet type to number properties list
    numId = OxmlElement('w:numId') #create numId element - sets bullet type
    numId.set(qn('w:val'), str(list_type+1))
    numPr.append(numId) #add bullet type to number properties list
    pPr.append(numPr) #add number properties to paragraph
Esempio n. 34
0
def saveDoc(self, py):
    """" формирование документа"""
    self.py = py
    document = docx.Document()
    sections = document.sections
    section = sections[0]
    section.left_margin = Inches(1)
    section.right_margin = Inches(0.65)
    section.page_width = Inches(8.3)
    section.page_height = Inches(11.7)

    styles = document.styles
    styles["List Number"].font.name = "Calibri"
    styles["Normal"].font.name = "Calibri"

    style = styles.add_style('table_z', WD_STYLE_TYPE.PARAGRAPH)
    style.base_style = styles['Normal']

    style = styles["table_z"]
    style.font.bold = True

    style = styles.add_style('Code', WD_STYLE_TYPE.PARAGRAPH)
    style.base_style = styles['Normal']
    style.font.name = "Courier New"
    style.font.size = Pt(10)
    styles = document.styles
    style = styles["Code"]

    p = style._element.get_or_add_pPr()
    numPr = OxmlElement('w:shd')  # create number properties element
    numPr.set(qn('w:fill'), "FEF2E8")  # set list type/indentation
    p.append(numPr)

    style = styles.add_style('hyperlink', WD_STYLE_TYPE.CHARACTER)
    style.base_style = styles['Default Paragraph Font']
    style = styles['hyperlink']
    style.font._element.get_or_add_rPr()
    style.font._element.get_or_add_unhideWhenUsed()
    style.font._element.get_or_add_semiHidden()
    style.font._element.rPr.get_or_add_u()
    style.font._element.rPr.u.val = WD_UNDERLINE.SINGLE
    style.font._element.rPr.get_or_add_color()
    style.font._element.rPr.color.val = RGBColor(2, 3, 226)
    style.font._element.rPr.color.themeColor = MSO_THEME_COLOR.HYPERLINK

    h = document.add_header()
    hp = h.add_paragraph(text1 % (self.py.nameProject.itemText(self.py.nameProject.currentIndex()),
                                  self.py.numBid.text()))
    hp.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
    document.add_paragraph(u"Цель", style='table_z')
    document.add_paragraph(text2_0 % (self.py.nameProject.itemText(self.py.nameProject.currentIndex())))
    h = document.add_paragraph('', style='List Bullet 3')
    h.add_run(text2_1 % (self.py.numberBid.text())).style = styles['hyperlink']
    h.add_run(' - %s' % (self.py.specBid.text()))

    document.add_heading("Этап 1. Подготовка к публикации", level=2)
    document.add_paragraph(text3 % (self.py.timeIn.text(), self.py.timeOut.text(), self.py.dateIn.text()))
    make_table(document, self.py.tableView.model().cached, 0)
    document.add_paragraph()
    document.add_paragraph(text19_0)
    document.add_paragraph(text19_1)
    make_table(document, self.py.tableView.model().cached, 1)
    document.add_paragraph()
    document.add_paragraph(text20)
    document.add_paragraph()
    document.add_heading("Этап 2. Публикация изменений", level=2)
    document.add_paragraph()
    listSer = []
    listApp = []
    listVamish = []
    test = []
    if self.py.app1.text() != "":
        listSer = {self.py.app1.text(): self.py.ipAddress1.text()}
        listApp = [self.py.app1.text()]
        listVamish = [self.py.vamish1.text()]
        test = [self.py.test1.text()]
    if self.py.app2.text() != "":
        listSer[self.py.app2.text()] = self.py.ipAddress2.text()
        listApp.append(self.py.app2.text())
        listVamish.append(self.py.vamish2.text())
        test.append(self.py.test2.text())
    if self.py.app3.text() != "":
        listSer[self.py.app3.text()] = self.py.ipAddress3.text()
        listApp.append(self.py.app3.text())
        listVamish.append(self.py.vamish3.text())
        test.append(self.py.test3.text())
    if self.py.app4.text() != "":
        listSer[self.py.app4.text()] = self.py.ipAddress4.text()
        listApp.append(self.py.app4.text())
        listVamish.append(self.py.vamish4.text())
        test.append(self.py.test4.text())
    document.add_paragraph(text5 % ", ".join(i for i in listSer), style='List Number')
    for i in range(0, len(listApp)):
        if (len(listApp) - 1) == i:
            serverPer = 0
        else:
            serverPer = i + 1
        com1 = bashIPPost % (listSer.get(listApp[serverPer]), self.py.portApp.text(), listSer.get(listApp[i]))
        com2 = bashIPPre % (listSer.get(listApp[i]), self.py.portApp.text(), listSer.get(listApp[serverPer]))
        document.add_paragraph(text6 % (self.py.nameProject.itemText(self.py.nameProject.currentIndex()),
                                        listApp[i], listApp[serverPer]), style='List Number')
        document.add_paragraph("%s \n%s" % (com1, com2), style="Code")
        document.add_paragraph(text7 % (listApp[i], self.py.numberRev.text()), style='List Number')
        h = document.add_paragraph('svn switch ', style="Code")
        h.add_run(self.py.svn.text()).style = styles['hyperlink']
        h.add_run('\nsvn update')
        document.add_paragraph(text8 % (listApp[i]), style='List Number')
        document.add_paragraph("%s \n%s \n%s" % (text9, com2, com1), style="Code")
        if self.py.cache.isChecked():
            document.add_paragraph(text10 % (listVamish[i]), style='List Number')
            document.add_paragraph(self.py.comandCache.text(), style="Code")
        document.add_paragraph(text12, style='List Number')
        document.add_paragraph(text13_0, style='List Bullet')
        document.add_paragraph(text13_1, style='List Bullet')
        document.add_paragraph(text13_2, style='List Bullet')
        document.add_paragraph(text13_3, style='List Bullet')
        for j in (self.py.tableView.model().cached):
            if j[2]:
                h = document.add_paragraph(style='List Paragraph')
                create_list(h, i)
                h.add_run(j[6]).style = styles['hyperlink']
        document.add_paragraph(text14, style='List Number')
        document.add_paragraph(text17 % (test[i]), style="Code")
        s = ", ".join(c for c in listApp[0:i+1])
        document.add_paragraph(text15 % s, style='List Number')
    document.add_paragraph(text20, style="List Number")
    document.add_heading("Этап 3. Мониторинг работы", level=2)
    document.add_paragraph(text4)

    return document