Beispiel #1
0
class CT_OBJECT(BaseOxmlElement):
    """
    ``w:object``
    """
    _tag_seq = (
        'v:shapetype', 'v:shape', 'o:OLEObject'
    )
    shapetype = ZeroOrOne("v:shapetype", successors=_tag_seq[1:])
    shape = ZeroOrOne("v:shape", successors=_tag_seq[2:])
    oleobject = ZeroOrOne("o:OLEObject", successors=_tag_seq[3:])
    del _tag_seq
Beispiel #2
0
class CT_Settings(BaseOxmlElement):
    """`w:settings` element, root element for the settings part"""

    _tag_seq = (
        "w:writeProtection", "w:view", "w:zoom", "w:removePersonalInformation",
        "w:removeDateAndTime", "w:doNotDisplayPageBoundaries",
        "w:displayBackgroundShape", "w:printPostScriptOverText",
        "w:printFractionalCharacterWidth", "w:printFormsData", "w:embedTrueTypeFonts",
        "w:embedSystemFonts", "w:saveSubsetFonts", "w:saveFormsData", "w:mirrorMargins",
        "w:alignBordersAndEdges", "w:bordersDoNotSurroundHeader",
        "w:bordersDoNotSurroundFooter", "w:gutterAtTop", "w:hideSpellingErrors",
        "w:hideGrammaticalErrors", "w:activeWritingStyle", "w:proofState",
        "w:formsDesign", "w:attachedTemplate", "w:linkStyles",
        "w:stylePaneFormatFilter", "w:stylePaneSortMethod", "w:documentType",
        "w:mailMerge", "w:revisionView", "w:trackRevisions", "w:doNotTrackMoves",
        "w:doNotTrackFormatting", "w:documentProtection", "w:autoFormatOverride",
        "w:styleLockTheme", "w:styleLockQFSet", "w:defaultTabStop", "w:autoHyphenation",
        "w:consecutiveHyphenLimit", "w:hyphenationZone", "w:doNotHyphenateCaps",
        "w:showEnvelope", "w:summaryLength", "w:clickAndTypeStyle",
        "w:defaultTableStyle", "w:evenAndOddHeaders", "w:bookFoldRevPrinting",
        "w:bookFoldPrinting", "w:bookFoldPrintingSheets",
        "w:drawingGridHorizontalSpacing", "w:drawingGridVerticalSpacing",
        "w:displayHorizontalDrawingGridEvery", "w:displayVerticalDrawingGridEvery",
        "w:doNotUseMarginsForDrawingGridOrigin", "w:drawingGridHorizontalOrigin",
        "w:drawingGridVerticalOrigin", "w:doNotShadeFormData", "w:noPunctuationKerning",
        "w:characterSpacingControl", "w:printTwoOnOne", "w:strictFirstAndLastChars",
        "w:noLineBreaksAfter", "w:noLineBreaksBefore", "w:savePreviewPicture",
        "w:doNotValidateAgainstSchema", "w:saveInvalidXml", "w:ignoreMixedContent",
        "w:alwaysShowPlaceholderText", "w:doNotDemarcateInvalidXml",
        "w:saveXmlDataOnly", "w:useXSLTWhenSaving", "w:saveThroughXslt",
        "w:showXMLTags", "w:alwaysMergeEmptyNamespace", "w:updateFields",
        "w:hdrShapeDefaults", "w:footnotePr", "w:endnotePr", "w:compat", "w:docVars",
        "w:rsids", "m:mathPr", "w:attachedSchema", "w:themeFontLang",
        "w:clrSchemeMapping", "w:doNotIncludeSubdocsInStats",
        "w:doNotAutoCompressPictures", "w:forceUpgrade", "w:captions",
        "w:readModeInkLockDown", "w:smartTagType", "sl:schemaLibrary",
        "w:shapeDefaults", "w:doNotEmbedSmartTags", "w:decimalSymbol", "w:listSeparator"
    )
    evenAndOddHeaders = ZeroOrOne("w:evenAndOddHeaders", successors=_tag_seq[48:])
    del _tag_seq

    @property
    def evenAndOddHeaders_val(self):
        """value of `w:evenAndOddHeaders/@w:val` or |None| if not present."""
        evenAndOddHeaders = self.evenAndOddHeaders
        if evenAndOddHeaders is None:
            return False
        return evenAndOddHeaders.val

    @evenAndOddHeaders_val.setter
    def evenAndOddHeaders_val(self, value):
        if value in [None, False]:
            self._remove_evenAndOddHeaders()
        else:
            self.get_or_add_evenAndOddHeaders().val = value
