Create, read, and update Microsoft Word .docx files.
—
Page setup, margins, orientation, headers, footers, and section management for comprehensive document layout control. Provides full control over document structure and page formatting.
Access and manage document sections for layout control.
class Document:
@property
def sections(self):
"""Collection of document sections.
Returns:
Sections: Sequence of Section objects
"""
def add_section(self, start_type=None):
"""Add a new section to the document.
Args:
start_type (WD_SECTION_START, optional): How the section should start
Returns:
Section: New section object
"""
class Sections:
def __len__(self):
"""Number of sections in document."""
def __iter__(self):
"""Iterate over sections."""
def __getitem__(self, index):
"""Access section by index."""Usage Examples:
from docx.enum.section import WD_SECTION_START
# Access existing sections
sections = doc.sections
print(f"Document has {len(sections)} sections")
# Access first section
first_section = sections[0]
# Add new section with page break
new_section = doc.add_section(WD_SECTION_START.NEW_PAGE)
# Add continuous section (no page break)
continuous_section = doc.add_section(WD_SECTION_START.CONTINUOUS)
# Iterate through all sections
for i, section in enumerate(doc.sections):
print(f"Section {i+1}: {section.page_width.inches}\" x {section.page_height.inches}\"")Control page size, orientation, and dimensions.
class Section:
@property
def page_width(self):
"""Page width (read/write).
Returns:
Length: Page width
"""
@page_width.setter
def page_width(self, value):
"""Set page width."""
@property
def page_height(self):
"""Page height (read/write).
Returns:
Length: Page height
"""
@page_height.setter
def page_height(self, value):
"""Set page height."""
@property
def orientation(self):
"""Page orientation (read/write).
Returns:
WD_ORIENTATION: Current page orientation
"""
@orientation.setter
def orientation(self, value):
"""Set page orientation."""
@property
def start_type(self):
"""Section start type (read/write).
Returns:
WD_SECTION_START: How this section starts
"""
@start_type.setter
def start_type(self, value):
"""Set section start type."""Usage Examples:
from docx.shared import Inches
from docx.enum.section import WD_ORIENTATION, WD_SECTION_START
# Access section for page setup
section = doc.sections[0]
# Set page dimensions (US Letter)
section.page_width = Inches(8.5)
section.page_height = Inches(11)
# Set page orientation
section.orientation = WD_ORIENTATION.PORTRAIT
# Create landscape section
landscape_section = doc.add_section(WD_SECTION_START.NEW_PAGE)
landscape_section.orientation = WD_ORIENTATION.LANDSCAPE
# For landscape, swap width and height
landscape_section.page_width = Inches(11)
landscape_section.page_height = Inches(8.5)
# Common page sizes
# US Letter: 8.5" x 11"
# A4: 8.27" x 11.69"
# Legal: 8.5" x 14"
# Set A4 page size
section.page_width = Inches(8.27)
section.page_height = Inches(11.69)Control page margins for precise layout.
class Section:
@property
def top_margin(self):
"""Top margin (read/write).
Returns:
Length: Top margin distance
"""
@top_margin.setter
def top_margin(self, value):
"""Set top margin."""
@property
def bottom_margin(self):
"""Bottom margin (read/write).
Returns:
Length: Bottom margin distance
"""
@bottom_margin.setter
def bottom_margin(self, value):
"""Set bottom margin."""
@property
def left_margin(self):
"""Left margin (read/write).
Returns:
Length: Left margin distance
"""
@left_margin.setter
def left_margin(self, value):
"""Set left margin."""
@property
def right_margin(self):
"""Right margin (read/write).
Returns:
Length: Right margin distance
"""
@right_margin.setter
def right_margin(self, value):
"""Set right margin."""Usage Examples:
from docx.shared import Inches, Cm
# Set standard margins (1 inch)
section = doc.sections[0]
section.top_margin = Inches(1)
section.bottom_margin = Inches(1)
section.left_margin = Inches(1)
section.right_margin = Inches(1)
# Set narrow margins
section.top_margin = Inches(0.5)
section.bottom_margin = Inches(0.5)
section.left_margin = Inches(0.5)
section.right_margin = Inches(0.5)
# Set different margins for binding
section.left_margin = Inches(1.5) # Extra space for binding
section.right_margin = Inches(1)
section.top_margin = Inches(1)
section.bottom_margin = Inches(1)
# Use metric measurements
section.top_margin = Cm(2.5)
section.bottom_margin = Cm(2.5)
section.left_margin = Cm(3)
section.right_margin = Cm(2)Create and manage section headers.
class Section:
@property
def header(self):
"""Primary header for this section.
Returns:
_Header: Header object
"""
@property
def header_distance(self):
"""Distance from top of page to header (read/write).
Returns:
Length: Header distance
"""
@header_distance.setter
def header_distance(self, value):
"""Set header distance."""
@property
def different_first_page_header_footer(self):
"""Whether first page has different header/footer (read/write).
Returns:
bool: True if first page is different
"""
@different_first_page_header_footer.setter
def different_first_page_header_footer(self, value):
"""Set different first page header/footer."""
class _Header:
def add_paragraph(self, text='', style=None):
"""Add a paragraph to the header.
Args:
text (str, optional): Paragraph text
style (str or ParagraphStyle, optional): Paragraph style
Returns:
Paragraph: New paragraph object
"""
def add_table(self, rows, cols):
"""Add a table to the header.
Args:
rows (int): Number of initial rows
cols (int): Number of initial columns
Returns:
Table: New table object
"""
@property
def is_linked_to_previous(self):
"""Whether header is linked to previous section (read/write).
Returns:
bool: True if linked to previous section
"""
@is_linked_to_previous.setter
def is_linked_to_previous(self, value):
"""Set link to previous section."""
@property
def paragraphs(self):
"""Paragraphs in the header.
Returns:
list[Paragraph]: List of paragraph objects
"""
@property
def tables(self):
"""Tables in the header.
Returns:
list[Table]: List of table objects
"""Usage Examples:
from docx.shared import Inches
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
# Access section header
section = doc.sections[0]
header = section.header
# Add simple header text
header_para = header.add_paragraph("Document Title")
header_para.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Add header with different content
header.add_paragraph("Chapter 1: Introduction", style='Header')
# Set header distance from page top
section.header_distance = Inches(0.5)
# Create header with table for complex layout
header_table = header.add_table(rows=1, cols=3)
header_table.cell(0, 0).text = "Left Header"
header_table.cell(0, 1).text = "Center Header"
header_table.cell(0, 2).text = "Right Header"
# Set table alignment
header_table.cell(0, 0).paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.LEFT
header_table.cell(0, 1).paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
header_table.cell(0, 2).paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT
# Unlink from previous section (create unique header)
header.is_linked_to_previous = False
# Set different first page
section.different_first_page_header_footer = TrueCreate and manage section footers.
class Section:
@property
def footer(self):
"""Primary footer for this section.
Returns:
_Footer: Footer object
"""
@property
def footer_distance(self):
"""Distance from bottom of page to footer (read/write).
Returns:
Length: Footer distance
"""
@footer_distance.setter
def footer_distance(self, value):
"""Set footer distance."""
class _Footer:
def add_paragraph(self, text='', style=None):
"""Add a paragraph to the footer.
Args:
text (str, optional): Paragraph text
style (str or ParagraphStyle, optional): Paragraph style
Returns:
Paragraph: New paragraph object
"""
def add_table(self, rows, cols):
"""Add a table to the footer.
Args:
rows (int): Number of initial rows
cols (int): Number of initial columns
Returns:
Table: New table object
"""
@property
def is_linked_to_previous(self):
"""Whether footer is linked to previous section (read/write).
Returns:
bool: True if linked to previous section
"""
@is_linked_to_previous.setter
def is_linked_to_previous(self, value):
"""Set link to previous section."""
@property
def paragraphs(self):
"""Paragraphs in the footer.
Returns:
list[Paragraph]: List of paragraph objects
"""
@property
def tables(self):
"""Tables in the footer.
Returns:
list[Table]: List of table objects
"""Usage Examples:
from docx.shared import Inches
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
# Access section footer
section = doc.sections[0]
footer = section.footer
# Add simple footer text
footer_para = footer.add_paragraph("Page Footer")
footer_para.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Add footer with page numbers (conceptual - actual page numbers require fields)
footer_para = footer.add_paragraph("Page 1")
footer_para.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT
# Set footer distance from page bottom
section.footer_distance = Inches(0.5)
# Create footer with table for layout
footer_table = footer.add_table(rows=1, cols=2)
footer_table.cell(0, 0).text = "© 2024 Company Name"
footer_table.cell(0, 1).text = "Confidential"
footer_table.cell(0, 0).paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.LEFT
footer_table.cell(0, 1).paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT
# Unlink from previous section
footer.is_linked_to_previous = FalseCreate documents with multiple sections having different layouts.
Usage Examples:
from docx.enum.section import WD_ORIENTATION, WD_SECTION_START
from docx.shared import Inches
# Create document with multiple sections
doc = Document()
# First section - portrait title page
doc.add_heading('Document Title', 0)
doc.add_paragraph('Title page content')
# Add landscape section for wide table/chart
landscape_section = doc.add_section(WD_SECTION_START.NEW_PAGE)
landscape_section.orientation = WD_ORIENTATION.LANDSCAPE
landscape_section.page_width = Inches(11)
landscape_section.page_height = Inches(8.5)
# Add wide table in landscape section
table = doc.add_table(rows=5, cols=8)
# ... populate table
# Add portrait section for continued text
portrait_section = doc.add_section(WD_SECTION_START.NEW_PAGE)
portrait_section.orientation = WD_ORIENTATION.PORTRAIT
portrait_section.page_width = Inches(8.5)
portrait_section.page_height = Inches(11)
doc.add_paragraph('Continued text in portrait orientation')
# Set different headers for each section
# Title page - no header
doc.sections[0].header.is_linked_to_previous = False
# Landscape section - different header
doc.sections[1].header.is_linked_to_previous = False
doc.sections[1].header.add_paragraph('Data Tables Section')
# Portrait section - main document header
doc.sections[2].header.is_linked_to_previous = False
doc.sections[2].header.add_paragraph('Main Document')Control how sections start and flow.
Usage Examples:
from docx.enum.section import WD_SECTION_START
# Continuous section (no page break)
continuous_section = doc.add_section(WD_SECTION_START.CONTINUOUS)
# New page section (default)
new_page_section = doc.add_section(WD_SECTION_START.NEW_PAGE)
# Even page section (starts on even page)
even_page_section = doc.add_section(WD_SECTION_START.EVEN_PAGE)
# Odd page section (starts on odd page)
odd_page_section = doc.add_section(WD_SECTION_START.ODD_PAGE)
# New column section (for multi-column layouts)
new_column_section = doc.add_section(WD_SECTION_START.NEW_COLUMN)
# Change existing section's start type
section = doc.sections[0]
section.start_type = WD_SECTION_START.ODD_PAGEComplex layout scenarios using sections.
Usage Examples:
# Create document with different margin for chapters
def add_chapter(doc, title, content):
# Add new section for chapter
chapter_section = doc.add_section(WD_SECTION_START.ODD_PAGE)
# Set chapter-specific margins
chapter_section.top_margin = Inches(2) # Extra top margin
chapter_section.left_margin = Inches(1.5)
# Add chapter header
header = chapter_section.header
header.is_linked_to_previous = False
header.add_paragraph(title, style='Header')
# Add chapter content
doc.add_heading(title, level=1)
doc.add_paragraph(content)
return chapter_section
# Add multiple chapters
add_chapter(doc, "Chapter 1: Introduction", "Chapter 1 content...")
add_chapter(doc, "Chapter 2: Methods", "Chapter 2 content...")
# Create appendix with different formatting
appendix_section = doc.add_section(WD_SECTION_START.NEW_PAGE)
appendix_section.left_margin = Inches(1) # Standard margin
appendix_section.right_margin = Inches(1)
# Different footer for appendix
footer = appendix_section.footer
footer.is_linked_to_previous = False
footer.add_paragraph("Appendix")from docx.enum.section import WD_SECTION_START
class WD_SECTION_START:
"""Section start type options."""
CONTINUOUS = 0 # No page break
NEW_COLUMN = 1 # Start in new column
NEW_PAGE = 2 # Start on new page (default)
EVEN_PAGE = 3 # Start on next even page
ODD_PAGE = 4 # Start on next odd page
from docx.enum.section import WD_ORIENTATION
class WD_ORIENTATION:
"""Page orientation options."""
PORTRAIT = 0 # Height > Width
LANDSCAPE = 1 # Width > Height
from docx.enum.section import WD_HEADER_FOOTER_INDEX
class WD_HEADER_FOOTER_INDEX:
"""Header/footer index options."""
PRIMARY = 0 # Primary header/footer
FIRST_PAGE = 1 # First page header/footer
EVEN_PAGE = 2 # Even page header/footerInstall with Tessl CLI
npx tessl i tessl/pypi-python-docx