Create, read, and update Microsoft Word .docx files.
—
Comprehensive text manipulation including paragraphs, runs, character formatting, alignment, and rich text capabilities. This covers all text-related functionality for creating and formatting document content.
Add paragraphs with optional text content and styling.
class Document:
def add_paragraph(self, text='', style=None):
"""Add a paragraph to the document.
Args:
text (str, optional): Initial paragraph text
style (str or ParagraphStyle, optional): Paragraph style name or object
Returns:
Paragraph: New paragraph object
"""
def add_heading(self, text='', level=1):
"""Add a heading paragraph.
Args:
text (str, optional): Heading text
level (int): Heading level (0-9, where 0 is Title style)
Returns:
Paragraph: New heading paragraph
"""Usage Examples:
# Add simple paragraph
para = doc.add_paragraph('This is a simple paragraph.')
# Add paragraph with style
styled_para = doc.add_paragraph('Styled paragraph', style='Quote')
# Add headings
title = doc.add_heading('Document Title', level=0) # Title style
heading1 = doc.add_heading('Chapter 1', level=1) # Heading 1
heading2 = doc.add_heading('Section 1.1', level=2) # Heading 2Access and manipulate paragraph content and formatting.
class Paragraph:
def add_run(self, text=None, style=None):
"""Add a run of text to the paragraph.
Args:
text (str, optional): Run text content
style (str or CharacterStyle, optional): Character style
Returns:
Run: New run object
"""
def clear(self):
"""Remove all content from paragraph, keeping the paragraph element."""
def insert_paragraph_before(self, text='', style=None):
"""Insert a new paragraph before this one.
Args:
text (str, optional): New paragraph text
style (str or ParagraphStyle, optional): Paragraph style
Returns:
Paragraph: New paragraph object
"""
@property
def text(self):
"""Plain text content of paragraph (read/write).
Setting this property replaces all paragraph content with plain text.
"""
@text.setter
def text(self, value):
"""Set paragraph text content."""
@property
def runs(self):
"""List of runs in the paragraph.
Returns:
list[Run]: All run objects in paragraph
"""
@property
def style(self):
"""Paragraph style (read/write).
Returns:
ParagraphStyle or None: Current paragraph style
"""
@style.setter
def style(self, value):
"""Set paragraph style."""
@property
def paragraph_format(self):
"""Paragraph formatting object.
Returns:
ParagraphFormat: Formatting properties for paragraph
"""
@property
def alignment(self):
"""Paragraph alignment (read/write).
Returns:
WD_PARAGRAPH_ALIGNMENT or None: Current alignment
"""
@alignment.setter
def alignment(self, value):
"""Set paragraph alignment."""Usage Examples:
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
# Create paragraph with multiple runs
para = doc.add_paragraph()
para.add_run('This is normal text. ')
para.add_run('This is bold text.').bold = True
para.add_run(' This is italic text.').italic = True
# Set paragraph alignment
para.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Access paragraph text
print(f"Paragraph text: {para.text}")
# Clear and reset paragraph
para.clear()
para.text = "New paragraph content"
# Insert paragraph before existing one
new_para = para.insert_paragraph_before("This paragraph comes first")Manipulate individual runs of text with character formatting.
class Run:
def add_break(self, break_type=None):
"""Add a break to the run.
Args:
break_type (WD_BREAK_TYPE, optional): Type of break to add
"""
def add_tab(self):
"""Add a tab character to the run."""
def add_picture(self, image_path_or_stream, width=None, height=None):
"""Add an inline picture to the run.
Args:
image_path_or_stream (str or file-like): Image file path or stream
width (Length, optional): Picture width
height (Length, optional): Picture height
Returns:
InlineShape: New inline shape object
"""
def clear(self):
"""Remove all content from run, keeping the run element."""
@property
def text(self):
"""Run text content (read/write)."""
@text.setter
def text(self, value):
"""Set run text content."""
@property
def style(self):
"""Character style (read/write).
Returns:
CharacterStyle or None: Current character style
"""
@style.setter
def style(self, value):
"""Set character style."""
@property
def bold(self):
"""Bold formatting (read/write).
Returns:
bool or None: True/False for explicit bold, None for inherit
"""
@bold.setter
def bold(self, value):
"""Set bold formatting."""
@property
def italic(self):
"""Italic formatting (read/write).
Returns:
bool or None: True/False for explicit italic, None for inherit
"""
@italic.setter
def italic(self, value):
"""Set italic formatting."""
@property
def underline(self):
"""Underline formatting (read/write).
Returns:
bool, WD_UNDERLINE, or None: Underline setting
"""
@underline.setter
def underline(self, value):
"""Set underline formatting."""
@property
def font(self):
"""Font formatting object.
Returns:
Font: Font formatting properties
"""Usage Examples:
from docx.enum.text import WD_BREAK_TYPE
from docx.shared import Inches
# Create and format runs
run = para.add_run('Formatted text')
run.bold = True
run.italic = True
run.underline = True
# Add breaks
run.add_break(WD_BREAK_TYPE.LINE) # Line break
run.add_break(WD_BREAK_TYPE.PAGE) # Page break
# Add tab
run.add_tab()
# Add picture to run
run.add_picture('image.png', width=Inches(1))
# Clear run content
run.clear()
run.text = "New run content"Detailed character formatting through Font objects.
class Font:
@property
def name(self):
"""Font name (read/write).
Returns:
str or None: Font name like 'Arial', 'Times New Roman'
"""
@name.setter
def name(self, value):
"""Set font name."""
@property
def size(self):
"""Font size (read/write).
Returns:
Length or None: Font size in points (Pt objects)
"""
@size.setter
def size(self, value):
"""Set font size."""
@property
def bold(self):
"""Bold formatting (read/write).
Returns:
bool or None: Bold setting
"""
@bold.setter
def bold(self, value):
"""Set bold formatting."""
@property
def italic(self):
"""Italic formatting (read/write).
Returns:
bool or None: Italic setting
"""
@italic.setter
def italic(self, value):
"""Set italic formatting."""
@property
def underline(self):
"""Underline formatting (read/write).
Returns:
bool, WD_UNDERLINE, or None: Underline setting
"""
@underline.setter
def underline(self, value):
"""Set underline formatting."""
@property
def strike(self):
"""Strikethrough formatting (read/write).
Returns:
bool or None: Strike setting
"""
@strike.setter
def strike(self, value):
"""Set strikethrough formatting."""
@property
def subscript(self):
"""Subscript formatting (read/write).
Returns:
bool or None: Subscript setting
"""
@subscript.setter
def subscript(self, value):
"""Set subscript formatting."""
@property
def superscript(self):
"""Superscript formatting (read/write).
Returns:
bool or None: Superscript setting
"""
@superscript.setter
def superscript(self, value):
"""Set superscript formatting."""
@property
def color(self):
"""Font color formatting.
Returns:
ColorFormat: Color formatting object
"""
@property
def highlight_color(self):
"""Text highlight color (read/write).
Returns:
WD_COLOR_INDEX or None: Highlight color
"""
@highlight_color.setter
def highlight_color(self, value):
"""Set highlight color."""
@property
def all_caps(self):
"""All caps formatting (read/write).
Returns:
bool or None: All caps setting
"""
@all_caps.setter
def all_caps(self, value):
"""Set all caps formatting."""
@property
def small_caps(self):
"""Small caps formatting (read/write).
Returns:
bool or None: Small caps setting
"""
@small_caps.setter
def small_caps(self, value):
"""Set small caps formatting."""Usage Examples:
from docx.shared import Pt, RGBColor
from docx.enum.text import WD_COLOR_INDEX, WD_UNDERLINE
# Access font through run
run = para.add_run('Formatted text')
font = run.font
# Set basic font properties
font.name = 'Arial'
font.size = Pt(12)
font.bold = True
font.italic = True
# Set underline style
font.underline = WD_UNDERLINE.SINGLE
# Set font color
font.color.rgb = RGBColor(255, 0, 0) # Red
# Set highlight color
font.highlight_color = WD_COLOR_INDEX.YELLOW
# Set special formatting
font.all_caps = True
font.strike = True
font.subscript = True # Note: subscript and superscript are mutually exclusiveAdvanced paragraph formatting through ParagraphFormat objects.
class ParagraphFormat:
@property
def alignment(self):
"""Paragraph alignment (read/write).
Returns:
WD_PARAGRAPH_ALIGNMENT or None: Alignment setting
"""
@alignment.setter
def alignment(self, value):
"""Set paragraph alignment."""
@property
def left_indent(self):
"""Left indent (read/write).
Returns:
Length or None: Left indent distance
"""
@left_indent.setter
def left_indent(self, value):
"""Set left indent."""
@property
def right_indent(self):
"""Right indent (read/write).
Returns:
Length or None: Right indent distance
"""
@right_indent.setter
def right_indent(self, value):
"""Set right indent."""
@property
def first_line_indent(self):
"""First line indent (read/write).
Returns:
Length or None: First line indent distance
"""
@first_line_indent.setter
def first_line_indent(self, value):
"""Set first line indent."""
@property
def space_before(self):
"""Space before paragraph (read/write).
Returns:
Length or None: Space before distance
"""
@space_before.setter
def space_before(self, value):
"""Set space before paragraph."""
@property
def space_after(self):
"""Space after paragraph (read/write).
Returns:
Length or None: Space after distance
"""
@space_after.setter
def space_after(self, value):
"""Set space after paragraph."""
@property
def line_spacing(self):
"""Line spacing (read/write).
Returns:
float, Length, or None: Line spacing value
"""
@line_spacing.setter
def line_spacing(self, value):
"""Set line spacing."""
@property
def line_spacing_rule(self):
"""Line spacing rule (read/write).
Returns:
WD_LINE_SPACING or None: Line spacing rule
"""
@line_spacing_rule.setter
def line_spacing_rule(self, value):
"""Set line spacing rule."""
@property
def keep_together(self):
"""Keep paragraph together on page (read/write).
Returns:
bool or None: Keep together setting
"""
@keep_together.setter
def keep_together(self, value):
"""Set keep together."""
@property
def keep_with_next(self):
"""Keep with next paragraph (read/write).
Returns:
bool or None: Keep with next setting
"""
@keep_with_next.setter
def keep_with_next(self, value):
"""Set keep with next."""
@property
def page_break_before(self):
"""Page break before paragraph (read/write).
Returns:
bool or None: Page break before setting
"""
@page_break_before.setter
def page_break_before(self, value):
"""Set page break before."""
@property
def widow_control(self):
"""Widow/orphan control (read/write).
Returns:
bool or None: Widow control setting
"""
@widow_control.setter
def widow_control(self, value):
"""Set widow control."""
@property
def tab_stops(self):
"""Tab stops collection.
Returns:
TabStops: Tab stops collection object
"""Usage Examples:
from docx.shared import Inches, Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT, WD_LINE_SPACING
# Access paragraph format
para = doc.add_paragraph('Formatted paragraph')
fmt = para.paragraph_format
# Set alignment and indentation
fmt.alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY
fmt.left_indent = Inches(0.5)
fmt.right_indent = Inches(0.25)
fmt.first_line_indent = Inches(0.25)
# Set spacing
fmt.space_before = Pt(6)
fmt.space_after = Pt(6)
fmt.line_spacing = 1.5
fmt.line_spacing_rule = WD_LINE_SPACING.MULTIPLE
# Set page control options
fmt.keep_together = True
fmt.keep_with_next = True
fmt.page_break_before = False
fmt.widow_control = TrueManage paragraph tab stops for precise text alignment.
class TabStops:
def add_tab_stop(self, position, alignment=None, leader=None):
"""Add a tab stop.
Args:
position (Length): Tab stop position from left margin
alignment (WD_TAB_ALIGNMENT, optional): Tab alignment
leader (WD_TAB_LEADER, optional): Tab leader character
Returns:
TabStop: New tab stop object
"""
def clear_all(self):
"""Remove all custom tab stops."""
class TabStop:
@property
def position(self):
"""Tab stop position from left margin.
Returns:
Length: Position distance
"""
@property
def alignment(self):
"""Tab alignment.
Returns:
WD_TAB_ALIGNMENT: Alignment setting
"""
@property
def leader(self):
"""Tab leader character.
Returns:
WD_TAB_LEADER: Leader setting
"""Usage Examples:
from docx.shared import Inches
from docx.enum.text import WD_TAB_ALIGNMENT, WD_TAB_LEADER
# Add tab stops to paragraph
para = doc.add_paragraph()
tabs = para.paragraph_format.tab_stops
# Add different types of tab stops
tabs.add_tab_stop(Inches(1), WD_TAB_ALIGNMENT.LEFT)
tabs.add_tab_stop(Inches(3), WD_TAB_ALIGNMENT.CENTER)
tabs.add_tab_stop(Inches(5), WD_TAB_ALIGNMENT.RIGHT, WD_TAB_LEADER.DOTS)
# Add content with tabs
run = para.add_run("Left\tCenter\tRight with dots")from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
class WD_PARAGRAPH_ALIGNMENT:
"""Paragraph alignment options."""
LEFT = 0
CENTER = 1
RIGHT = 2
JUSTIFY = 3
DISTRIBUTE = 4
from docx.enum.text import WD_BREAK_TYPE
class WD_BREAK_TYPE:
"""Break type options."""
COLUMN = 8
LINE = 6
LINE_CLEAR_LEFT = 9
LINE_CLEAR_RIGHT = 11
PAGE = 7
TEXT_WRAPPING = 5
from docx.enum.text import WD_LINE_SPACING
class WD_LINE_SPACING:
"""Line spacing rule options."""
SINGLE = 0
ONE_POINT_FIVE = 1
DOUBLE = 2
AT_LEAST = 3
EXACTLY = 4
MULTIPLE = 5
from docx.enum.text import WD_UNDERLINE
class WD_UNDERLINE:
"""Underline type options."""
NONE = 0
SINGLE = 1
WORDS = 2
DOUBLE = 3
DOTTED = 4
THICK = 6
DASH = 7
DOT_DASH = 9
DOT_DOT_DASH = 10
WAVY = 11
from docx.enum.text import WD_COLOR_INDEX
class WD_COLOR_INDEX:
"""Text highlight color options."""
AUTO = 0
BLACK = 1
BLUE = 2
BRIGHT_GREEN = 4
DARK_BLUE = 9
DARK_RED = 13
DARK_YELLOW = 14
GRAY_25 = 16
GRAY_50 = 15
GREEN = 11
PINK = 5
RED = 6
TEAL = 10
TURQUOISE = 3
VIOLET = 12
WHITE = 8
YELLOW = 7
from docx.enum.text import WD_TAB_ALIGNMENT
class WD_TAB_ALIGNMENT:
"""Tab alignment options."""
LEFT = 0
CENTER = 1
RIGHT = 2
DECIMAL = 3
BAR = 4
LIST = 6
CLEAR = 7
from docx.enum.text import WD_TAB_LEADER
class WD_TAB_LEADER:
"""Tab leader options."""
SPACES = 0
DOTS = 1
DASHES = 2
LINES = 3
HEAVY = 4
MIDDLE_DOT = 5Install with Tessl CLI
npx tessl i tessl/pypi-python-docx