"""The |Section| object and related proxy classes."""from__future__importannotationsfromtypingimportTYPE_CHECKING,Iterator,List,Sequence,overloadfromdocx.blkcntnrimportBlockItemContainerfromdocx.enum.sectionimportWD_HEADER_FOOTERfromdocx.oxml.text.paragraphimportCT_Pfromdocx.parts.hdrftrimportFooterPart,HeaderPartfromdocx.sharedimportlazypropertyfromdocx.tableimportTablefromdocx.text.paragraphimportParagraphifTYPE_CHECKING:fromdocx.enum.sectionimportWD_ORIENTATION,WD_SECTION_STARTfromdocx.oxml.documentimportCT_Documentfromdocx.oxml.sectionimportCT_SectPrfromdocx.parts.documentimportDocumentPartfromdocx.parts.storyimportStoryPartfromdocx.sharedimportLength
[文档]classSection:"""Document section, providing access to section and page setup settings. Also provides access to headers and footers. """def__init__(self,sectPr:CT_SectPr,document_part:DocumentPart):super(Section,self).__init__()self._sectPr=sectPrself._document_part=document_part@propertydefbottom_margin(self)->Length|None:"""Read/write. Bottom margin for pages in this section, in EMU. `None` when no bottom margin has been specified. Assigning |None| removes any bottom-margin setting. """returnself._sectPr.bottom_margin@bottom_margin.setterdefbottom_margin(self,value:int|Length|None):self._sectPr.bottom_margin=value@propertydefdifferent_first_page_header_footer(self)->bool:"""True if this section displays a distinct first-page header and footer. Read/write. The definition of the first-page header and footer are accessed using :attr:`.first_page_header` and :attr:`.first_page_footer` respectively. """returnself._sectPr.titlePg_val@different_first_page_header_footer.setterdefdifferent_first_page_header_footer(self,value:bool):self._sectPr.titlePg_val=value@propertydefeven_page_footer(self)->_Footer:"""|_Footer| object defining footer content for even pages. The content of this footer definition is ignored unless the document setting :attr:`~.Settings.odd_and_even_pages_header_footer` is set True. """return_Footer(self._sectPr,self._document_part,WD_HEADER_FOOTER.EVEN_PAGE)@propertydefeven_page_header(self)->_Header:"""|_Header| object defining header content for even pages. The content of this header definition is ignored unless the document setting :attr:`~.Settings.odd_and_even_pages_header_footer` is set True. """return_Header(self._sectPr,self._document_part,WD_HEADER_FOOTER.EVEN_PAGE)@propertydeffirst_page_footer(self)->_Footer:"""|_Footer| object defining footer content for the first page of this section. The content of this footer definition is ignored unless the property :attr:`.different_first_page_header_footer` is set True. """return_Footer(self._sectPr,self._document_part,WD_HEADER_FOOTER.FIRST_PAGE)@propertydeffirst_page_header(self)->_Header:"""|_Header| object defining header content for the first page of this section. The content of this header definition is ignored unless the property :attr:`.different_first_page_header_footer` is set True. """return_Header(self._sectPr,self._document_part,WD_HEADER_FOOTER.FIRST_PAGE)
[文档]@lazypropertydeffooter(self)->_Footer:"""|_Footer| object representing default page footer for this section. The default footer is used for odd-numbered pages when separate odd/even footers are enabled. It is used for both odd and even-numbered pages otherwise. """return_Footer(self._sectPr,self._document_part,WD_HEADER_FOOTER.PRIMARY)
@propertydeffooter_distance(self)->Length|None:"""Distance from bottom edge of page to bottom edge of the footer. Read/write. |None| if no setting is present in the XML. """returnself._sectPr.footer@footer_distance.setterdeffooter_distance(self,value:int|Length|None):self._sectPr.footer=value@propertydefgutter(self)->Length|None:"""|Length| object representing page gutter size in English Metric Units. Read/write. The page gutter is extra spacing added to the `inner` margin to ensure even margins after page binding. Generally only used in book-bound documents with double-sided and facing pages. This setting applies to all pages in this section. """returnself._sectPr.gutter@gutter.setterdefgutter(self,value:int|Length|None):self._sectPr.gutter=value
[文档]@lazypropertydefheader(self)->_Header:"""|_Header| object representing default page header for this section. The default header is used for odd-numbered pages when separate odd/even headers are enabled. It is used for both odd and even-numbered pages otherwise. """return_Header(self._sectPr,self._document_part,WD_HEADER_FOOTER.PRIMARY)
@propertydefheader_distance(self)->Length|None:"""Distance from top edge of page to top edge of header. Read/write. |None| if no setting is present in the XML. Assigning |None| causes default value to be used. """returnself._sectPr.header@header_distance.setterdefheader_distance(self,value:int|Length|None):self._sectPr.header=value
[文档]defiter_inner_content(self)->Iterator[Paragraph|Table]:"""Generate each Paragraph or Table object in this `section`. Items appear in document order. """forelementinself._sectPr.iter_inner_content():yield(Paragraph(element,self)ifisinstance(element,CT_P)elseTable(element,self))
@propertydefleft_margin(self)->Length|None:"""|Length| object representing the left margin for all pages in this section in English Metric Units."""returnself._sectPr.left_margin@left_margin.setterdefleft_margin(self,value:int|Length|None):self._sectPr.left_margin=value@propertydeforientation(self)->WD_ORIENTATION:""":ref:`WdOrientation` member specifying page orientation for this section. One of ``WD_ORIENT.PORTRAIT`` or ``WD_ORIENT.LANDSCAPE``. """returnself._sectPr.orientation@orientation.setterdeforientation(self,value:WD_ORIENTATION|None):self._sectPr.orientation=value@propertydefpage_height(self)->Length|None:"""Total page height used for this section. This value is inclusive of all edge spacing values such as margins. Page orientation is taken into account, so for example, its expected value would be ``Inches(8.5)`` for letter-sized paper when orientation is landscape. """returnself._sectPr.page_height@page_height.setterdefpage_height(self,value:Length|None):self._sectPr.page_height=value@propertydefpage_width(self)->Length|None:"""Total page width used for this section. This value is like "paper size" and includes all edge spacing values such as margins. Page orientation is taken into account, so for example, its expected value would be ``Inches(11)`` for letter-sized paper when orientation is landscape. """returnself._sectPr.page_width@page_width.setterdefpage_width(self,value:Length|None):self._sectPr.page_width=value@propertydefpart(self)->StoryPart:returnself._document_part@propertydefright_margin(self)->Length|None:"""|Length| object representing the right margin for all pages in this section in English Metric Units."""returnself._sectPr.right_margin@right_margin.setterdefright_margin(self,value:Length|None):self._sectPr.right_margin=value@propertydefstart_type(self)->WD_SECTION_START:"""Type of page-break (if any) inserted at the start of this section. For exmple, ``WD_SECTION_START.ODD_PAGE`` if the section should begin on the next odd page, possibly inserting two page-breaks instead of one. """returnself._sectPr.start_type@start_type.setterdefstart_type(self,value:WD_SECTION_START|None):self._sectPr.start_type=value@propertydeftop_margin(self)->Length|None:"""|Length| object representing the top margin for all pages in this section in English Metric Units."""returnself._sectPr.top_margin@top_margin.setterdeftop_margin(self,value:Length|None):self._sectPr.top_margin=value
[文档]classSections(Sequence[Section]):"""Sequence of |Section| objects corresponding to the sections in the document. Supports ``len()``, iteration, and indexed access. """def__init__(self,document_elm:CT_Document,document_part:DocumentPart):super(Sections,self).__init__()self._document_elm=document_elmself._document_part=document_part@overloaddef__getitem__(self,key:int)->Section:...@overloaddef__getitem__(self,key:slice)->List[Section]:...def__getitem__(self,key:int|slice)->Section|List[Section]:ifisinstance(key,slice):return[Section(sectPr,self._document_part)forsectPrinself._document_elm.sectPr_lst[key]]returnSection(self._document_elm.sectPr_lst[key],self._document_part)def__iter__(self)->Iterator[Section]:forsectPrinself._document_elm.sectPr_lst:yieldSection(sectPr,self._document_part)def__len__(self)->int:returnlen(self._document_elm.sectPr_lst)
class_BaseHeaderFooter(BlockItemContainer):"""Base class for header and footer classes."""def__init__(self,sectPr:CT_SectPr,document_part:DocumentPart,header_footer_index:WD_HEADER_FOOTER,):self._sectPr=sectPrself._document_part=document_partself._hdrftr_index=header_footer_index@propertydefis_linked_to_previous(self)->bool:"""``True`` if this header/footer uses the definition from the prior section. ``False`` if this header/footer has an explicit definition. Assigning ``True`` to this property removes the header/footer definition for this section, causing it to "inherit" the corresponding definition of the prior section. Assigning ``False`` causes a new, empty definition to be added for this section, but only if no definition is already present. """# ---absence of a header/footer part indicates "linked" behavior---returnnotself._has_definition@is_linked_to_previous.setterdefis_linked_to_previous(self,value:bool)->None:new_state=bool(value)# ---do nothing when value is not being changed---ifnew_state==self.is_linked_to_previous:returnifnew_stateisTrue:self._drop_definition()else:self._add_definition()@propertydefpart(self)->HeaderPart|FooterPart:"""The |HeaderPart| or |FooterPart| for this header/footer. This overrides `BlockItemContainer.part` and is required to support image insertion and perhaps other content like hyperlinks. """# ---should not appear in documentation;# ---not an interface property, even though publicreturnself._get_or_add_definition()def_add_definition(self)->HeaderPart|FooterPart:"""Return newly-added header/footer part."""raiseNotImplementedError("must be implemented by each subclass")@propertydef_definition(self)->HeaderPart|FooterPart:"""|HeaderPart| or |FooterPart| object containing header/footer content."""raiseNotImplementedError("must be implemented by each subclass")def_drop_definition(self)->None:"""Remove header/footer part containing the definition of this header/footer."""raiseNotImplementedError("must be implemented by each subclass")@propertydef_element(self):"""`w:hdr` or `w:ftr` element, root of header/footer part."""returnself._get_or_add_definition().elementdef_get_or_add_definition(self)->HeaderPart|FooterPart:"""Return HeaderPart or FooterPart object for this section. If this header/footer inherits its content, the part for the prior header/footer is returned; this process continue recursively until a definition is found. If the definition cannot be inherited (because the header/footer belongs to the first section), a new definition is added for that first section and then returned. """# ---note this method is called recursively to access inherited definitions---# ---case-1: definition is not inherited---ifself._has_definition:returnself._definition# ---case-2: definition is inherited and belongs to second-or-later section---prior_headerfooter=self._prior_headerfooterifprior_headerfooter:returnprior_headerfooter._get_or_add_definition()# ---case-3: definition is inherited, but belongs to first section---returnself._add_definition()@propertydef_has_definition(self)->bool:"""True if this header/footer has a related part containing its definition."""raiseNotImplementedError("must be implemented by each subclass")@propertydef_prior_headerfooter(self)->_Header|_Footer|None:"""|_Header| or |_Footer| proxy on prior sectPr element. Returns None if this is first section. """raiseNotImplementedError("must be implemented by each subclass")
[文档]class_Footer(_BaseHeaderFooter):"""Page footer, used for all three types (default, even-page, and first-page). Note that, like a document or table cell, a footer must contain a minimum of one paragraph and a new or otherwise "empty" footer contains a single empty paragraph. This first paragraph can be accessed as `footer.paragraphs[0]` for purposes of adding content to it. Using :meth:`add_paragraph()` by itself to add content will leave an empty paragraph above the newly added one. """def_add_definition(self)->FooterPart:"""Return newly-added footer part."""footer_part,rId=self._document_part.add_footer_part()self._sectPr.add_footerReference(self._hdrftr_index,rId)returnfooter_part@propertydef_definition(self):"""|FooterPart| object containing content of this footer."""footerReference=self._sectPr.get_footerReference(self._hdrftr_index)# -- currently this is never called when `._has_definition` evaluates False --assertfooterReferenceisnotNonereturnself._document_part.footer_part(footerReference.rId)def_drop_definition(self):"""Remove footer definition (footer part) associated with this section."""rId=self._sectPr.remove_footerReference(self._hdrftr_index)self._document_part.drop_rel(rId)@propertydef_has_definition(self)->bool:"""True if a footer is defined for this section."""footerReference=self._sectPr.get_footerReference(self._hdrftr_index)returnfooterReferenceisnotNone@propertydef_prior_headerfooter(self):"""|_Footer| proxy on prior sectPr element or None if this is first section."""preceding_sectPr=self._sectPr.preceding_sectPrreturn(Noneifpreceding_sectPrisNoneelse_Footer(preceding_sectPr,self._document_part,self._hdrftr_index))
[文档]class_Header(_BaseHeaderFooter):"""Page header, used for all three types (default, even-page, and first-page). Note that, like a document or table cell, a header must contain a minimum of one paragraph and a new or otherwise "empty" header contains a single empty paragraph. This first paragraph can be accessed as `header.paragraphs[0]` for purposes of adding content to it. Using :meth:`add_paragraph()` by itself to add content will leave an empty paragraph above the newly added one. """def_add_definition(self):"""Return newly-added header part."""header_part,rId=self._document_part.add_header_part()self._sectPr.add_headerReference(self._hdrftr_index,rId)returnheader_part@propertydef_definition(self):"""|HeaderPart| object containing content of this header."""headerReference=self._sectPr.get_headerReference(self._hdrftr_index)# -- currently this is never called when `._has_definition` evaluates False --assertheaderReferenceisnotNonereturnself._document_part.header_part(headerReference.rId)def_drop_definition(self):"""Remove header definition associated with this section."""rId=self._sectPr.remove_headerReference(self._hdrftr_index)self._document_part.drop_header_part(rId)@propertydef_has_definition(self)->bool:"""True if a header is explicitly defined for this section."""headerReference=self._sectPr.get_headerReference(self._hdrftr_index)returnheaderReferenceisnotNone@propertydef_prior_headerfooter(self):"""|_Header| proxy on prior sectPr element or None if this is first section."""preceding_sectPr=self._sectPr.preceding_sectPrreturn(Noneifpreceding_sectPrisNoneelse_Header(preceding_sectPr,self._document_part,self._hdrftr_index))