0
# Styles and Formatting
1
2
Comprehensive style management and formatting including paragraph styles, character styles, fonts, colors, measurements, and document-wide style definitions.
3
4
## Capabilities
5
6
### Style Management
7
8
Access and manage document styles collection.
9
10
```python { .api }
11
class Document:
12
@property
13
def styles(self):
14
"""Document styles collection.
15
16
Returns:
17
Styles: Collection of all document styles
18
"""
19
20
class Styles:
21
def add_style(self, name, style_type, builtin=False):
22
"""Add a new style to the document.
23
24
Args:
25
name (str): Style name
26
style_type (WD_STYLE_TYPE): Type of style (paragraph, character, etc.)
27
builtin (bool): Whether style is a built-in Word style
28
29
Returns:
30
BaseStyle: New style object of appropriate type
31
"""
32
33
def get_by_id(self, style_id):
34
"""Get style by its identifier.
35
36
Args:
37
style_id (str): Style identifier
38
39
Returns:
40
BaseStyle or None: Style object or None if not found
41
"""
42
43
def get_style_id(self, name, style_type):
44
"""Get style ID for given name and type.
45
46
Args:
47
name (str): Style name
48
style_type (WD_STYLE_TYPE): Style type
49
50
Returns:
51
str: Style identifier
52
"""
53
54
@property
55
def default(self):
56
"""Default paragraph style.
57
58
Returns:
59
ParagraphStyle: Default paragraph style
60
"""
61
62
@property
63
def latent_styles(self):
64
"""Latent styles collection.
65
66
Returns:
67
LatentStyles: Latent styles collection
68
"""
69
70
def __iter__(self):
71
"""Iterate over all styles."""
72
73
def __len__(self):
74
"""Number of styles in collection."""
75
76
def __getitem__(self, key):
77
"""Access style by name or index."""
78
```
79
80
**Usage Examples:**
81
82
```python
83
from docx.enum.style import WD_STYLE_TYPE
84
85
# Access document styles
86
styles = doc.styles
87
88
# List all styles
89
for style in styles:
90
print(f"{style.name} ({style.type})")
91
92
# Get specific style
93
normal_style = styles['Normal']
94
heading1_style = styles['Heading 1']
95
96
# Add custom paragraph style
97
custom_style = styles.add_style('Custom Para', WD_STYLE_TYPE.PARAGRAPH)
98
custom_style.font.name = 'Arial'
99
custom_style.font.size = Pt(11)
100
101
# Add custom character style
102
char_style = styles.add_style('Highlight', WD_STYLE_TYPE.CHARACTER)
103
char_style.font.highlight_color = WD_COLOR_INDEX.YELLOW
104
```
105
106
### Base Style Properties
107
108
Common properties available to all style types.
109
110
```python { .api }
111
class BaseStyle:
112
@property
113
def name(self):
114
"""Style name (read/write).
115
116
Returns:
117
str: Style display name
118
"""
119
120
@name.setter
121
def name(self, value):
122
"""Set style name."""
123
124
@property
125
def style_id(self):
126
"""Style identifier.
127
128
Returns:
129
str: Internal style identifier
130
"""
131
132
@property
133
def type(self):
134
"""Style type.
135
136
Returns:
137
WD_STYLE_TYPE: Style type (paragraph, character, etc.)
138
"""
139
140
@property
141
def builtin(self):
142
"""Whether style is built-in.
143
144
Returns:
145
bool: True if built-in Word style
146
"""
147
148
@property
149
def hidden(self):
150
"""Whether style is hidden (read/write).
151
152
Returns:
153
bool: True if style is hidden from UI
154
"""
155
156
@hidden.setter
157
def hidden(self, value):
158
"""Set hidden status."""
159
160
@property
161
def locked(self):
162
"""Whether style is locked (read/write).
163
164
Returns:
165
bool: True if style is locked from editing
166
"""
167
168
@locked.setter
169
def locked(self, value):
170
"""Set locked status."""
171
172
@property
173
def priority(self):
174
"""Style priority (read/write).
175
176
Returns:
177
int: Style priority for sorting (lower = higher priority)
178
"""
179
180
@priority.setter
181
def priority(self, value):
182
"""Set style priority."""
183
184
@property
185
def quick_style(self):
186
"""Whether appears in quick style gallery (read/write).
187
188
Returns:
189
bool: True if appears in quick style gallery
190
"""
191
192
@quick_style.setter
193
def quick_style(self, value):
194
"""Set quick style status."""
195
196
@property
197
def unhide_when_used(self):
198
"""Whether to unhide when used (read/write).
199
200
Returns:
201
bool: True if style unhides when used
202
"""
203
204
@unhide_when_used.setter
205
def unhide_when_used(self, value):
206
"""Set unhide when used."""
207
208
@property
209
def delete(self):
210
"""Mark style for deletion (write-only).
211
212
Setting to True marks style for deletion.
213
"""
214
215
@delete.setter
216
def delete(self, value):
217
"""Mark style for deletion."""
218
```
219
220
### Character Styles
221
222
Character-level formatting styles that can be applied to runs.
223
224
```python { .api }
225
class CharacterStyle(BaseStyle):
226
@property
227
def base_style(self):
228
"""Base style this style inherits from (read/write).
229
230
Returns:
231
CharacterStyle or None: Base character style
232
"""
233
234
@base_style.setter
235
def base_style(self, value):
236
"""Set base style."""
237
238
@property
239
def font(self):
240
"""Font formatting for this style.
241
242
Returns:
243
Font: Font formatting object
244
"""
245
```
246
247
**Usage Examples:**
248
249
```python
250
# Create custom character style
251
char_style = styles.add_style('Emphasis', WD_STYLE_TYPE.CHARACTER)
252
char_style.font.italic = True
253
char_style.font.color.rgb = RGBColor(128, 0, 0) # Dark red
254
255
# Apply character style to run
256
para = doc.add_paragraph('Normal text with ')
257
run = para.add_run('emphasized text')
258
run.style = char_style
259
para.add_run(' and more normal text.')
260
```
261
262
### Paragraph Styles
263
264
Paragraph-level styles that include both paragraph and character formatting.
265
266
```python { .api }
267
class ParagraphStyle(CharacterStyle):
268
@property
269
def next_paragraph_style(self):
270
"""Style for next paragraph (read/write).
271
272
Returns:
273
ParagraphStyle or None: Style automatically applied to next paragraph
274
"""
275
276
@next_paragraph_style.setter
277
def next_paragraph_style(self, value):
278
"""Set next paragraph style."""
279
280
@property
281
def paragraph_format(self):
282
"""Paragraph formatting for this style.
283
284
Returns:
285
ParagraphFormat: Paragraph formatting object
286
"""
287
```
288
289
**Usage Examples:**
290
291
```python
292
from docx.shared import Pt, Inches
293
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
294
295
# Create custom paragraph style
296
para_style = styles.add_style('Custom Heading', WD_STYLE_TYPE.PARAGRAPH)
297
298
# Set font properties
299
para_style.font.name = 'Arial'
300
para_style.font.size = Pt(16)
301
para_style.font.bold = True
302
para_style.font.color.rgb = RGBColor(0, 0, 128) # Dark blue
303
304
# Set paragraph formatting
305
para_style.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
306
para_style.paragraph_format.space_after = Pt(12)
307
para_style.paragraph_format.keep_with_next = True
308
309
# Set next paragraph style
310
para_style.next_paragraph_style = styles['Normal']
311
312
# Apply paragraph style
313
heading = doc.add_paragraph('Custom Heading Text', style=para_style)
314
```
315
316
### Built-in Styles
317
318
Access to Word's built-in styles through enumeration.
319
320
```python { .api }
321
from docx.enum.style import WD_BUILTIN_STYLE
322
323
class WD_BUILTIN_STYLE:
324
"""Built-in style identifiers."""
325
NORMAL = -1
326
HEADING_1 = -2
327
HEADING_2 = -3
328
HEADING_3 = -4
329
HEADING_4 = -5
330
HEADING_5 = -6
331
HEADING_6 = -7
332
HEADING_7 = -8
333
HEADING_8 = -9
334
HEADING_9 = -10
335
TITLE = -63
336
SUBTITLE = -75
337
QUOTE = -181
338
INTENSE_QUOTE = -182
339
# ... over 200 additional built-in styles
340
```
341
342
**Usage Examples:**
343
344
```python
345
from docx.enum.style import WD_BUILTIN_STYLE
346
347
# Access built-in styles by name
348
normal = styles['Normal']
349
heading1 = styles['Heading 1']
350
title = styles['Title']
351
quote = styles['Quote']
352
353
# Access by built-in style enum (alternative method)
354
# Note: These provide the style IDs for programmatic access
355
title_id = WD_BUILTIN_STYLE.TITLE
356
quote_id = WD_BUILTIN_STYLE.QUOTE
357
358
# Apply built-in styles
359
doc.add_paragraph('Document Title', style='Title')
360
doc.add_paragraph('This is a quote.', style='Quote')
361
doc.add_heading('Chapter 1', level=1) # Uses Heading 1 style
362
```
363
364
### Color Formatting
365
366
Comprehensive color formatting for fonts and highlighting.
367
368
```python { .api }
369
class ColorFormat:
370
@property
371
def rgb(self):
372
"""RGB color value (read/write).
373
374
Returns:
375
RGBColor or None: RGB color specification
376
"""
377
378
@rgb.setter
379
def rgb(self, value):
380
"""Set RGB color."""
381
382
@property
383
def theme_color(self):
384
"""Theme color (read/write).
385
386
Returns:
387
MSO_THEME_COLOR_INDEX or None: Theme color index
388
"""
389
390
@theme_color.setter
391
def theme_color(self, value):
392
"""Set theme color."""
393
394
@property
395
def type(self):
396
"""Color type.
397
398
Returns:
399
MSO_COLOR_TYPE: Type of color (RGB, theme, auto, etc.)
400
"""
401
402
class RGBColor(tuple):
403
"""RGB color specification."""
404
405
def __new__(cls, r, g, b):
406
"""Create RGB color.
407
408
Args:
409
r (int): Red component (0-255)
410
g (int): Green component (0-255)
411
b (int): Blue component (0-255)
412
"""
413
return tuple.__new__(cls, (r, g, b))
414
```
415
416
**Usage Examples:**
417
418
```python
419
from docx.shared import RGBColor
420
from docx.enum.dml import MSO_THEME_COLOR_INDEX
421
422
# Set RGB color
423
run = para.add_run('Red text')
424
run.font.color.rgb = RGBColor(255, 0, 0)
425
426
# Set theme color
427
run = para.add_run('Accent color text')
428
run.font.color.theme_color = MSO_THEME_COLOR_INDEX.ACCENT_1
429
430
# Check color type
431
color_format = run.font.color
432
if color_format.type == MSO_COLOR_TYPE.RGB:
433
print(f"RGB color: {color_format.rgb}")
434
elif color_format.type == MSO_COLOR_TYPE.SCHEME:
435
print(f"Theme color: {color_format.theme_color}")
436
```
437
438
### Measurement Classes
439
440
Precise measurement units for formatting.
441
442
```python { .api }
443
class Length(int):
444
"""Base measurement class in English Metric Units (EMUs)."""
445
446
@property
447
def inches(self):
448
"""Value in inches.
449
450
Returns:
451
float: Length in inches
452
"""
453
454
@property
455
def cm(self):
456
"""Value in centimeters.
457
458
Returns:
459
float: Length in centimeters
460
"""
461
462
@property
463
def mm(self):
464
"""Value in millimeters.
465
466
Returns:
467
float: Length in millimeters
468
"""
469
470
@property
471
def pt(self):
472
"""Value in points.
473
474
Returns:
475
float: Length in points
476
"""
477
478
@property
479
def twips(self):
480
"""Value in twips.
481
482
Returns:
483
float: Length in twips
484
"""
485
486
@property
487
def emu(self):
488
"""Value in English Metric Units.
489
490
Returns:
491
int: Length in EMUs
492
"""
493
494
def Inches(inches):
495
"""Create Length from inches.
496
497
Args:
498
inches (float): Length in inches
499
500
Returns:
501
Length: Length object
502
"""
503
504
def Cm(cm):
505
"""Create Length from centimeters.
506
507
Args:
508
cm (float): Length in centimeters
509
510
Returns:
511
Length: Length object
512
"""
513
514
def Mm(mm):
515
"""Create Length from millimeters.
516
517
Args:
518
mm (float): Length in millimeters
519
520
Returns:
521
Length: Length object
522
"""
523
524
def Pt(points):
525
"""Create Length from points.
526
527
Args:
528
points (float): Length in points
529
530
Returns:
531
Length: Length object
532
"""
533
534
def Emu(emu):
535
"""Create Length from English Metric Units.
536
537
Args:
538
emu (int): Length in EMUs
539
540
Returns:
541
Length: Length object
542
"""
543
544
def Twips(twips):
545
"""Create Length from twips.
546
547
Args:
548
twips (int): Length in twips
549
550
Returns:
551
Length: Length object
552
"""
553
```
554
555
**Usage Examples:**
556
557
```python
558
from docx.shared import Inches, Cm, Mm, Pt
559
560
# Create measurements
561
margin = Inches(1.0)
562
indent = Cm(1.5)
563
spacing = Mm(6)
564
font_size = Pt(12)
565
566
# Use in formatting
567
para_format = para.paragraph_format
568
para_format.left_indent = indent
569
para_format.space_after = spacing
570
571
font = run.font
572
font.size = font_size
573
574
# Convert between units
575
print(f"1 inch = {Inches(1).cm} cm")
576
print(f"12 pt = {Pt(12).mm} mm")
577
```
578
579
### Latent Styles
580
581
Management of latent (available but not loaded) styles.
582
583
```python { .api }
584
class LatentStyles:
585
@property
586
def default_priority(self):
587
"""Default priority for latent styles (read/write).
588
589
Returns:
590
int: Default priority
591
"""
592
593
@default_priority.setter
594
def default_priority(self, value):
595
"""Set default priority."""
596
597
@property
598
def default_to_locked(self):
599
"""Default locked setting (read/write).
600
601
Returns:
602
bool: Default locked setting for latent styles
603
"""
604
605
@default_to_locked.setter
606
def default_to_locked(self, value):
607
"""Set default locked setting."""
608
609
@property
610
def default_to_quick_style(self):
611
"""Default quick style setting (read/write).
612
613
Returns:
614
bool: Default quick style setting
615
"""
616
617
@default_to_quick_style.setter
618
def default_to_quick_style(self, value):
619
"""Set default quick style setting."""
620
621
@property
622
def default_to_unhide_when_used(self):
623
"""Default unhide when used setting (read/write).
624
625
Returns:
626
bool: Default unhide when used setting
627
"""
628
629
@default_to_unhide_when_used.setter
630
def default_to_unhide_when_used(self, value):
631
"""Set default unhide when used setting."""
632
633
@property
634
def load_count(self):
635
"""Number of latent styles to load (read/write).
636
637
Returns:
638
int: Number of styles to load
639
"""
640
641
@load_count.setter
642
def load_count(self, value):
643
"""Set load count."""
644
```
645
646
## Types
647
648
```python { .api }
649
from docx.enum.style import WD_STYLE_TYPE
650
651
class WD_STYLE_TYPE:
652
"""Style type options."""
653
CHARACTER = 2
654
LIST = 4
655
PARAGRAPH = 1
656
TABLE = 3
657
658
from docx.enum.dml import MSO_COLOR_TYPE
659
660
class MSO_COLOR_TYPE:
661
"""Color type options."""
662
AUTO = 101
663
RGB = 1
664
SCHEME = 2
665
UNSET = 0
666
667
from docx.enum.dml import MSO_THEME_COLOR_INDEX
668
669
class MSO_THEME_COLOR_INDEX:
670
"""Theme color index options."""
671
ACCENT_1 = 5
672
ACCENT_2 = 6
673
ACCENT_3 = 7
674
ACCENT_4 = 8
675
ACCENT_5 = 9
676
ACCENT_6 = 10
677
BACKGROUND_1 = 15
678
BACKGROUND_2 = 16
679
DARK_1 = 1
680
DARK_2 = 3
681
FOLLOWED_HYPERLINK = 12
682
HYPERLINK = 11
683
LIGHT_1 = 2
684
LIGHT_2 = 4
685
NOT_THEME_COLOR = 0
686
TEXT_1 = 13
687
TEXT_2 = 14
688
```