0
# Text and Paragraphs
1
2
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.
3
4
## Capabilities
5
6
### Paragraph Creation
7
8
Add paragraphs with optional text content and styling.
9
10
```python { .api }
11
class Document:
12
def add_paragraph(self, text='', style=None):
13
"""Add a paragraph to the document.
14
15
Args:
16
text (str, optional): Initial paragraph text
17
style (str or ParagraphStyle, optional): Paragraph style name or object
18
19
Returns:
20
Paragraph: New paragraph object
21
"""
22
23
def add_heading(self, text='', level=1):
24
"""Add a heading paragraph.
25
26
Args:
27
text (str, optional): Heading text
28
level (int): Heading level (0-9, where 0 is Title style)
29
30
Returns:
31
Paragraph: New heading paragraph
32
"""
33
```
34
35
**Usage Examples:**
36
37
```python
38
# Add simple paragraph
39
para = doc.add_paragraph('This is a simple paragraph.')
40
41
# Add paragraph with style
42
styled_para = doc.add_paragraph('Styled paragraph', style='Quote')
43
44
# Add headings
45
title = doc.add_heading('Document Title', level=0) # Title style
46
heading1 = doc.add_heading('Chapter 1', level=1) # Heading 1
47
heading2 = doc.add_heading('Section 1.1', level=2) # Heading 2
48
```
49
50
### Paragraph Properties and Methods
51
52
Access and manipulate paragraph content and formatting.
53
54
```python { .api }
55
class Paragraph:
56
def add_run(self, text=None, style=None):
57
"""Add a run of text to the paragraph.
58
59
Args:
60
text (str, optional): Run text content
61
style (str or CharacterStyle, optional): Character style
62
63
Returns:
64
Run: New run object
65
"""
66
67
def clear(self):
68
"""Remove all content from paragraph, keeping the paragraph element."""
69
70
def insert_paragraph_before(self, text='', style=None):
71
"""Insert a new paragraph before this one.
72
73
Args:
74
text (str, optional): New paragraph text
75
style (str or ParagraphStyle, optional): Paragraph style
76
77
Returns:
78
Paragraph: New paragraph object
79
"""
80
81
@property
82
def text(self):
83
"""Plain text content of paragraph (read/write).
84
85
Setting this property replaces all paragraph content with plain text.
86
"""
87
88
@text.setter
89
def text(self, value):
90
"""Set paragraph text content."""
91
92
@property
93
def runs(self):
94
"""List of runs in the paragraph.
95
96
Returns:
97
list[Run]: All run objects in paragraph
98
"""
99
100
@property
101
def style(self):
102
"""Paragraph style (read/write).
103
104
Returns:
105
ParagraphStyle or None: Current paragraph style
106
"""
107
108
@style.setter
109
def style(self, value):
110
"""Set paragraph style."""
111
112
@property
113
def paragraph_format(self):
114
"""Paragraph formatting object.
115
116
Returns:
117
ParagraphFormat: Formatting properties for paragraph
118
"""
119
120
@property
121
def alignment(self):
122
"""Paragraph alignment (read/write).
123
124
Returns:
125
WD_PARAGRAPH_ALIGNMENT or None: Current alignment
126
"""
127
128
@alignment.setter
129
def alignment(self, value):
130
"""Set paragraph alignment."""
131
```
132
133
**Usage Examples:**
134
135
```python
136
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
137
138
# Create paragraph with multiple runs
139
para = doc.add_paragraph()
140
para.add_run('This is normal text. ')
141
para.add_run('This is bold text.').bold = True
142
para.add_run(' This is italic text.').italic = True
143
144
# Set paragraph alignment
145
para.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
146
147
# Access paragraph text
148
print(f"Paragraph text: {para.text}")
149
150
# Clear and reset paragraph
151
para.clear()
152
para.text = "New paragraph content"
153
154
# Insert paragraph before existing one
155
new_para = para.insert_paragraph_before("This paragraph comes first")
156
```
157
158
### Run Properties and Methods
159
160
Manipulate individual runs of text with character formatting.
161
162
```python { .api }
163
class Run:
164
def add_break(self, break_type=None):
165
"""Add a break to the run.
166
167
Args:
168
break_type (WD_BREAK_TYPE, optional): Type of break to add
169
"""
170
171
def add_tab(self):
172
"""Add a tab character to the run."""
173
174
def add_picture(self, image_path_or_stream, width=None, height=None):
175
"""Add an inline picture to the run.
176
177
Args:
178
image_path_or_stream (str or file-like): Image file path or stream
179
width (Length, optional): Picture width
180
height (Length, optional): Picture height
181
182
Returns:
183
InlineShape: New inline shape object
184
"""
185
186
def clear(self):
187
"""Remove all content from run, keeping the run element."""
188
189
@property
190
def text(self):
191
"""Run text content (read/write)."""
192
193
@text.setter
194
def text(self, value):
195
"""Set run text content."""
196
197
@property
198
def style(self):
199
"""Character style (read/write).
200
201
Returns:
202
CharacterStyle or None: Current character style
203
"""
204
205
@style.setter
206
def style(self, value):
207
"""Set character style."""
208
209
@property
210
def bold(self):
211
"""Bold formatting (read/write).
212
213
Returns:
214
bool or None: True/False for explicit bold, None for inherit
215
"""
216
217
@bold.setter
218
def bold(self, value):
219
"""Set bold formatting."""
220
221
@property
222
def italic(self):
223
"""Italic formatting (read/write).
224
225
Returns:
226
bool or None: True/False for explicit italic, None for inherit
227
"""
228
229
@italic.setter
230
def italic(self, value):
231
"""Set italic formatting."""
232
233
@property
234
def underline(self):
235
"""Underline formatting (read/write).
236
237
Returns:
238
bool, WD_UNDERLINE, or None: Underline setting
239
"""
240
241
@underline.setter
242
def underline(self, value):
243
"""Set underline formatting."""
244
245
@property
246
def font(self):
247
"""Font formatting object.
248
249
Returns:
250
Font: Font formatting properties
251
"""
252
```
253
254
**Usage Examples:**
255
256
```python
257
from docx.enum.text import WD_BREAK_TYPE
258
from docx.shared import Inches
259
260
# Create and format runs
261
run = para.add_run('Formatted text')
262
run.bold = True
263
run.italic = True
264
run.underline = True
265
266
# Add breaks
267
run.add_break(WD_BREAK_TYPE.LINE) # Line break
268
run.add_break(WD_BREAK_TYPE.PAGE) # Page break
269
270
# Add tab
271
run.add_tab()
272
273
# Add picture to run
274
run.add_picture('image.png', width=Inches(1))
275
276
# Clear run content
277
run.clear()
278
run.text = "New run content"
279
```
280
281
### Font Formatting
282
283
Detailed character formatting through Font objects.
284
285
```python { .api }
286
class Font:
287
@property
288
def name(self):
289
"""Font name (read/write).
290
291
Returns:
292
str or None: Font name like 'Arial', 'Times New Roman'
293
"""
294
295
@name.setter
296
def name(self, value):
297
"""Set font name."""
298
299
@property
300
def size(self):
301
"""Font size (read/write).
302
303
Returns:
304
Length or None: Font size in points (Pt objects)
305
"""
306
307
@size.setter
308
def size(self, value):
309
"""Set font size."""
310
311
@property
312
def bold(self):
313
"""Bold formatting (read/write).
314
315
Returns:
316
bool or None: Bold setting
317
"""
318
319
@bold.setter
320
def bold(self, value):
321
"""Set bold formatting."""
322
323
@property
324
def italic(self):
325
"""Italic formatting (read/write).
326
327
Returns:
328
bool or None: Italic setting
329
"""
330
331
@italic.setter
332
def italic(self, value):
333
"""Set italic formatting."""
334
335
@property
336
def underline(self):
337
"""Underline formatting (read/write).
338
339
Returns:
340
bool, WD_UNDERLINE, or None: Underline setting
341
"""
342
343
@underline.setter
344
def underline(self, value):
345
"""Set underline formatting."""
346
347
@property
348
def strike(self):
349
"""Strikethrough formatting (read/write).
350
351
Returns:
352
bool or None: Strike setting
353
"""
354
355
@strike.setter
356
def strike(self, value):
357
"""Set strikethrough formatting."""
358
359
@property
360
def subscript(self):
361
"""Subscript formatting (read/write).
362
363
Returns:
364
bool or None: Subscript setting
365
"""
366
367
@subscript.setter
368
def subscript(self, value):
369
"""Set subscript formatting."""
370
371
@property
372
def superscript(self):
373
"""Superscript formatting (read/write).
374
375
Returns:
376
bool or None: Superscript setting
377
"""
378
379
@superscript.setter
380
def superscript(self, value):
381
"""Set superscript formatting."""
382
383
@property
384
def color(self):
385
"""Font color formatting.
386
387
Returns:
388
ColorFormat: Color formatting object
389
"""
390
391
@property
392
def highlight_color(self):
393
"""Text highlight color (read/write).
394
395
Returns:
396
WD_COLOR_INDEX or None: Highlight color
397
"""
398
399
@highlight_color.setter
400
def highlight_color(self, value):
401
"""Set highlight color."""
402
403
@property
404
def all_caps(self):
405
"""All caps formatting (read/write).
406
407
Returns:
408
bool or None: All caps setting
409
"""
410
411
@all_caps.setter
412
def all_caps(self, value):
413
"""Set all caps formatting."""
414
415
@property
416
def small_caps(self):
417
"""Small caps formatting (read/write).
418
419
Returns:
420
bool or None: Small caps setting
421
"""
422
423
@small_caps.setter
424
def small_caps(self, value):
425
"""Set small caps formatting."""
426
```
427
428
**Usage Examples:**
429
430
```python
431
from docx.shared import Pt, RGBColor
432
from docx.enum.text import WD_COLOR_INDEX, WD_UNDERLINE
433
434
# Access font through run
435
run = para.add_run('Formatted text')
436
font = run.font
437
438
# Set basic font properties
439
font.name = 'Arial'
440
font.size = Pt(12)
441
font.bold = True
442
font.italic = True
443
444
# Set underline style
445
font.underline = WD_UNDERLINE.SINGLE
446
447
# Set font color
448
font.color.rgb = RGBColor(255, 0, 0) # Red
449
450
# Set highlight color
451
font.highlight_color = WD_COLOR_INDEX.YELLOW
452
453
# Set special formatting
454
font.all_caps = True
455
font.strike = True
456
font.subscript = True # Note: subscript and superscript are mutually exclusive
457
```
458
459
### Paragraph Formatting
460
461
Advanced paragraph formatting through ParagraphFormat objects.
462
463
```python { .api }
464
class ParagraphFormat:
465
@property
466
def alignment(self):
467
"""Paragraph alignment (read/write).
468
469
Returns:
470
WD_PARAGRAPH_ALIGNMENT or None: Alignment setting
471
"""
472
473
@alignment.setter
474
def alignment(self, value):
475
"""Set paragraph alignment."""
476
477
@property
478
def left_indent(self):
479
"""Left indent (read/write).
480
481
Returns:
482
Length or None: Left indent distance
483
"""
484
485
@left_indent.setter
486
def left_indent(self, value):
487
"""Set left indent."""
488
489
@property
490
def right_indent(self):
491
"""Right indent (read/write).
492
493
Returns:
494
Length or None: Right indent distance
495
"""
496
497
@right_indent.setter
498
def right_indent(self, value):
499
"""Set right indent."""
500
501
@property
502
def first_line_indent(self):
503
"""First line indent (read/write).
504
505
Returns:
506
Length or None: First line indent distance
507
"""
508
509
@first_line_indent.setter
510
def first_line_indent(self, value):
511
"""Set first line indent."""
512
513
@property
514
def space_before(self):
515
"""Space before paragraph (read/write).
516
517
Returns:
518
Length or None: Space before distance
519
"""
520
521
@space_before.setter
522
def space_before(self, value):
523
"""Set space before paragraph."""
524
525
@property
526
def space_after(self):
527
"""Space after paragraph (read/write).
528
529
Returns:
530
Length or None: Space after distance
531
"""
532
533
@space_after.setter
534
def space_after(self, value):
535
"""Set space after paragraph."""
536
537
@property
538
def line_spacing(self):
539
"""Line spacing (read/write).
540
541
Returns:
542
float, Length, or None: Line spacing value
543
"""
544
545
@line_spacing.setter
546
def line_spacing(self, value):
547
"""Set line spacing."""
548
549
@property
550
def line_spacing_rule(self):
551
"""Line spacing rule (read/write).
552
553
Returns:
554
WD_LINE_SPACING or None: Line spacing rule
555
"""
556
557
@line_spacing_rule.setter
558
def line_spacing_rule(self, value):
559
"""Set line spacing rule."""
560
561
@property
562
def keep_together(self):
563
"""Keep paragraph together on page (read/write).
564
565
Returns:
566
bool or None: Keep together setting
567
"""
568
569
@keep_together.setter
570
def keep_together(self, value):
571
"""Set keep together."""
572
573
@property
574
def keep_with_next(self):
575
"""Keep with next paragraph (read/write).
576
577
Returns:
578
bool or None: Keep with next setting
579
"""
580
581
@keep_with_next.setter
582
def keep_with_next(self, value):
583
"""Set keep with next."""
584
585
@property
586
def page_break_before(self):
587
"""Page break before paragraph (read/write).
588
589
Returns:
590
bool or None: Page break before setting
591
"""
592
593
@page_break_before.setter
594
def page_break_before(self, value):
595
"""Set page break before."""
596
597
@property
598
def widow_control(self):
599
"""Widow/orphan control (read/write).
600
601
Returns:
602
bool or None: Widow control setting
603
"""
604
605
@widow_control.setter
606
def widow_control(self, value):
607
"""Set widow control."""
608
609
@property
610
def tab_stops(self):
611
"""Tab stops collection.
612
613
Returns:
614
TabStops: Tab stops collection object
615
"""
616
```
617
618
**Usage Examples:**
619
620
```python
621
from docx.shared import Inches, Pt
622
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT, WD_LINE_SPACING
623
624
# Access paragraph format
625
para = doc.add_paragraph('Formatted paragraph')
626
fmt = para.paragraph_format
627
628
# Set alignment and indentation
629
fmt.alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY
630
fmt.left_indent = Inches(0.5)
631
fmt.right_indent = Inches(0.25)
632
fmt.first_line_indent = Inches(0.25)
633
634
# Set spacing
635
fmt.space_before = Pt(6)
636
fmt.space_after = Pt(6)
637
fmt.line_spacing = 1.5
638
fmt.line_spacing_rule = WD_LINE_SPACING.MULTIPLE
639
640
# Set page control options
641
fmt.keep_together = True
642
fmt.keep_with_next = True
643
fmt.page_break_before = False
644
fmt.widow_control = True
645
```
646
647
### Tab Stops
648
649
Manage paragraph tab stops for precise text alignment.
650
651
```python { .api }
652
class TabStops:
653
def add_tab_stop(self, position, alignment=None, leader=None):
654
"""Add a tab stop.
655
656
Args:
657
position (Length): Tab stop position from left margin
658
alignment (WD_TAB_ALIGNMENT, optional): Tab alignment
659
leader (WD_TAB_LEADER, optional): Tab leader character
660
661
Returns:
662
TabStop: New tab stop object
663
"""
664
665
def clear_all(self):
666
"""Remove all custom tab stops."""
667
668
class TabStop:
669
@property
670
def position(self):
671
"""Tab stop position from left margin.
672
673
Returns:
674
Length: Position distance
675
"""
676
677
@property
678
def alignment(self):
679
"""Tab alignment.
680
681
Returns:
682
WD_TAB_ALIGNMENT: Alignment setting
683
"""
684
685
@property
686
def leader(self):
687
"""Tab leader character.
688
689
Returns:
690
WD_TAB_LEADER: Leader setting
691
"""
692
```
693
694
**Usage Examples:**
695
696
```python
697
from docx.shared import Inches
698
from docx.enum.text import WD_TAB_ALIGNMENT, WD_TAB_LEADER
699
700
# Add tab stops to paragraph
701
para = doc.add_paragraph()
702
tabs = para.paragraph_format.tab_stops
703
704
# Add different types of tab stops
705
tabs.add_tab_stop(Inches(1), WD_TAB_ALIGNMENT.LEFT)
706
tabs.add_tab_stop(Inches(3), WD_TAB_ALIGNMENT.CENTER)
707
tabs.add_tab_stop(Inches(5), WD_TAB_ALIGNMENT.RIGHT, WD_TAB_LEADER.DOTS)
708
709
# Add content with tabs
710
run = para.add_run("Left\tCenter\tRight with dots")
711
```
712
713
## Types
714
715
```python { .api }
716
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
717
718
class WD_PARAGRAPH_ALIGNMENT:
719
"""Paragraph alignment options."""
720
LEFT = 0
721
CENTER = 1
722
RIGHT = 2
723
JUSTIFY = 3
724
DISTRIBUTE = 4
725
726
from docx.enum.text import WD_BREAK_TYPE
727
728
class WD_BREAK_TYPE:
729
"""Break type options."""
730
COLUMN = 8
731
LINE = 6
732
LINE_CLEAR_LEFT = 9
733
LINE_CLEAR_RIGHT = 11
734
PAGE = 7
735
TEXT_WRAPPING = 5
736
737
from docx.enum.text import WD_LINE_SPACING
738
739
class WD_LINE_SPACING:
740
"""Line spacing rule options."""
741
SINGLE = 0
742
ONE_POINT_FIVE = 1
743
DOUBLE = 2
744
AT_LEAST = 3
745
EXACTLY = 4
746
MULTIPLE = 5
747
748
from docx.enum.text import WD_UNDERLINE
749
750
class WD_UNDERLINE:
751
"""Underline type options."""
752
NONE = 0
753
SINGLE = 1
754
WORDS = 2
755
DOUBLE = 3
756
DOTTED = 4
757
THICK = 6
758
DASH = 7
759
DOT_DASH = 9
760
DOT_DOT_DASH = 10
761
WAVY = 11
762
763
from docx.enum.text import WD_COLOR_INDEX
764
765
class WD_COLOR_INDEX:
766
"""Text highlight color options."""
767
AUTO = 0
768
BLACK = 1
769
BLUE = 2
770
BRIGHT_GREEN = 4
771
DARK_BLUE = 9
772
DARK_RED = 13
773
DARK_YELLOW = 14
774
GRAY_25 = 16
775
GRAY_50 = 15
776
GREEN = 11
777
PINK = 5
778
RED = 6
779
TEAL = 10
780
TURQUOISE = 3
781
VIOLET = 12
782
WHITE = 8
783
YELLOW = 7
784
785
from docx.enum.text import WD_TAB_ALIGNMENT
786
787
class WD_TAB_ALIGNMENT:
788
"""Tab alignment options."""
789
LEFT = 0
790
CENTER = 1
791
RIGHT = 2
792
DECIMAL = 3
793
BAR = 4
794
LIST = 6
795
CLEAR = 7
796
797
from docx.enum.text import WD_TAB_LEADER
798
799
class WD_TAB_LEADER:
800
"""Tab leader options."""
801
SPACES = 0
802
DOTS = 1
803
DASHES = 2
804
LINES = 3
805
HEAVY = 4
806
MIDDLE_DOT = 5
807
```