Styles and formatting
Formatting in a Word document comes from styles, named sets of formatting in the document's style table, plus optional direct formatting on individual paragraphs and runs. DocWright models both exactly as Word does.
Define and apply a style
using DocWright.Core.Document;
using DocWright.Core.Primitives;
using DocWright.Dom;
using DocWright.Dom.Editing;
using var document = new WordDocument();
Section section = document.AppendSection();
// A paragraph style: a real Word style that shows in Word's Styles pane.
var heading = new Style("SectionHeading", StyleType.Paragraph)
{
Name = "Section Heading",
QuickFormat = true,
CharacterFormat = new CharacterFormat
{
Bold = true,
FontSize = Twips.FromPoints(16),
Color = new DocColor(ColorRgb.FromRgb(0x1E, 0x3A, 0x8A)),
},
ParagraphFormat = new ParagraphFormat
{
SpacingBefore = Twips.FromPoints(18),
SpacingAfter = Twips.FromPoints(6),
KeepNext = true,
OutlineLevel = 0, // appears in the navigation pane and as H1 in tagged PDF
},
};
document.Styles.Add(heading);
section.AppendParagraph("Findings").ApplyStyle("SectionHeading");
Paragraph body = section.AppendParagraph("All fire exits were clear. ");
// Direct formatting on top of the style, for one run only.
body.AppendText("Two extinguishers were past their service date.",
new CharacterFormat { Bold = true, Highlight = HighlightColor.Yellow });
section.AppendParagraph("Actions").ApplyStyle("SectionHeading");
section.AppendParagraph("Replace both extinguishers by 15 October.")
.ApplyFormatting(new ParagraphFormat { Alignment = ParagraphAlignment.Center });

| Call | Does |
|---|---|
document.Styles.Add(style) |
Adds a style to the document's style table. |
paragraph.ApplyStyle(id) / run.ApplyStyle(id) |
References a paragraph or character style by its id. |
paragraph.ApplyFormatting(ParagraphFormat) |
Adds direct paragraph formatting. Only the properties you set are changed; the rest keep inheriting. |
run.ApplyFormatting(CharacterFormat) |
The same for a run of text. |
range.ApplyFormatting(...), range.ApplyStyle(id) |
The same for every paragraph or run in a DocumentRange. |
Styles are checked
ApplyStyle throws InvalidDocumentException (code DXP1002) when the style doesn't exist, or is the wrong kind:
using DocWright.Core;
using DocWright.Dom.Editing;
try
{
section.AppendParagraph("Oops").ApplyStyle("Heading9"); // not in this document
}
catch (InvalidDocumentException ex)
{
Console.WriteLine(ex.Message);
}
Output
DXP1002: the document defines no style with id 'Heading9'; applying it would leave a dangling reference that resolves to nothing.
A reference to a style that doesn't exist would be silently ignored at render time, so the formatting you asked for would never appear. Failing early is kinder.
Edit style definitions
Word's Styles pane changes the definitions themselves, and every paragraph in the style follows. These are undoable edits, with Word's rules (WQ-0103):
using DocWright.Core.Document;
using DocWright.Core.Primitives;
using DocWright.Dom;
using DocWright.Dom.Editing;
using DocWright.Layout;
// Modify Style: every Heading 1 turns green and centred.
document.FormatStyle(caret, "Heading1", s =>
{
(s.CharacterFormat ??= new CharacterFormat()).Color = new DocColor(ColorRgb.FromRgb(0x00, 0xB0, 0x50));
(s.ParagraphFormat ??= new ParagraphFormat()).Alignment = ParagraphAlignment.Center;
});
// Create a Style from the italic paragraph, and apply it there.
document.CreateStyleFromSelection(selection, "Pull quote");
StyleFormatting quote = StyleResolver.ResolveStyleFormatting(document, "Pullquote");
Console.WriteLine($"Pullquote: italic {quote.Character.Italic}, linked {document.Styles.Find("Pullquote")!.LinkedStyleId}");
Console.WriteLine($"Heading 1: {StyleResolver.ResolveStyleFormatting(document, "Heading1").Paragraph.Alignment}");
Output
Pullquote: italic True, linked PullquoteChar
Heading 1: Center