Beispiel #3
0
class CT_Parent(BaseOxmlElement):
    """
    ``<w:parent>`` element, an invented element for use in testing.
    """
    eg_zooChoice = ZeroOrOneChoice((Choice('w:choice'), Choice('w:choice2')),
                                   successors=('w:oomChild', 'w:oooChild'))
    oomChild = OneOrMore('w:oomChild',
                         successors=('w:oooChild', 'w:zomChild', 'w:zooChild'))
    oooChild = OneAndOnlyOne('w:oooChild')
    zomChild = ZeroOrMore('w:zomChild', successors=('w:zooChild', ))
    zooChild = ZeroOrOne('w:zooChild', successors=())
    optAttr = OptionalAttribute('w:optAttr', ST_IntegerType)
    reqAttr = RequiredAttribute('reqAttr', ST_IntegerType)
class CT_RPr2(CT_RPr):
    """
    ``<w:rStyle>`` element, containing the properties for a style.
    """
    _color = ZeroOrOne('w:color')

    @property
    def color(self):
        color = self._color
        if color is None:
            return color
        return color.val

    @color.setter
    def color(self, color):
        if color is None:
            self._remove__color()
        elif self._color is None:
            self._add__color(val=color)
        else:
            self._color.val = color
Beispiel #5
0
class CT_CoreProperties(BaseOxmlElement):
    """
    ``<cp:coreProperties>`` element, the root element of the Core Properties
    part stored as ``/docProps/core.xml``. Implements many of the Dublin Core
    document metadata elements. String elements resolve to an empty string
    ('') if the element is not present in the XML. String elements are
    limited in length to 255 unicode characters.
    """
    category = ZeroOrOne('cp:category', successors=())
    contentStatus = ZeroOrOne('cp:contentStatus', successors=())
    created = ZeroOrOne('dcterms:created', successors=())
    creator = ZeroOrOne('dc:creator', successors=())
    description = ZeroOrOne('dc:description', successors=())
    identifier = ZeroOrOne('dc:identifier', successors=())
    keywords = ZeroOrOne('cp:keywords', successors=())
    language = ZeroOrOne('dc:language', successors=())
    lastModifiedBy = ZeroOrOne('cp:lastModifiedBy', successors=())
    lastPrinted = ZeroOrOne('cp:lastPrinted', successors=())
    modified = ZeroOrOne('dcterms:modified', successors=())
    revision = ZeroOrOne('cp:revision', successors=())
    subject = ZeroOrOne('dc:subject', successors=())
    title = ZeroOrOne('dc:title', successors=())
    version = ZeroOrOne('cp:version', successors=())

    _coreProperties_tmpl = (
        '<cp:coreProperties %s/>\n' % nsdecls('cp', 'dc', 'dcterms')
    )

    @classmethod
    def new(cls):
        """
        Return a new ``<cp:coreProperties>`` element
        """
        xml = cls._coreProperties_tmpl
        coreProperties = parse_xml(xml)
        return coreProperties

    @property
    def author_text(self):
        """
        The text in the `dc:creator` child element.
        """
        return self._text_of_element('creator')

    @author_text.setter
    def author_text(self, value):
        self._set_element_text('creator', value)

    @property
    def category_text(self):
        return self._text_of_element('category')

    @category_text.setter
    def category_text(self, value):
        self._set_element_text('category', value)

    @property
    def comments_text(self):
        return self._text_of_element('description')

    @comments_text.setter
    def comments_text(self, value):
        self._set_element_text('description', value)

    @property
    def contentStatus_text(self):
        return self._text_of_element('contentStatus')

    @contentStatus_text.setter
    def contentStatus_text(self, value):
        self._set_element_text('contentStatus', value)

    @property
    def created_datetime(self):
        return self._datetime_of_element('created')

    @created_datetime.setter
    def created_datetime(self, value):
        self._set_element_datetime('created', value)

    @property
    def identifier_text(self):
        return self._text_of_element('identifier')

    @identifier_text.setter
    def identifier_text(self, value):
        self._set_element_text('identifier', value)

    @property
    def keywords_text(self):
        return self._text_of_element('keywords')

    @keywords_text.setter
    def keywords_text(self, value):
        self._set_element_text('keywords', value)

    @property
    def language_text(self):
        return self._text_of_element('language')

    @language_text.setter
    def language_text(self, value):
        self._set_element_text('language', value)

    @property
    def lastModifiedBy_text(self):
        return self._text_of_element('lastModifiedBy')

    @lastModifiedBy_text.setter
    def lastModifiedBy_text(self, value):
        self._set_element_text('lastModifiedBy', value)

    @property
    def lastPrinted_datetime(self):
        return self._datetime_of_element('lastPrinted')

    @lastPrinted_datetime.setter
    def lastPrinted_datetime(self, value):
        self._set_element_datetime('lastPrinted', value)

    @property
    def modified_datetime(self):
        return self._datetime_of_element('modified')

    @modified_datetime.setter
    def modified_datetime(self, value):
        self._set_element_datetime('modified', value)

    @property
    def revision_number(self):
        """
        Integer value of revision property.
        """
        revision = self.revision
        if revision is None:
            return 0
        revision_str = revision.text
        try:
            revision = int(revision_str)
        except ValueError:
            # non-integer revision strings also resolve to 0
            revision = 0
        # as do negative integers
        if revision < 0:
            revision = 0
        return revision

    @revision_number.setter
    def revision_number(self, value):
        """
        Set revision property to string value of integer *value*.
        """
        if not isinstance(value, int) or value < 1:
            tmpl = "revision property requires positive int, got '%s'"
            raise ValueError(tmpl % value)
        revision = self.get_or_add_revision()
        revision.text = str(value)

    @property
    def subject_text(self):
        return self._text_of_element('subject')

    @subject_text.setter
    def subject_text(self, value):
        self._set_element_text('subject', value)

    @property
    def title_text(self):
        return self._text_of_element('title')

    @title_text.setter
    def title_text(self, value):
        self._set_element_text('title', value)

    @property
    def version_text(self):
        return self._text_of_element('version')

    @version_text.setter
    def version_text(self, value):
        self._set_element_text('version', value)

    def _datetime_of_element(self, property_name):
        element = getattr(self, property_name)
        if element is None:
            return None
        datetime_str = element.text
        try:
            return self._parse_W3CDTF_to_datetime(datetime_str)
        except ValueError:
            # invalid datetime strings are ignored
            return None

    def _get_or_add(self, prop_name):
        """
        Return element returned by 'get_or_add_' method for *prop_name*.
        """
        get_or_add_method_name = 'get_or_add_%s' % prop_name
        get_or_add_method = getattr(self, get_or_add_method_name)
        element = get_or_add_method()
        return element

    @classmethod
    def _offset_dt(cls, dt, offset_str):
        """
        Return a |datetime| instance that is offset from datetime *dt* by
        the timezone offset specified in *offset_str*, a string like
        ``'-07:00'``.
        """
        match = cls._offset_pattern.match(offset_str)
        if match is None:
            raise ValueError(
                "'%s' is not a valid offset string" % offset_str
            )
        sign, hours_str, minutes_str = match.groups()
        sign_factor = -1 if sign == '+' else 1
        hours = int(hours_str) * sign_factor
        minutes = int(minutes_str) * sign_factor
        td = timedelta(hours=hours, minutes=minutes)
        return dt + td

    _offset_pattern = re.compile(r'([+-])(\d\d):(\d\d)')

    @classmethod
    def _parse_W3CDTF_to_datetime(cls, w3cdtf_str):
        # valid W3CDTF date cases:
        # yyyy e.g. '2003'
        # yyyy-mm e.g. '2003-12'
        # yyyy-mm-dd e.g. '2003-12-31'
        # UTC timezone e.g. '2003-12-31T10:14:55Z'
        # numeric timezone e.g. '2003-12-31T10:14:55-08:00'
        templates = (
            '%Y-%m-%dT%H:%M:%S',
            '%Y-%m-%d',
            '%Y-%m',
            '%Y',
        )
        # strptime isn't smart enough to parse literal timezone offsets like
        # '-07:30', so we have to do it ourselves
        parseable_part = w3cdtf_str[:19]
        offset_str = w3cdtf_str[19:]
        dt = None
        for tmpl in templates:
            try:
                dt = datetime.strptime(parseable_part, tmpl)
            except ValueError:
                continue
        if dt is None:
            tmpl = "could not parse W3CDTF datetime string '%s'"
            raise ValueError(tmpl % w3cdtf_str)
        if len(offset_str) == 6:
            return cls._offset_dt(dt, offset_str)
        return dt

    def _set_element_datetime(self, prop_name, value):
        """
        Set date/time value of child element having *prop_name* to *value*.
        """
        if not isinstance(value, datetime):
            tmpl = (
                "property requires <type 'datetime.datetime'> object, got %s"
            )
            raise ValueError(tmpl % type(value))
        element = self._get_or_add(prop_name)
        dt_str = value.strftime('%Y-%m-%dT%H:%M:%SZ')
        element.text = dt_str
        if prop_name in ('created', 'modified'):
            # These two require an explicit 'xsi:type="dcterms:W3CDTF"'
            # attribute. The first and last line are a hack required to add
            # the xsi namespace to the root element rather than each child
            # element in which it is referenced
            self.set(qn('xsi:foo'), 'bar')
            element.set(qn('xsi:type'), 'dcterms:W3CDTF')
            del self.attrib[qn('xsi:foo')]

    def _set_element_text(self, prop_name, value):
        """Set string value of *name* property to *value*."""
        if not is_string(value):
            value = str(value)

        if len(value) > 255:
            tmpl = (
                "exceeded 255 char limit for property, got:\n\n'%s'"
            )
            raise ValueError(tmpl % value)
        element = self._get_or_add(prop_name)
        element.text = value

    def _text_of_element(self, property_name):
        """
        Return the text in the element matching *property_name*, or an empty
        string if the element is not present or contains no text.
        """
        element = getattr(self, property_name)
        if element is None:
            return ''
        if element.text is None:
            return ''
        return element.text
