# pyright: reportImportCycles=false# pyright: reportPrivateUsage=false"""|Document| and closely related objects."""from__future__importannotationsfromtypingimportIO,TYPE_CHECKING,Iterator,Listfromdocx.blkcntnrimportBlockItemContainerfromdocx.enum.sectionimportWD_SECTIONfromdocx.enum.textimportWD_BREAKfromdocx.sectionimportSection,Sectionsfromdocx.sharedimportElementProxy,EmuifTYPE_CHECKING:importdocx.typesastfromdocx.oxml.documentimportCT_Body,CT_Documentfromdocx.parts.documentimportDocumentPartfromdocx.settingsimportSettingsfromdocx.sharedimportLengthfromdocx.styles.styleimportParagraphStyle,_TableStylefromdocx.tableimportTablefromdocx.text.paragraphimportParagraph
[文档]classDocument(ElementProxy):"""WordprocessingML (WML) document. Not intended to be constructed directly. Use :func:`docx.Document` to open or create a document. """def__init__(self,element:CT_Document,part:DocumentPart):super(Document,self).__init__(element)self._element=elementself._part=partself.__body=None
[文档]defadd_heading(self,text:str="",level:int=1):"""Return a heading paragraph newly added to the end of the document. The heading paragraph will contain `text` and have its paragraph style determined by `level`. If `level` is 0, the style is set to `Title`. If `level` is 1 (or omitted), `Heading 1` is used. Otherwise the style is set to `Heading {level}`. Raises |ValueError| if `level` is outside the range 0-9. """ifnot0<=level<=9:raiseValueError("level must be in range 0-9, got %d"%level)style="Title"iflevel==0else"Heading %d"%levelreturnself.add_paragraph(text,style)
[文档]defadd_page_break(self):"""Return newly |Paragraph| object containing only a page break."""paragraph=self.add_paragraph()paragraph.add_run().add_break(WD_BREAK.PAGE)returnparagraph
[文档]defadd_paragraph(self,text:str="",style:str|ParagraphStyle|None=None)->Paragraph:"""Return paragraph newly added to the end of the document. The paragraph is populated with `text` and having paragraph style `style`. `text` can contain tab (``\\t``) characters, which are converted to the appropriate XML form for a tab. `text` can also include newline (``\\n``) or carriage return (``\\r``) characters, each of which is converted to a line break. """returnself._body.add_paragraph(text,style)
[文档]defadd_picture(self,image_path_or_stream:str|IO[bytes],width:int|Length|None=None,height:int|Length|None=None,):"""Return new picture shape added in its own paragraph at end of the document. The picture contains the image at `image_path_or_stream`, scaled based on `width` and `height`. If neither width nor height is specified, the picture appears at its native size. If only one is specified, it is used to compute a scaling factor that is then applied to the unspecified dimension, preserving the aspect ratio of the image. The native size of the picture is calculated using the dots-per-inch (dpi) value specified in the image file, defaulting to 72 dpi if no value is specified, as is often the case. """run=self.add_paragraph().add_run()returnrun.add_picture(image_path_or_stream,width,height)
[文档]defadd_section(self,start_type:WD_SECTION=WD_SECTION.NEW_PAGE):"""Return a |Section| object newly added at the end of the document. The optional `start_type` argument must be a member of the :ref:`WdSectionStart` enumeration, and defaults to ``WD_SECTION.NEW_PAGE`` if not provided. """new_sectPr=self._element.body.add_section_break()new_sectPr.start_type=start_typereturnSection(new_sectPr,self._part)
[文档]defadd_table(self,rows:int,cols:int,style:str|_TableStyle|None=None):"""Add a table having row and column counts of `rows` and `cols` respectively. `style` may be a table style object or a table style name. If `style` is |None|, the table inherits the default table style of the document. """table=self._body.add_table(rows,cols,self._block_width)table.style=stylereturntable
@propertydefcore_properties(self):"""A |CoreProperties| object providing Dublin Core properties of document."""returnself._part.core_properties@propertydefinline_shapes(self):"""The |InlineShapes| collection for this document. An inline shape is a graphical object, such as a picture, contained in a run of text and behaving like a character glyph, being flowed like other text in a paragraph. """returnself._part.inline_shapes
[文档]defiter_inner_content(self)->Iterator[Paragraph|Table]:"""Generate each `Paragraph` or `Table` in this document in document order."""returnself._body.iter_inner_content()
@propertydefparagraphs(self)->List[Paragraph]:"""The |Paragraph| instances in the document, in document order. Note that paragraphs within revision marks such as ``<w:ins>`` or ``<w:del>`` do not appear in this list. """returnself._body.paragraphs@propertydefpart(self)->DocumentPart:"""The |DocumentPart| object of this document."""returnself._part
[文档]defsave(self,path_or_stream:str|IO[bytes]):"""Save this document to `path_or_stream`. `path_or_stream` can be either a path to a filesystem location (a string) or a file-like object. """self._part.save(path_or_stream)
@propertydefsections(self)->Sections:"""|Sections| object providing access to each section in this document."""returnSections(self._element,self._part)@propertydefsettings(self)->Settings:"""A |Settings| object providing access to the document-level settings."""returnself._part.settings@propertydefstyles(self):"""A |Styles| object providing access to the styles in this document."""returnself._part.styles@propertydeftables(self)->List[Table]:"""All |Table| instances in the document, in document order. Note that only tables appearing at the top level of the document appear in this list; a table nested inside a table cell does not appear. A table within revision marks such as ``<w:ins>`` or ``<w:del>`` will also not appear in the list. """returnself._body.tables@propertydef_block_width(self)->Length:"""A |Length| object specifying the space between margins in last section."""section=self.sections[-1]returnEmu(section.page_width-section.left_margin-section.right_margin)@propertydef_body(self)->_Body:"""The |_Body| instance containing the content for this document."""ifself.__bodyisNone:self.__body=_Body(self._element.body,self)returnself.__body
class_Body(BlockItemContainer):"""Proxy for `<w:body>` element in this document. It's primary role is a container for document content. """def__init__(self,body_elm:CT_Body,parent:t.ProvidesStoryPart):super(_Body,self).__init__(body_elm,parent)self._body=body_elmdefclear_content(self):"""Return this |_Body| instance after clearing it of all content. Section properties for the main document story, if present, are preserved. """self._body.clear_content()returnself