| Call | Does |
|---|---|
document.FormatStyle(at, id, change) |
Modify Style: changes the definition; direct formatting stays. A paragraph style's run formatting is copied to its linked character style. |
document.UpdateStyleToMatch(span) |
Update to Match Selection: the paragraph's style takes its direct formatting, then is reapplied to every paragraph in it. Direct paragraph formatting goes; a direct run property on more than half of a paragraph's characters goes. |
document.CreateStyleFromSelection(span, name) |
Create a Style: a paragraph style plus its linked name Char style, applied to the selected paragraphs. |
StyleResolver.ResolveStyleFormatting(document, id) |
What a style resolves to through its chain, without direct formatting. |
Document defaults
Word's Manage Styles > Set Defaults changes the document's defaults (w:docDefaults), the layer every style resolves
over. SetDocumentDefaults replaces them as one undoable edit: every paragraph is reported changed, and no style's own
properties move (WQ-0123).
DocumentEdit edit = document.SetDocumentDefaults(DocumentPosition.StartOf(paragraph), defaults =>
{
(defaults.CharacterFormat ??= new CharacterFormat()).FontSize = new Twips(360); // 18 pt
(defaults.ParagraphFormat ??= new ParagraphFormat()).SpacingAfter = new Twips(200);
});
An empty w:rPrDefault or w:pPrDefault is not the same as none (WQ-0163). Word gives a document that lacks one its own
application defaults for that half (Aptos, 8pt after, 1.16 lines in Microsoft 365) and a document that states one, even
empty, the specification's (Times New Roman 10pt, no spacing). DocDefaults.DeclaresRunDefaults and
DeclaresParagraphDefaults record which halves a document states: the DOCX reader sets them from the package, so a
document is saved with exactly the halves it was read with, and a document built in memory states both.
using DocWright.Dom;
using WordDocument document = converter.Load(new MemoryStream(source));
DocDefaults defaults = document.Styles.DocDefaults;
Console.WriteLine($"Read: w:rPrDefault stated {defaults.DeclaresRunDefaults}, w:pPrDefault stated {defaults.DeclaresParagraphDefaults}");
using var saved = new MemoryStream();
converter.Save(document, saved); // written back as read: Word keeps its own defaults
Console.WriteLine($"Saved as read: {DocDefaultsXml(saved)}");
defaults.DeclaresRunDefaults = true; // state the specification's run defaults
defaults.DeclaresParagraphDefaults = true;
using var stated = new MemoryStream();
converter.Save(document, stated);
Console.WriteLine($"Saved stated: {DocDefaultsXml(stated)}");
Read: w:rPrDefault stated False, w:pPrDefault stated False
Saved as read: (no w:docDefaults)
Saved stated: <w:docDefaults><w:rPrDefault /><w:pPrDefault /></w:docDefaults>
StyleUsage.Spans(document, styleId) lists every use of a style as spans in document order (whole paragraphs for a
paragraph style, each consecutive-run stretch for a character style): what Word's "Select All N Instances" selects.
Word's built-in styles
A Word document holds Heading 1, Quote or Strong only once someone has used them. ApplyBuiltInStyle applies one by
name and, the first time, adds Word's own definition of it, with the linked … Char style of a linked paragraph style,
as Word does (WQ-0106). The document's own style of the name is used when it has one, whatever its id:
using DocWright.Dom;
using DocWright.Dom.Editing;
int before = document.Styles.Styles.Count;
// Title is in the document already; Quote and Strong are not, and are added as Word defines them.
document.ApplyBuiltInStyle(new DocumentSpan(title, title), "Title");
document.ApplyBuiltInStyle(new DocumentSpan(quote, quote), "Quote");
document.ApplyBuiltInStyle(word, "Strong");
Console.WriteLine($"Styles added: {document.Styles.Styles.Count - before}");
foreach (string id in new[] { "Quote", "QuoteChar", "Strong" })
{
Style style = document.Styles.Find(id)!;
Console.WriteLine($"{id,-10} {style.Type,-9} \"{style.Name}\" linked to {style.LinkedStyleId ?? "-"}");
}
Console.WriteLine($"The library: {BuiltInStyles.Names.Count} styles, from \"{BuiltInStyles.Names[0]}\" to \"{BuiltInStyles.Names[^1]}\"");
Output
Styles added: 3
Quote Paragraph "Quote" linked to QuoteChar
QuoteChar Character "Quote Char" linked to Quote
Strong Character "Strong" linked to -
The library: 23 styles, from "heading 1" to "Book Title"