Beispiel #6
0
class CT_AppProperties(BaseOxmlElement):
    """
    ``<ap:Properties>`` element, the root element of the App Properties
    part stored as ``/docProps/app.xml``. Implements many of the Dublin App
    document metadata elements. String elements resolve to an empty string
    ('') if the element is not present in the XML. String elements are
    limited in length to 255 unicode characters.
    """
    template = ZeroOrOne('ap:Template', successors=())
    totaltime = ZeroOrOne('ap:TotalTime', successors=())
    pages = ZeroOrOne('ap:Pages', successors=())
    words = ZeroOrOne('ap:Words', successors=())
    characters = ZeroOrOne('ap:Characters', successors=())
    lines = ZeroOrOne('ap:Lines', successors=())
    company = ZeroOrOne('ap:Company', successors=())
    paragraphs = ZeroOrOne('ap:Paragraphs', successors=())
    version = ZeroOrOne('ap:AppVersion', successors=())

    _appProperties_tmpl = ('<ap:Properties %s/>\n' % nsdecls('ap'))

    @classmethod
    def new(cls):
        xml = cls._appProperties_tmpl
        appProperties = parse_xml(xml)
        return appProperties

    @property
    def template_text(self):
        return self._text_of_element('template')

    @template_text.setter
    def template_text(self, value):
        self._set_element_text('template', value)

    @property
    def total_time_text(self):
        return self._text_of_element('totaltime')

    @total_time_text.setter
    def total_time_text(self, value):
        self._set_element_text('totaltime', value)

    @property
    def pages_text(self):
        return self._text_of_element('pages')

    @pages_text.setter
    def pages_text(self, value):
        self._set_element_text('pages', value)

    @property
    def words_text(self):
        return self._text_of_element('words')

    @words_text.setter
    def words_text(self, value):
        self._set_element_text('words', value)

    @property
    def characters_text(self):
        return self._text_of_element('characters')

    @characters_text.setter
    def characters_text(self, value):
        self._set_element_text('characters', value)

    @property
    def lines_text(self):
        return self._text_of_element('lines')

    @lines_text.setter
    def lines_text(self, value):
        self._set_element_text('lines', value)

    @property
    def company_text(self):
        return self._text_of_element('company')

    @company_text.setter
    def company_text(self, value):
        self._set_element_text('company', value)

    @property
    def paragraphs_text(self):
        return self._text_of_element('paragraphs')

    @paragraphs_text.setter
    def paragraphs_text(self, value):
        self._set_element_text('paragraphs', value)

    @property
    def app_version_text(self):
        return self._text_of_element('version')

    @app_version_text.setter
    def app_version(self, value):
        self._set_element_text('version', value)

    def _datetime_of_element(self, property_name):
        element = getattr(self, property_name)
        if element is None:
            return None
        datetime_str = element.text
        try:
            return self._parse_W3CDTF_to_datetime(datetime_str)
        except ValueError:
            # invalid datetime strings are ignored
            return None

    def _get_or_add(self, prop_name):
        """
        Return element returned by 'get_or_add_' method for *prop_name*.
        """
        get_or_add_method_name = 'get_or_add_%s' % prop_name
        get_or_add_method = getattr(self, get_or_add_method_name)
        element = get_or_add_method()
        return element

    @classmethod
    def _offset_dt(cls, dt, offset_str):
        """
        Return a |datetime| instance that is offset from datetime *dt* by
        the timezone offset specified in *offset_str*, a string like
        ``'-07:00'``.
        """
        match = cls._offset_pattern.match(offset_str)
        if match is None:
            raise ValueError("'%s' is not a valid offset string" % offset_str)
        sign, hours_str, minutes_str = match.groups()
        sign_factor = -1 if sign == '+' else 1
        hours = int(hours_str) * sign_factor
        minutes = int(minutes_str) * sign_factor
        td = timedelta(hours=hours, minutes=minutes)
        return dt + td

    _offset_pattern = re.compile(r'([+-])(\d\d):(\d\d)')

    @classmethod
    def _parse_W3CDTF_to_datetime(cls, w3cdtf_str):
        # valid W3CDTF date cases:
        # yyyy e.g. '2003'
        # yyyy-mm e.g. '2003-12'
        # yyyy-mm-dd e.g. '2003-12-31'
        # UTC timezone e.g. '2003-12-31T10:14:55Z'
        # numeric timezone e.g. '2003-12-31T10:14:55-08:00'
        templates = (
            '%Y-%m-%dT%H:%M:%S',
            '%Y-%m-%d',
            '%Y-%m',
            '%Y',
        )
        # strptime isn't smart enough to parse literal timezone offsets like
        # '-07:30', so we have to do it ourselves
        parseable_part = w3cdtf_str[:19]
        offset_str = w3cdtf_str[19:]
        dt = None
        for tmpl in templates:
            try:
                dt = datetime.strptime(parseable_part, tmpl)
            except ValueError:
                continue
        if dt is None:
            tmpl = "could not parse W3CDTF datetime string '%s'"
            raise ValueError(tmpl % w3cdtf_str)
        if len(offset_str) == 6:
            return cls._offset_dt(dt, offset_str)
        return dt

    def _set_element_datetime(self, prop_name, value):
        """
        Set date/time value of child element having *prop_name* to *value*.
        """
        if not isinstance(value, datetime):
            tmpl = (
                "property requires <type 'datetime.datetime'> object, got %s")
            raise ValueError(tmpl % type(value))
        element = self._get_or_add(prop_name)
        dt_str = value.strftime('%Y-%m-%dT%H:%M:%SZ')
        element.text = dt_str
        if prop_name in ('created', 'modified'):
            # These two require an explicit 'xsi:type="dcterms:W3CDTF"'
            # attribute. The first and last line are a hack required to add
            # the xsi namespace to the root element rather than each child
            # element in which it is referenced
            self.set(qn('xsi:foo'), 'bar')
            element.set(qn('xsi:type'), 'dcterms:W3CDTF')
            del self.attrib[qn('xsi:foo')]

    def _set_element_text(self, prop_name, value):
        """Set string value of *name* property to *value*."""
        if not is_string(value):
            value = str(value)

        if len(value) > 255:
            tmpl = ("exceeded 255 char limit for property, got:\n\n'%s'")
            raise ValueError(tmpl % value)
        element = self._get_or_add(prop_name)
        element.text = value

    def _text_of_element(self, property_name):
        """
        Return the text in the element matching *property_name*, or an empty
        string if the element is not present or contains no text.
        """
        element = getattr(self, property_name)
        if element is None:
            return ''
        if element.text is None:
            return ''
        return element.text
