Create, read, and update Microsoft Word .docx files.
—
Comprehensive style management and formatting including paragraph styles, character styles, fonts, colors, measurements, and document-wide style definitions.
Access and manage document styles collection.
class Document:
@property
def styles(self):
"""Document styles collection.
Returns:
Styles: Collection of all document styles
"""
class Styles:
def add_style(self, name, style_type, builtin=False):
"""Add a new style to the document.
Args:
name (str): Style name
style_type (WD_STYLE_TYPE): Type of style (paragraph, character, etc.)
builtin (bool): Whether style is a built-in Word style
Returns:
BaseStyle: New style object of appropriate type
"""
def get_by_id(self, style_id):
"""Get style by its identifier.
Args:
style_id (str): Style identifier
Returns:
BaseStyle or None: Style object or None if not found
"""
def get_style_id(self, name, style_type):
"""Get style ID for given name and type.
Args:
name (str): Style name
style_type (WD_STYLE_TYPE): Style type
Returns:
str: Style identifier
"""
@property
def default(self):
"""Default paragraph style.
Returns:
ParagraphStyle: Default paragraph style
"""
@property
def latent_styles(self):
"""Latent styles collection.
Returns:
LatentStyles: Latent styles collection
"""
def __iter__(self):
"""Iterate over all styles."""
def __len__(self):
"""Number of styles in collection."""
def __getitem__(self, key):
"""Access style by name or index."""Usage Examples:
from docx.enum.style import WD_STYLE_TYPE
# Access document styles
styles = doc.styles
# List all styles
for style in styles:
print(f"{style.name} ({style.type})")
# Get specific style
normal_style = styles['Normal']
heading1_style = styles['Heading 1']
# Add custom paragraph style
custom_style = styles.add_style('Custom Para', WD_STYLE_TYPE.PARAGRAPH)
custom_style.font.name = 'Arial'
custom_style.font.size = Pt(11)
# Add custom character style
char_style = styles.add_style('Highlight', WD_STYLE_TYPE.CHARACTER)
char_style.font.highlight_color = WD_COLOR_INDEX.YELLOWCommon properties available to all style types.
class BaseStyle:
@property
def name(self):
"""Style name (read/write).
Returns:
str: Style display name
"""
@name.setter
def name(self, value):
"""Set style name."""
@property
def style_id(self):
"""Style identifier.
Returns:
str: Internal style identifier
"""
@property
def type(self):
"""Style type.
Returns:
WD_STYLE_TYPE: Style type (paragraph, character, etc.)
"""
@property
def builtin(self):
"""Whether style is built-in.
Returns:
bool: True if built-in Word style
"""
@property
def hidden(self):
"""Whether style is hidden (read/write).
Returns:
bool: True if style is hidden from UI
"""
@hidden.setter
def hidden(self, value):
"""Set hidden status."""
@property
def locked(self):
"""Whether style is locked (read/write).
Returns:
bool: True if style is locked from editing
"""
@locked.setter
def locked(self, value):
"""Set locked status."""
@property
def priority(self):
"""Style priority (read/write).
Returns:
int: Style priority for sorting (lower = higher priority)
"""
@priority.setter
def priority(self, value):
"""Set style priority."""
@property
def quick_style(self):
"""Whether appears in quick style gallery (read/write).
Returns:
bool: True if appears in quick style gallery
"""
@quick_style.setter
def quick_style(self, value):
"""Set quick style status."""
@property
def unhide_when_used(self):
"""Whether to unhide when used (read/write).
Returns:
bool: True if style unhides when used
"""
@unhide_when_used.setter
def unhide_when_used(self, value):
"""Set unhide when used."""
@property
def delete(self):
"""Mark style for deletion (write-only).
Setting to True marks style for deletion.
"""
@delete.setter
def delete(self, value):
"""Mark style for deletion."""Character-level formatting styles that can be applied to runs.
class CharacterStyle(BaseStyle):
@property
def base_style(self):
"""Base style this style inherits from (read/write).
Returns:
CharacterStyle or None: Base character style
"""
@base_style.setter
def base_style(self, value):
"""Set base style."""
@property
def font(self):
"""Font formatting for this style.
Returns:
Font: Font formatting object
"""Usage Examples:
# Create custom character style
char_style = styles.add_style('Emphasis', WD_STYLE_TYPE.CHARACTER)
char_style.font.italic = True
char_style.font.color.rgb = RGBColor(128, 0, 0) # Dark red
# Apply character style to run
para = doc.add_paragraph('Normal text with ')
run = para.add_run('emphasized text')
run.style = char_style
para.add_run(' and more normal text.')Paragraph-level styles that include both paragraph and character formatting.
class ParagraphStyle(CharacterStyle):
@property
def next_paragraph_style(self):
"""Style for next paragraph (read/write).
Returns:
ParagraphStyle or None: Style automatically applied to next paragraph
"""
@next_paragraph_style.setter
def next_paragraph_style(self, value):
"""Set next paragraph style."""
@property
def paragraph_format(self):
"""Paragraph formatting for this style.
Returns:
ParagraphFormat: Paragraph formatting object
"""Usage Examples:
from docx.shared import Pt, Inches
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
# Create custom paragraph style
para_style = styles.add_style('Custom Heading', WD_STYLE_TYPE.PARAGRAPH)
# Set font properties
para_style.font.name = 'Arial'
para_style.font.size = Pt(16)
para_style.font.bold = True
para_style.font.color.rgb = RGBColor(0, 0, 128) # Dark blue
# Set paragraph formatting
para_style.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
para_style.paragraph_format.space_after = Pt(12)
para_style.paragraph_format.keep_with_next = True
# Set next paragraph style
para_style.next_paragraph_style = styles['Normal']
# Apply paragraph style
heading = doc.add_paragraph('Custom Heading Text', style=para_style)Access to Word's built-in styles through enumeration.
from docx.enum.style import WD_BUILTIN_STYLE
class WD_BUILTIN_STYLE:
"""Built-in style identifiers."""
NORMAL = -1
HEADING_1 = -2
HEADING_2 = -3
HEADING_3 = -4
HEADING_4 = -5
HEADING_5 = -6
HEADING_6 = -7
HEADING_7 = -8
HEADING_8 = -9
HEADING_9 = -10
TITLE = -63
SUBTITLE = -75
QUOTE = -181
INTENSE_QUOTE = -182
# ... over 200 additional built-in stylesUsage Examples:
from docx.enum.style import WD_BUILTIN_STYLE
# Access built-in styles by name
normal = styles['Normal']
heading1 = styles['Heading 1']
title = styles['Title']
quote = styles['Quote']
# Access by built-in style enum (alternative method)
# Note: These provide the style IDs for programmatic access
title_id = WD_BUILTIN_STYLE.TITLE
quote_id = WD_BUILTIN_STYLE.QUOTE
# Apply built-in styles
doc.add_paragraph('Document Title', style='Title')
doc.add_paragraph('This is a quote.', style='Quote')
doc.add_heading('Chapter 1', level=1) # Uses Heading 1 styleComprehensive color formatting for fonts and highlighting.
class ColorFormat:
@property
def rgb(self):
"""RGB color value (read/write).
Returns:
RGBColor or None: RGB color specification
"""
@rgb.setter
def rgb(self, value):
"""Set RGB color."""
@property
def theme_color(self):
"""Theme color (read/write).
Returns:
MSO_THEME_COLOR_INDEX or None: Theme color index
"""
@theme_color.setter
def theme_color(self, value):
"""Set theme color."""
@property
def type(self):
"""Color type.
Returns:
MSO_COLOR_TYPE: Type of color (RGB, theme, auto, etc.)
"""
class RGBColor(tuple):
"""RGB color specification."""
def __new__(cls, r, g, b):
"""Create RGB color.
Args:
r (int): Red component (0-255)
g (int): Green component (0-255)
b (int): Blue component (0-255)
"""
return tuple.__new__(cls, (r, g, b))Usage Examples:
from docx.shared import RGBColor
from docx.enum.dml import MSO_THEME_COLOR_INDEX
# Set RGB color
run = para.add_run('Red text')
run.font.color.rgb = RGBColor(255, 0, 0)
# Set theme color
run = para.add_run('Accent color text')
run.font.color.theme_color = MSO_THEME_COLOR_INDEX.ACCENT_1
# Check color type
color_format = run.font.color
if color_format.type == MSO_COLOR_TYPE.RGB:
print(f"RGB color: {color_format.rgb}")
elif color_format.type == MSO_COLOR_TYPE.SCHEME:
print(f"Theme color: {color_format.theme_color}")Precise measurement units for formatting.
class Length(int):
"""Base measurement class in English Metric Units (EMUs)."""
@property
def inches(self):
"""Value in inches.
Returns:
float: Length in inches
"""
@property
def cm(self):
"""Value in centimeters.
Returns:
float: Length in centimeters
"""
@property
def mm(self):
"""Value in millimeters.
Returns:
float: Length in millimeters
"""
@property
def pt(self):
"""Value in points.
Returns:
float: Length in points
"""
@property
def twips(self):
"""Value in twips.
Returns:
float: Length in twips
"""
@property
def emu(self):
"""Value in English Metric Units.
Returns:
int: Length in EMUs
"""
def Inches(inches):
"""Create Length from inches.
Args:
inches (float): Length in inches
Returns:
Length: Length object
"""
def Cm(cm):
"""Create Length from centimeters.
Args:
cm (float): Length in centimeters
Returns:
Length: Length object
"""
def Mm(mm):
"""Create Length from millimeters.
Args:
mm (float): Length in millimeters
Returns:
Length: Length object
"""
def Pt(points):
"""Create Length from points.
Args:
points (float): Length in points
Returns:
Length: Length object
"""
def Emu(emu):
"""Create Length from English Metric Units.
Args:
emu (int): Length in EMUs
Returns:
Length: Length object
"""
def Twips(twips):
"""Create Length from twips.
Args:
twips (int): Length in twips
Returns:
Length: Length object
"""Usage Examples:
from docx.shared import Inches, Cm, Mm, Pt
# Create measurements
margin = Inches(1.0)
indent = Cm(1.5)
spacing = Mm(6)
font_size = Pt(12)
# Use in formatting
para_format = para.paragraph_format
para_format.left_indent = indent
para_format.space_after = spacing
font = run.font
font.size = font_size
# Convert between units
print(f"1 inch = {Inches(1).cm} cm")
print(f"12 pt = {Pt(12).mm} mm")Management of latent (available but not loaded) styles.
class LatentStyles:
@property
def default_priority(self):
"""Default priority for latent styles (read/write).
Returns:
int: Default priority
"""
@default_priority.setter
def default_priority(self, value):
"""Set default priority."""
@property
def default_to_locked(self):
"""Default locked setting (read/write).
Returns:
bool: Default locked setting for latent styles
"""
@default_to_locked.setter
def default_to_locked(self, value):
"""Set default locked setting."""
@property
def default_to_quick_style(self):
"""Default quick style setting (read/write).
Returns:
bool: Default quick style setting
"""
@default_to_quick_style.setter
def default_to_quick_style(self, value):
"""Set default quick style setting."""
@property
def default_to_unhide_when_used(self):
"""Default unhide when used setting (read/write).
Returns:
bool: Default unhide when used setting
"""
@default_to_unhide_when_used.setter
def default_to_unhide_when_used(self, value):
"""Set default unhide when used setting."""
@property
def load_count(self):
"""Number of latent styles to load (read/write).
Returns:
int: Number of styles to load
"""
@load_count.setter
def load_count(self, value):
"""Set load count."""from docx.enum.style import WD_STYLE_TYPE
class WD_STYLE_TYPE:
"""Style type options."""
CHARACTER = 2
LIST = 4
PARAGRAPH = 1
TABLE = 3
from docx.enum.dml import MSO_COLOR_TYPE
class MSO_COLOR_TYPE:
"""Color type options."""
AUTO = 101
RGB = 1
SCHEME = 2
UNSET = 0
from docx.enum.dml import MSO_THEME_COLOR_INDEX
class MSO_THEME_COLOR_INDEX:
"""Theme color index options."""
ACCENT_1 = 5
ACCENT_2 = 6
ACCENT_3 = 7
ACCENT_4 = 8
ACCENT_5 = 9
ACCENT_6 = 10
BACKGROUND_1 = 15
BACKGROUND_2 = 16
DARK_1 = 1
DARK_2 = 3
FOLLOWED_HYPERLINK = 12
HYPERLINK = 11
LIGHT_1 = 2
LIGHT_2 = 4
NOT_THEME_COLOR = 0
TEXT_1 = 13
TEXT_2 = 14Install with Tessl CLI
npx tessl i tessl/pypi-python-docx