| Call | Does |
|---|---|
document.ApplyBuiltInStyle(span, name) |
Applies the style named (ignoring case: heading 1 is how Word writes it), adding Word's definition when the document has none. A paragraph style goes to every paragraph the span touches, a character style to the text it covers. A style hidden until used is unhidden. One undo step. |
BuiltInStyles.Names |
The 23 styles of the library: headings 1 to 9, Title, Subtitle, Quote, Intense Quote, List Paragraph, No Spacing, Caption, and the character styles of the Styles gallery. |
BuiltInStyles.Find(name) |
A copy of Word's definition, or null. |
These are the definitions Word gives a document it did not create, not those of its new-document template (whose Heading 1 is 20 pt rather than 16 pt).
Number a style
Modify Style > Format > Numbering is SetStyleList(caret, styleId, template): a new list from a ListLibrary template,
the style's w:numPr naming it and the list's first level naming the style, as Word writes it (WQ-0120). Every
paragraph of the style is then numbered; null is None. One undoable edit, which takes the list away too.
document.SetStyleList(DocumentPosition.StartOf(paragraph), "Callout", ListLibrary.Numbering[0]);
Delete a style
The Styles pane's Delete: DeleteStyle removes a style as one undoable edit, the way Word does it (WQ-0109).
StyleUsage.Count says how often the text uses each style, for an "in use" list.
using DocWright.Dom;
using DocWright.Dom.Editing;
IReadOnlyDictionary<string, int> uses = StyleUsage.Count(document);
Console.WriteLine($"Pull quote is used {uses["Pullquote"]} time(s); can delete: {document.CanDeleteStyle("Pullquote")}");
Console.WriteLine($"Heading 1 can be deleted: {document.CanDeleteStyle("Heading1")} (one of Word's {(BuiltInStyles.IsWordStyleName("heading 1") ? "built-in" : "custom")} styles)");
DocumentEdit edit = document.DeleteStyle(caret, "Pullquote");
Console.WriteLine($"After Delete: style {first.Format.StyleId ?? "Normal"}, alignment {first.Format.Alignment}, Pull quote Char kept: {document.Styles.Find("PullquoteChar") is not null}");
edit.Undo();
Console.WriteLine($"After Undo: style {first.Format.StyleId}");
Pull quote is used 1 time(s); can delete: True
Heading 1 can be deleted: False (one of Word's built-in styles)
After Delete: style Normal, alignment Center, Pull quote Char kept: False
After Undo: style Pullquote
| Call | Does |
|---|---|
document.CanDeleteStyle(id) |
False for a default style, a numbering style and Word's built-in styles, recognised by name (BuiltInStyles.IsWordStyleName, 376 names) whatever customStyle says. |
document.DeleteStyle(caret, id) |
Its paragraphs become Normal and its runs and tables lose it; direct formatting stays. A style based on it is rebased on the default style and keeps its look; a next naming it names Normal. A linked pair goes together, but the … Char half of a built-in style goes alone. |
StyleUsage.Count(document) |
Style id to its uses: paragraphs, stretches of runs, tables; body, headers, footers and notes. |
The formatting model
Every property on CharacterFormat and ParagraphFormat is nullable. null means "inherit": from the paragraph's style, its base style, and finally the document defaults. This matches how Word stores formatting, and it's why saving a document writes back only what was really set.
Common CharacterFormat properties |
Common ParagraphFormat properties |
|---|---|
Bold, Italic, Underline, Strike |
Alignment |
FontSize (Twips), FontAscii (the font name) |
SpacingBefore, SpacingAfter, LineSpacing |
Color (DocColor), Highlight, Shading |
IndentLeft, IndentRight, IndentFirstLine, IndentHanging |
Caps, SmallCaps, Vanish (hidden) |
KeepNext, KeepLines, PageBreakBefore, WidowControl |
CharacterSpacing, Kerning, Position |
OutlineLevel, Borders, Tabs |
Lists
paragraph.AppendToList(numberingId, level) puts a paragraph into an existing list definition from document.Numbering. It references the list rather than copying it, so numbering continues instead of restarting. To create new lists from code, Composition's List(...) writes the numbering definition for you.