Beispiel #7
0
class CT_SectPr(BaseOxmlElement):
    """`w:sectPr` element, the container element for section properties"""

    _tag_seq = (
        'w:footnotePr',
        'w:endnotePr',
        'w:type',
        'w:pgSz',
        'w:pgMar',
        'w:paperSrc',
        'w:pgBorders',
        'w:lnNumType',
        'w:pgNumType',
        'w:cols',
        'w:formProt',
        'w:vAlign',
        'w:noEndnote',
        'w:titlePg',
        'w:textDirection',
        'w:bidi',
        'w:rtlGutter',
        'w:docGrid',
        'w:printerSettings',
        'w:sectPrChange',
    )
    headerReference = ZeroOrMore("w:headerReference", successors=_tag_seq)
    footerReference = ZeroOrMore("w:footerReference", successors=_tag_seq)
    type = ZeroOrOne("w:type", successors=_tag_seq[3:])
    pgSz = ZeroOrOne("w:pgSz", successors=_tag_seq[4:])
    pgMar = ZeroOrOne("w:pgMar", successors=_tag_seq[5:])
    titlePg = ZeroOrOne("w:titlePg", successors=_tag_seq[14:])
    del _tag_seq

    def add_footerReference(self, type_, rId):
        """Return newly added CT_HdrFtrRef element of *type_* with *rId*.

        The element tag is `w:footerReference`.
        """
        footerReference = self._add_footerReference()
        footerReference.type_ = type_
        footerReference.rId = rId
        return footerReference

    def add_headerReference(self, type_, rId):
        """Return newly added CT_HdrFtrRef element of *type_* with *rId*.

        The element tag is `w:headerReference`.
        """
        headerReference = self._add_headerReference()
        headerReference.type_ = type_
        headerReference.rId = rId
        return headerReference

    @property
    def bottom_margin(self):
        """
        The value of the ``w:bottom`` attribute in the ``<w:pgMar>`` child
        element, as a |Length| object, or |None| if either the element or the
        attribute is not present.
        """
        pgMar = self.pgMar
        if pgMar is None:
            return None
        return pgMar.bottom

    @bottom_margin.setter
    def bottom_margin(self, value):
        pgMar = self.get_or_add_pgMar()
        pgMar.bottom = value

    def clone(self):
        """
        Return an exact duplicate of this ``<w:sectPr>`` element tree
        suitable for use in adding a section break. All rsid* attributes are
        removed from the root ``<w:sectPr>`` element.
        """
        clone_sectPr = deepcopy(self)
        clone_sectPr.attrib.clear()
        return clone_sectPr

    @property
    def footer(self):
        """
        The value of the ``w:footer`` attribute in the ``<w:pgMar>`` child
        element, as a |Length| object, or |None| if either the element or the
        attribute is not present.
        """
        pgMar = self.pgMar
        if pgMar is None:
            return None
        return pgMar.footer

    @footer.setter
    def footer(self, value):
        pgMar = self.get_or_add_pgMar()
        pgMar.footer = value

    def get_footerReference(self, type_):
        """Return footerReference element of *type_* or None if not present."""
        path = "./w:footerReference[@w:type='%s']" % WD_HEADER_FOOTER.to_xml(
            type_)
        footerReferences = self.xpath(path)
        if not footerReferences:
            return None
        return footerReferences[0]

    def get_headerReference(self, type_):
        """Return headerReference element of *type_* or None if not present."""
        matching_headerReferences = self.xpath(
            "./w:headerReference[@w:type='%s']" %
            WD_HEADER_FOOTER.to_xml(type_))
        if len(matching_headerReferences) == 0:
            return None
        return matching_headerReferences[0]

    @property
    def gutter(self):
        """
        The value of the ``w:gutter`` attribute in the ``<w:pgMar>`` child
        element, as a |Length| object, or |None| if either the element or the
        attribute is not present.
        """
        pgMar = self.pgMar
        if pgMar is None:
            return None
        return pgMar.gutter

    @gutter.setter
    def gutter(self, value):
        pgMar = self.get_or_add_pgMar()
        pgMar.gutter = value

    @property
    def header(self):
        """
        The value of the ``w:header`` attribute in the ``<w:pgMar>`` child
        element, as a |Length| object, or |None| if either the element or the
        attribute is not present.
        """
        pgMar = self.pgMar
        if pgMar is None:
            return None
        return pgMar.header

    @header.setter
    def header(self, value):
        pgMar = self.get_or_add_pgMar()
        pgMar.header = value

    @property
    def left_margin(self):
        """
        The value of the ``w:left`` attribute in the ``<w:pgMar>`` child
        element, as a |Length| object, or |None| if either the element or the
        attribute is not present.
        """
        pgMar = self.pgMar
        if pgMar is None:
            return None
        return pgMar.left

    @left_margin.setter
    def left_margin(self, value):
        pgMar = self.get_or_add_pgMar()
        pgMar.left = value

    @property
    def orientation(self):
        """
        The member of the ``WD_ORIENTATION`` enumeration corresponding to the
        value of the ``orient`` attribute of the ``<w:pgSz>`` child element,
        or ``WD_ORIENTATION.PORTRAIT`` if not present.
        """
        pgSz = self.pgSz
        if pgSz is None:
            return WD_ORIENTATION.PORTRAIT
        return pgSz.orient

    @orientation.setter
    def orientation(self, value):
        pgSz = self.get_or_add_pgSz()
        pgSz.orient = value

    @property
    def page_height(self):
        """
        Value in EMU of the ``h`` attribute of the ``<w:pgSz>`` child
        element, or |None| if not present.
        """
        pgSz = self.pgSz
        if pgSz is None:
            return None
        return pgSz.h

    @page_height.setter
    def page_height(self, value):
        pgSz = self.get_or_add_pgSz()
        pgSz.h = value

    @property
    def page_width(self):
        """
        Value in EMU of the ``w`` attribute of the ``<w:pgSz>`` child
        element, or |None| if not present.
        """
        pgSz = self.pgSz
        if pgSz is None:
            return None
        return pgSz.w

    @page_width.setter
    def page_width(self, value):
        pgSz = self.get_or_add_pgSz()
        pgSz.w = value

    @property
    def preceding_sectPr(self):
        """sectPr immediately preceding this one or None if this is the first."""
        # ---[1] predicate returns list of zero or one value---
        preceding_sectPrs = self.xpath("./preceding::w:sectPr[1]")
        return preceding_sectPrs[0] if len(preceding_sectPrs) > 0 else None

    def remove_footerReference(self, type_):
        """Return rId of w:footerReference child of *type_* after removing it."""
        footerReference = self.get_footerReference(type_)
        rId = footerReference.rId
        self.remove(footerReference)
        return rId

    def remove_headerReference(self, type_):
        """Return rId of w:headerReference child of *type_* after removing it."""
        headerReference = self.get_headerReference(type_)
        rId = headerReference.rId
        self.remove(headerReference)
        return rId

    @property
    def right_margin(self):
        """
        The value of the ``w:right`` attribute in the ``<w:pgMar>`` child
        element, as a |Length| object, or |None| if either the element or the
        attribute is not present.
        """
        pgMar = self.pgMar
        if pgMar is None:
            return None
        return pgMar.right

    @right_margin.setter
    def right_margin(self, value):
        pgMar = self.get_or_add_pgMar()
        pgMar.right = value

    @property
    def start_type(self):
        """
        The member of the ``WD_SECTION_START`` enumeration corresponding to
        the value of the ``val`` attribute of the ``<w:type>`` child element,
        or ``WD_SECTION_START.NEW_PAGE`` if not present.
        """
        type = self.type
        if type is None or type.val is None:
            return WD_SECTION_START.NEW_PAGE
        return type.val

    @start_type.setter
    def start_type(self, value):
        if value is None or value is WD_SECTION_START.NEW_PAGE:
            self._remove_type()
            return
        type = self.get_or_add_type()
        type.val = value

    @property
    def titlePg_val(self):
        """Value of `w:titlePg/@val` or |None| if not present"""
        titlePg = self.titlePg
        if titlePg is None:
            return False
        return titlePg.val

    @titlePg_val.setter
    def titlePg_val(self, value):
        if value in [None, False]:
            self._remove_titlePg()
        else:
            self.get_or_add_titlePg().val = value

    @property
    def top_margin(self):
        """
        The value of the ``w:top`` attribute in the ``<w:pgMar>`` child
        element, as a |Length| object, or |None| if either the element or the
        attribute is not present.
        """
        pgMar = self.pgMar
        if pgMar is None:
            return None
        return pgMar.top

    @top_margin.setter
    def top_margin(self, value):
        pgMar = self.get_or_add_pgMar()
        pgMar.top = value
class CT_TrPr(BaseOxmlElement):
    tblHeader = ZeroOrOne('w:tblHeader')
Beispiel #9
0
class CT_R2(CT_R):
    embed_object = ZeroOrOne('w:object')
    pict = ZeroOrOne('w:pict')