0
# Sections and Page Layout
1
2
Page setup, margins, orientation, headers, footers, and section management for comprehensive document layout control. Provides full control over document structure and page formatting.
3
4
## Capabilities
5
6
### Section Access and Management
7
8
Access and manage document sections for layout control.
9
10
```python { .api }
11
class Document:
12
@property
13
def sections(self):
14
"""Collection of document sections.
15
16
Returns:
17
Sections: Sequence of Section objects
18
"""
19
20
def add_section(self, start_type=None):
21
"""Add a new section to the document.
22
23
Args:
24
start_type (WD_SECTION_START, optional): How the section should start
25
26
Returns:
27
Section: New section object
28
"""
29
30
class Sections:
31
def __len__(self):
32
"""Number of sections in document."""
33
34
def __iter__(self):
35
"""Iterate over sections."""
36
37
def __getitem__(self, index):
38
"""Access section by index."""
39
```
40
41
**Usage Examples:**
42
43
```python
44
from docx.enum.section import WD_SECTION_START
45
46
# Access existing sections
47
sections = doc.sections
48
print(f"Document has {len(sections)} sections")
49
50
# Access first section
51
first_section = sections[0]
52
53
# Add new section with page break
54
new_section = doc.add_section(WD_SECTION_START.NEW_PAGE)
55
56
# Add continuous section (no page break)
57
continuous_section = doc.add_section(WD_SECTION_START.CONTINUOUS)
58
59
# Iterate through all sections
60
for i, section in enumerate(doc.sections):
61
print(f"Section {i+1}: {section.page_width.inches}\" x {section.page_height.inches}\"")
62
```
63
64
### Page Setup and Dimensions
65
66
Control page size, orientation, and dimensions.
67
68
```python { .api }
69
class Section:
70
@property
71
def page_width(self):
72
"""Page width (read/write).
73
74
Returns:
75
Length: Page width
76
"""
77
78
@page_width.setter
79
def page_width(self, value):
80
"""Set page width."""
81
82
@property
83
def page_height(self):
84
"""Page height (read/write).
85
86
Returns:
87
Length: Page height
88
"""
89
90
@page_height.setter
91
def page_height(self, value):
92
"""Set page height."""
93
94
@property
95
def orientation(self):
96
"""Page orientation (read/write).
97
98
Returns:
99
WD_ORIENTATION: Current page orientation
100
"""
101
102
@orientation.setter
103
def orientation(self, value):
104
"""Set page orientation."""
105
106
@property
107
def start_type(self):
108
"""Section start type (read/write).
109
110
Returns:
111
WD_SECTION_START: How this section starts
112
"""
113
114
@start_type.setter
115
def start_type(self, value):
116
"""Set section start type."""
117
```
118
119
**Usage Examples:**
120
121
```python
122
from docx.shared import Inches
123
from docx.enum.section import WD_ORIENTATION, WD_SECTION_START
124
125
# Access section for page setup
126
section = doc.sections[0]
127
128
# Set page dimensions (US Letter)
129
section.page_width = Inches(8.5)
130
section.page_height = Inches(11)
131
132
# Set page orientation
133
section.orientation = WD_ORIENTATION.PORTRAIT
134
135
# Create landscape section
136
landscape_section = doc.add_section(WD_SECTION_START.NEW_PAGE)
137
landscape_section.orientation = WD_ORIENTATION.LANDSCAPE
138
139
# For landscape, swap width and height
140
landscape_section.page_width = Inches(11)
141
landscape_section.page_height = Inches(8.5)
142
143
# Common page sizes
144
# US Letter: 8.5" x 11"
145
# A4: 8.27" x 11.69"
146
# Legal: 8.5" x 14"
147
148
# Set A4 page size
149
section.page_width = Inches(8.27)
150
section.page_height = Inches(11.69)
151
```
152
153
### Margin Settings
154
155
Control page margins for precise layout.
156
157
```python { .api }
158
class Section:
159
@property
160
def top_margin(self):
161
"""Top margin (read/write).
162
163
Returns:
164
Length: Top margin distance
165
"""
166
167
@top_margin.setter
168
def top_margin(self, value):
169
"""Set top margin."""
170
171
@property
172
def bottom_margin(self):
173
"""Bottom margin (read/write).
174
175
Returns:
176
Length: Bottom margin distance
177
"""
178
179
@bottom_margin.setter
180
def bottom_margin(self, value):
181
"""Set bottom margin."""
182
183
@property
184
def left_margin(self):
185
"""Left margin (read/write).
186
187
Returns:
188
Length: Left margin distance
189
"""
190
191
@left_margin.setter
192
def left_margin(self, value):
193
"""Set left margin."""
194
195
@property
196
def right_margin(self):
197
"""Right margin (read/write).
198
199
Returns:
200
Length: Right margin distance
201
"""
202
203
@right_margin.setter
204
def right_margin(self, value):
205
"""Set right margin."""
206
```
207
208
**Usage Examples:**
209
210
```python
211
from docx.shared import Inches, Cm
212
213
# Set standard margins (1 inch)
214
section = doc.sections[0]
215
section.top_margin = Inches(1)
216
section.bottom_margin = Inches(1)
217
section.left_margin = Inches(1)
218
section.right_margin = Inches(1)
219
220
# Set narrow margins
221
section.top_margin = Inches(0.5)
222
section.bottom_margin = Inches(0.5)
223
section.left_margin = Inches(0.5)
224
section.right_margin = Inches(0.5)
225
226
# Set different margins for binding
227
section.left_margin = Inches(1.5) # Extra space for binding
228
section.right_margin = Inches(1)
229
section.top_margin = Inches(1)
230
section.bottom_margin = Inches(1)
231
232
# Use metric measurements
233
section.top_margin = Cm(2.5)
234
section.bottom_margin = Cm(2.5)
235
section.left_margin = Cm(3)
236
section.right_margin = Cm(2)
237
```
238
239
### Header Management
240
241
Create and manage section headers.
242
243
```python { .api }
244
class Section:
245
@property
246
def header(self):
247
"""Primary header for this section.
248
249
Returns:
250
_Header: Header object
251
"""
252
253
@property
254
def header_distance(self):
255
"""Distance from top of page to header (read/write).
256
257
Returns:
258
Length: Header distance
259
"""
260
261
@header_distance.setter
262
def header_distance(self, value):
263
"""Set header distance."""
264
265
@property
266
def different_first_page_header_footer(self):
267
"""Whether first page has different header/footer (read/write).
268
269
Returns:
270
bool: True if first page is different
271
"""
272
273
@different_first_page_header_footer.setter
274
def different_first_page_header_footer(self, value):
275
"""Set different first page header/footer."""
276
277
class _Header:
278
def add_paragraph(self, text='', style=None):
279
"""Add a paragraph to the header.
280
281
Args:
282
text (str, optional): Paragraph text
283
style (str or ParagraphStyle, optional): Paragraph style
284
285
Returns:
286
Paragraph: New paragraph object
287
"""
288
289
def add_table(self, rows, cols):
290
"""Add a table to the header.
291
292
Args:
293
rows (int): Number of initial rows
294
cols (int): Number of initial columns
295
296
Returns:
297
Table: New table object
298
"""
299
300
@property
301
def is_linked_to_previous(self):
302
"""Whether header is linked to previous section (read/write).
303
304
Returns:
305
bool: True if linked to previous section
306
"""
307
308
@is_linked_to_previous.setter
309
def is_linked_to_previous(self, value):
310
"""Set link to previous section."""
311
312
@property
313
def paragraphs(self):
314
"""Paragraphs in the header.
315
316
Returns:
317
list[Paragraph]: List of paragraph objects
318
"""
319
320
@property
321
def tables(self):
322
"""Tables in the header.
323
324
Returns:
325
list[Table]: List of table objects
326
"""
327
```
328
329
**Usage Examples:**
330
331
```python
332
from docx.shared import Inches
333
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
334
335
# Access section header
336
section = doc.sections[0]
337
header = section.header
338
339
# Add simple header text
340
header_para = header.add_paragraph("Document Title")
341
header_para.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
342
343
# Add header with different content
344
header.add_paragraph("Chapter 1: Introduction", style='Header')
345
346
# Set header distance from page top
347
section.header_distance = Inches(0.5)
348
349
# Create header with table for complex layout
350
header_table = header.add_table(rows=1, cols=3)
351
header_table.cell(0, 0).text = "Left Header"
352
header_table.cell(0, 1).text = "Center Header"
353
header_table.cell(0, 2).text = "Right Header"
354
355
# Set table alignment
356
header_table.cell(0, 0).paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.LEFT
357
header_table.cell(0, 1).paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
358
header_table.cell(0, 2).paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT
359
360
# Unlink from previous section (create unique header)
361
header.is_linked_to_previous = False
362
363
# Set different first page
364
section.different_first_page_header_footer = True
365
```
366
367
### Footer Management
368
369
Create and manage section footers.
370
371
```python { .api }
372
class Section:
373
@property
374
def footer(self):
375
"""Primary footer for this section.
376
377
Returns:
378
_Footer: Footer object
379
"""
380
381
@property
382
def footer_distance(self):
383
"""Distance from bottom of page to footer (read/write).
384
385
Returns:
386
Length: Footer distance
387
"""
388
389
@footer_distance.setter
390
def footer_distance(self, value):
391
"""Set footer distance."""
392
393
class _Footer:
394
def add_paragraph(self, text='', style=None):
395
"""Add a paragraph to the footer.
396
397
Args:
398
text (str, optional): Paragraph text
399
style (str or ParagraphStyle, optional): Paragraph style
400
401
Returns:
402
Paragraph: New paragraph object
403
"""
404
405
def add_table(self, rows, cols):
406
"""Add a table to the footer.
407
408
Args:
409
rows (int): Number of initial rows
410
cols (int): Number of initial columns
411
412
Returns:
413
Table: New table object
414
"""
415
416
@property
417
def is_linked_to_previous(self):
418
"""Whether footer is linked to previous section (read/write).
419
420
Returns:
421
bool: True if linked to previous section
422
"""
423
424
@is_linked_to_previous.setter
425
def is_linked_to_previous(self, value):
426
"""Set link to previous section."""
427
428
@property
429
def paragraphs(self):
430
"""Paragraphs in the footer.
431
432
Returns:
433
list[Paragraph]: List of paragraph objects
434
"""
435
436
@property
437
def tables(self):
438
"""Tables in the footer.
439
440
Returns:
441
list[Table]: List of table objects
442
"""
443
```
444
445
**Usage Examples:**
446
447
```python
448
from docx.shared import Inches
449
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
450
451
# Access section footer
452
section = doc.sections[0]
453
footer = section.footer
454
455
# Add simple footer text
456
footer_para = footer.add_paragraph("Page Footer")
457
footer_para.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
458
459
# Add footer with page numbers (conceptual - actual page numbers require fields)
460
footer_para = footer.add_paragraph("Page 1")
461
footer_para.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT
462
463
# Set footer distance from page bottom
464
section.footer_distance = Inches(0.5)
465
466
# Create footer with table for layout
467
footer_table = footer.add_table(rows=1, cols=2)
468
footer_table.cell(0, 0).text = "© 2024 Company Name"
469
footer_table.cell(0, 1).text = "Confidential"
470
471
footer_table.cell(0, 0).paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.LEFT
472
footer_table.cell(0, 1).paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT
473
474
# Unlink from previous section
475
footer.is_linked_to_previous = False
476
```
477
478
### Multi-Section Documents
479
480
Create documents with multiple sections having different layouts.
481
482
**Usage Examples:**
483
484
```python
485
from docx.enum.section import WD_ORIENTATION, WD_SECTION_START
486
from docx.shared import Inches
487
488
# Create document with multiple sections
489
doc = Document()
490
491
# First section - portrait title page
492
doc.add_heading('Document Title', 0)
493
doc.add_paragraph('Title page content')
494
495
# Add landscape section for wide table/chart
496
landscape_section = doc.add_section(WD_SECTION_START.NEW_PAGE)
497
landscape_section.orientation = WD_ORIENTATION.LANDSCAPE
498
landscape_section.page_width = Inches(11)
499
landscape_section.page_height = Inches(8.5)
500
501
# Add wide table in landscape section
502
table = doc.add_table(rows=5, cols=8)
503
# ... populate table
504
505
# Add portrait section for continued text
506
portrait_section = doc.add_section(WD_SECTION_START.NEW_PAGE)
507
portrait_section.orientation = WD_ORIENTATION.PORTRAIT
508
portrait_section.page_width = Inches(8.5)
509
portrait_section.page_height = Inches(11)
510
511
doc.add_paragraph('Continued text in portrait orientation')
512
513
# Set different headers for each section
514
# Title page - no header
515
doc.sections[0].header.is_linked_to_previous = False
516
517
# Landscape section - different header
518
doc.sections[1].header.is_linked_to_previous = False
519
doc.sections[1].header.add_paragraph('Data Tables Section')
520
521
# Portrait section - main document header
522
doc.sections[2].header.is_linked_to_previous = False
523
doc.sections[2].header.add_paragraph('Main Document')
524
```
525
526
### Section Break Types
527
528
Control how sections start and flow.
529
530
**Usage Examples:**
531
532
```python
533
from docx.enum.section import WD_SECTION_START
534
535
# Continuous section (no page break)
536
continuous_section = doc.add_section(WD_SECTION_START.CONTINUOUS)
537
538
# New page section (default)
539
new_page_section = doc.add_section(WD_SECTION_START.NEW_PAGE)
540
541
# Even page section (starts on even page)
542
even_page_section = doc.add_section(WD_SECTION_START.EVEN_PAGE)
543
544
# Odd page section (starts on odd page)
545
odd_page_section = doc.add_section(WD_SECTION_START.ODD_PAGE)
546
547
# New column section (for multi-column layouts)
548
new_column_section = doc.add_section(WD_SECTION_START.NEW_COLUMN)
549
550
# Change existing section's start type
551
section = doc.sections[0]
552
section.start_type = WD_SECTION_START.ODD_PAGE
553
```
554
555
### Advanced Layout Techniques
556
557
Complex layout scenarios using sections.
558
559
**Usage Examples:**
560
561
```python
562
# Create document with different margin for chapters
563
def add_chapter(doc, title, content):
564
# Add new section for chapter
565
chapter_section = doc.add_section(WD_SECTION_START.ODD_PAGE)
566
567
# Set chapter-specific margins
568
chapter_section.top_margin = Inches(2) # Extra top margin
569
chapter_section.left_margin = Inches(1.5)
570
571
# Add chapter header
572
header = chapter_section.header
573
header.is_linked_to_previous = False
574
header.add_paragraph(title, style='Header')
575
576
# Add chapter content
577
doc.add_heading(title, level=1)
578
doc.add_paragraph(content)
579
580
return chapter_section
581
582
# Add multiple chapters
583
add_chapter(doc, "Chapter 1: Introduction", "Chapter 1 content...")
584
add_chapter(doc, "Chapter 2: Methods", "Chapter 2 content...")
585
586
# Create appendix with different formatting
587
appendix_section = doc.add_section(WD_SECTION_START.NEW_PAGE)
588
appendix_section.left_margin = Inches(1) # Standard margin
589
appendix_section.right_margin = Inches(1)
590
591
# Different footer for appendix
592
footer = appendix_section.footer
593
footer.is_linked_to_previous = False
594
footer.add_paragraph("Appendix")
595
```
596
597
## Types
598
599
```python { .api }
600
from docx.enum.section import WD_SECTION_START
601
602
class WD_SECTION_START:
603
"""Section start type options."""
604
CONTINUOUS = 0 # No page break
605
NEW_COLUMN = 1 # Start in new column
606
NEW_PAGE = 2 # Start on new page (default)
607
EVEN_PAGE = 3 # Start on next even page
608
ODD_PAGE = 4 # Start on next odd page
609
610
from docx.enum.section import WD_ORIENTATION
611
612
class WD_ORIENTATION:
613
"""Page orientation options."""
614
PORTRAIT = 0 # Height > Width
615
LANDSCAPE = 1 # Width > Height
616
617
from docx.enum.section import WD_HEADER_FOOTER_INDEX
618
619
class WD_HEADER_FOOTER_INDEX:
620
"""Header/footer index options."""
621
PRIMARY = 0 # Primary header/footer
622
FIRST_PAGE = 1 # First page header/footer
623
EVEN_PAGE = 2 # Even page header/footer
624
```