python-docx Documentation

repository·master·Indexed 26 days ago

https://github.com/python-openxml/python-docx

A 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.

Tokens
47.6K
Snippets
119
Records
241
Agent score
88%

What's inside python-docx

  1. Understand Word Section behavior

    master

    Word uses section elements 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.
  2. Understand the difference between inline and floating shapes

    master

    Word documents consist of two layers:

    1. Text layer: Text objects flow from left to right and top to bottom.
    2. Drawing layer: Drawing objects, called shapes (or floating shapes), 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-docx primarily supports inline pictures. Floating pictures can be added, but users with specific requirements should submit a feature request on the issue tracker.

  3. Understand Paragraph Style properties

    master

    A paragraph style in python-docx combines character formatting and paragraph-specific formatting:

    • Character Formatting: Inherited from CharacterStyle and primarily accessed via the font property.
    • Paragraph Formatting: Most paragraph-specific properties (like alignment, spacing, etc.) are managed through the ParagraphFormat object available via the paragraph_format property.
    • Style-Specific Properties: Some properties are unique to the paragraph style itself, such as next_paragraph_style.
  4. Understand Styles in python-docx

    master

    Styles 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.xml package part and are linked to document elements using a styleId string.

    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.xml part.
    • Latent styles: Built-in styles that have no explicit definition in the current document.
    • Style definition: An explicit <w:style> element in the styles.xml part that defines specific attributes.
    • Identification: Styles are identified by their name, not their styleId. The styleId is used for internal linking and may be transformed by Word (e.g., by removing spaces from the name).
  5. Understand Shape types in python-docx

    master

    In python-docx, graphical objects are categorized into two main types based on how they interact with text:

    1. Inline Shapes: These appear on a text baseline like a character glyph and affect the line height of the paragraph.
    2. 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 InlineShapes or Shapes collection) rather than the graphical object itself. The same object can be changed from inline to floating by moving it to a different container.

  6. Create documents using block-level objects

    master

    The Document object is the primary entry point for creating or opening a .docx file. 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 Document instance.

  7. Add comments to a document

    master

    You can add comments to a document using the Document.add_comment() method or the Run.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, and initials (both author and initials default 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>
  8. Use block-level object references for inline customization

    master
    Methods on the Document object that add block-level elements (such as add_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.
  9. Open and save documents using file-like objects

    master

    You can work with documents using file-like objects (such as io.BytesIO or io.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)