python-docx Documentation
repository·master·Indexed 26 days ago
https://github.com/python-openxml/python-docxA Python library for reading, creating, and updating Microsoft Word 2007+ (.docx) files. It provides tools for managing documents via the Document class, handling core properties, and manipulating elements such as paragraphs, tables, comments, and DrawingML colors. The library includes a comprehensive set of enumerations for controlling paragraph alignment, line spacing, page orientation, table cell vertical alignment, and built-in Word styles.
What's inside python-docx
- A table in a Word document is composed of rows of cells. The alignment of cells across these rows is managed by an implicit sequence of grid columns. If the table contains no merged cells, these grid columns correspond directly to the visual columns of the table. All content within a table must be contained within its cells.
Understand Word Section behavior
masterWord uses
sectionelements to define distinct page layout settings (e.g., switching between portrait and landscape).Key implementation details:
- Last Section: Defined by a
<w:sectPr>element as the last child of<w:body>. - Additional Sections: Defined by a
<w:sectPr>element within the paragraph properties (<w:p><w:pPr><w:sectPr>) of the last paragraph in that section. The subsequent paragraph begins the next section. - Section Breaks vs. Other Breaks: Section breaks are implemented via
<w:sectPr>in paragraph properties, whereas line, page, and column breaks use the<w:br>element within a run.
- Last Section: Defined by a
Understand the difference between inline and floating shapes
masterWord documents consist of two layers:
- Text layer: Text objects flow from left to right and top to bottom.
- Drawing layer: Drawing objects, called
shapes(orfloatingshapes), are placed at arbitrary positions.
A picture can exist in either layer:
- Inline shape (inline picture): Resides in the text layer and is treated like a large text character (a character glyph). It follows text wrapping rules; for example, inserting text before it will push it to the right. The line height increases to accommodate it.
- Floating shape: Resides in the drawing layer at arbitrary positions.
Note: As of the current version,
python-docxprimarily supports inline pictures. Floating pictures can be added, but users with specific requirements should submit a feature request on the issue tracker.Understand Paragraph Style properties
masterA paragraph style in
python-docxcombines character formatting and paragraph-specific formatting:- Character Formatting: Inherited from
CharacterStyleand primarily accessed via thefontproperty. - Paragraph Formatting: Most paragraph-specific properties (like alignment, spacing, etc.) are managed through the
ParagraphFormatobject available via theparagraph_formatproperty. - Style-Specific Properties: Some properties are unique to the paragraph style itself, such as
next_paragraph_style.
- Character Formatting: Inherited from
Understand Styles in python-docx
masterStyles allow you to apply a group of formatting properties consistently to paragraphs, runs, tables, or numbering schemes. In the underlying OpenXML structure, styles are defined in the
styles.xmlpackage part and are linked to document elements using astyleIdstring.Key concepts:
- Built-in styles: Standard styles known to Word (e.g., "Heading 1"). They exist in the document even if not explicitly defined in the
styles.xmlpart. - Latent styles: Built-in styles that have no explicit definition in the current document.
- Style definition: An explicit
<w:style>element in thestyles.xmlpart that defines specific attributes. - Identification: Styles are identified by their name, not their
styleId. ThestyleIdis used for internal linking and may be transformed by Word (e.g., by removing spaces from the name).
- Built-in styles: Standard styles known to Word (e.g., "Heading 1"). They exist in the document even if not explicitly defined in the
Understand Shape types in python-docx
masterIn
python-docx, graphical objects are categorized into two main types based on how they interact with text:- Inline Shapes: These appear on a text baseline like a character glyph and affect the line height of the paragraph.
- Floating Shapes: These appear at arbitrary locations on the document, allowing text to wrap around them.
Note that the placement is determined by the container (the
InlineShapesorShapescollection) rather than the graphical object itself. The same object can be changed from inline to floating by moving it to a different container.Understand Run-level content in python-docx
masterIn
python-docx, a Run is the object representing inline content. It contains elements that flow between block-item boundaries (like paragraphs), such as text, pictures, and other inline items.Common child elements found within a run include:
<w:t>(Text)<w:br>(Line breaks)<w:drawing>(Drawings/Images)<w:tab>(Tabs)<w:cr>(Carriage returns)
Create a new document
masterTo create a new document, instantiate the
Documentclass without passing any arguments. This creates a new document based on the built-in default template. You can then use the.save()method to write it to a file.from docx import Document document = Document() document.save('test.docx')Create documents using block-level objects
masterThe
Documentobject is the primary entry point for creating or opening a.docxfile. You can build a document by adding block-level objects to the end of the document sequentially. Block-level objects include:- Paragraphs: Used for standard text, headings, bullets, and numbered lists (which are paragraphs with specific styles applied).
- Tables
- Pictures
Most common use cases involve adding content from top to bottom using methods on the
Documentinstance.Add comments to a document
masterYou can add comments to a document using the
Document.add_comment()method or theRun.add_comment()method. A comment requires a range of text (the 'comment reference') to anchor it to the document. This range must start and end at even run boundaries. You can specify the range by providing a list of runs or a single run.Optional parameters include
text,author, andinitials(bothauthorandinitialsdefault to an empty string).>>> paragraph = document.add_paragraph("Hello, world!") >>> document.add_comment( ... runs=paragraph.runs, ... text="I have this to say about that", ... author="Steve Canny", ... initials="SC", ... ) <docx.comments.Comment object at 0x02468ACE> >>> paragraph = document.add_paragraph("Summary: ") >>> run = paragraph.add_run("{{place-summary-here}}") >>> document.add_comment( ... run, text="The AI model will replace this placeholder with a summary" ... ) <docx.comments.Comment object at 0x02468ACE>Use block-level object references for inline customization
masterMethods on theDocumentobject that add block-level elements (such asadd_paragraph()) return the newly created object. While you can often call these methods without capturing the return value, you must capture the reference if you need to perform further granular or inline modifications to that specific object.Open and save documents using file-like objects
masterYou can work with documents using file-like objects (such as
io.BytesIOorio.StringIO) instead of direct file paths. This is useful for handling documents from network connections or databases without interacting with the local file system.When opening a file directly using Python's
open(), it is recommended to use binary mode ('rb') to ensure compatibility with the underlying Zipfile implementation, especially on Windows and certain Linux distributions.from io import StringIO # Opening from a file stream f = open('foobar.docx', 'rb') document = Document(f) f.close() # Using a StringIO stream with open('foobar.docx', 'rb') as f: source_stream = StringIO(f.read()) document = Document(source_stream) source_stream.close() # Saving to a stream target_stream = StringIO() document.save(target_stream)