Format Document Content Directly
- 16 minutes to read
Direct formatting settings apply to individual text fragments and paragraphs. The Word Processing Document API stores direct formatting settings in the following objects:
| Object | Access | Settings |
|---|---|---|
| CharacterProperties | TextFragment.CharacterProperties | Font, font size, colors, underline, text effects, character spacing, and language. |
| ParagraphProperties | Paragraph.Properties | Alignment, indents, spacing, line spacing, pagination, borders, shading, and tab stops. |
Direct formatting takes precedence over style formatting. Most CharacterProperties and ParagraphProperties properties are nullable. If a property is set to null, the text fragment or paragraph has no direct setting and gets the setting from applied styles.
When you load a document, CharacterProperties and ParagraphProperties objects contain direct formatting settings from the document. Properties whose values come from styles are null.
Refer to the following help topic for additional information about styles: Apply Styles to Document Content.
Measurement Units
Formatting properties accept values in the following units:
| Unit | Properties |
|---|---|
| Document units (1/300 of an inch) | CharacterProperties.Spacing, paragraph indents and spacing, line height in ParagraphLineSpacing values, border width and offset, and tab stop positions. |
| Points | CharacterProperties.FontSize, CharacterProperties.Position, and CharacterProperties.KerningThreshold. |
| Percent | CharacterProperties.Scale. |
Character Formatting
Use the TextFragment.CharacterProperties property to format a text fragment. The Paragraph.AddText(text) method adds a text fragment to a paragraph and returns the TextFragment object.
The following code snippet creates a paragraph and applies font, size, bold, color, underline, and superscript formatting to text fragments:
using System.Drawing;
using System.IO;
using DevExpress.Docs;
using DevExpress.Docs.Office;
using DevExpress.Docs.Word;
using var document = new WordDocument();
var paragraph = document.Body.AddParagraph();
paragraph.AddText("Project status: ");
var status = paragraph.AddText("On schedule");
var properties = status.CharacterProperties;
properties.Font.Name = "Arial";
properties.FontSize = 14;
properties.Bold = true;
properties.ForeColor = new OfficeColor(Color.DarkGreen);
properties.Underline = TextUnderlineType.Single;
paragraph.AddText(". Budget spent: 85%");
var noteMark = paragraph.AddText("1");
noteMark.CharacterProperties.Script = TextScriptType.Superscript;
Directory.CreateDirectory("output");
using var stream = File.Create(Path.Combine("output", "Document.docx"));
document.Save(stream, DocumentFormat.Docx);
Font Settings
Use the following properties to specify the font and font style:
| Property | Description |
|---|---|
| Font | Gets fonts for text in different character sets. |
| FontSize | Gets or sets the font size in points. |
| Bold | Gets or sets whether to apply bold text formatting. |
| Italic | Gets or sets whether to apply italic text formatting. |
Colors
Use the following properties to specify text colors:
| Property | Description |
|---|---|
| ForeColor | Gets or sets the text color. |
| BackColor | Gets or sets the text background color (shading). |
| HighlightColor | Gets or sets the text highlight color. |
| UnderlineColor | Gets or sets the underline color. |
Assign an OfficeColor object to a color property (for example, new OfficeColor(Color.DarkGreen)).
Note
Word document formats support a limited set of highlight colors. If you specify another highlight color, the saved document contains the nearest supported color (for example, yellow instead of orange).
Text Effects
Use the following properties to underline, strike out, capitalize, raise, lower, or hide text:
| Property | Description |
|---|---|
| Underline | Gets or sets the underline type. |
| Strikeout | Gets or sets strikethrough text formatting. |
| AllCaps | Gets or sets whether to display all letters as capital letters. |
| SmallCaps | Gets or sets whether to display lowercase letters as small capital letters. |
| Script | Gets or sets superscript or subscript text formatting. |
| Hidden | Gets or sets whether text is hidden. |
Character Spacing and Position
Use the following properties to adjust the distance between characters, the character width, and the vertical text position:
| Property | Description |
|---|---|
| Spacing | Gets or sets the space between characters in Document units (1/300 of an inch). |
| Scale | Gets or sets the character width scale as a percentage. |
| Position | Gets or sets the vertical text position relative to the baseline in points. |
| KerningThreshold | Gets or sets the minimum font size for kerning in points. |
Language and Proofing
Use the following properties to specify the text language, proofing options, and East Asian text layout:
| Property | Description |
|---|---|
| Language | Gets or sets the text language. |
| NoProof | Gets or sets whether to exclude text from spelling and grammar checks. |
| SnapToGrid | Gets or sets whether to align characters to the document grid. |
Specify Fonts for Different Character Sets
A text fragment can contain characters from different character sets (for example, Latin and East Asian characters). The TextFont object (the CharacterProperties.Font property value) stores a font for each character set:
| Property | Description |
|---|---|
| Name | Gets or sets the font name. |
| Ascii | Gets or sets the font for ASCII characters (Unicode characters from U+0000 to U+007F). |
| HighAnsi | Gets or sets the font for characters that are not ASCII, East Asian, or complex script characters (for example, Latin letters with diacritical marks). |
| EastAsia | Gets or sets the font for East Asian characters (for example, Chinese, Japanese, and Korean characters). |
| ComplexScript | Gets or sets the font for complex script characters (for example, Arabic and Hebrew characters). |
When you set the Name property, the API assigns the font to Ascii, HighAnsi, and ComplexScript properties and removes theme fonts.
To apply a document theme font to text, use ThemeAscii, ThemeHighAnsi, ThemeEastAsia, and ThemeComplexScript properties. A theme font replaces the font name for the same character set. If you modify the document theme, text formatting that refers to the theme reflects the modified fonts.
The following code snippet applies the theme heading font to a heading and specifies separate fonts for Latin and East Asian characters in a paragraph:
using System.IO;
using DevExpress.Docs.Word;
using var document = new WordDocument();
var heading = document.Body.AddParagraph();
var headingFont = heading.AddText("Regional Offices").CharacterProperties.Font;
headingFont.ThemeAscii = TextThemeFont.HeadingsAscii;
headingFont.ThemeHighAnsi = TextThemeFont.HeadingsHighAnsi;
var paragraph = document.Body.AddParagraph();
var font = paragraph.AddText("Tokyo office (東京オフィス)").CharacterProperties.Font;
font.Ascii = "Calibri";
font.HighAnsi = "Calibri";
font.EastAsia = "Yu Gothic";
Directory.CreateDirectory("output");
using var stream = File.Create(Path.Combine("output", "Document.docx"));
document.Save(stream, DocumentFormat.Docx);
Refer to the following help topic for additional information about theme fonts: Apply Document Themes.
Paragraph Formatting
Use the Paragraph.Properties property to format a paragraph.
The following code snippet creates a centered heading and a justified paragraph with a first-line indent, 1.5 line spacing, and spacing after the paragraph:
using System.IO;
using DevExpress.Docs.Word;
using var document = new WordDocument();
// Indents and spacing are in Document units (1/300 of an inch).
var heading = document.Body.AddParagraph("Quarterly Report");
heading.Properties.Alignment = ParagraphAlignment.Center;
heading.Properties.SpacingAfter = 50;
heading.Properties.KeepWithNext = true;
var body = document.Body.AddParagraph("The team delivered all planned milestones for the quarter. The project remains on schedule and within budget.");
var properties = body.Properties;
properties.Alignment = ParagraphAlignment.Justify;
properties.FirstLineIndent = 150;
properties.LineSpacing = ParagraphLineSpacing.OneAndHalf;
properties.SpacingAfter = 50;
Directory.CreateDirectory("output");
using var stream = File.Create(Path.Combine("output", "Document.docx"));
document.Save(stream, DocumentFormat.Docx);
Alignment and Indents
Use the following properties to align paragraph text and specify paragraph indents:
| Property | Description |
|---|---|
| Alignment | Gets or sets paragraph text alignment. |
| LeftIndent | Gets or sets the left paragraph indent in document units. |
| RightIndent | Gets or sets the right paragraph indent in document units. |
| FirstLineIndent | Gets or sets the first line indent in document units. |
| RightToLeft | Gets or sets whether the paragraph uses right-to-left text direction. |
A positive FirstLineIndent value indents the first line. A negative value specifies a hanging indent. For example, to create a 0.5-inch hanging indent, set the LeftIndent property to 150 and the FirstLineIndent property to -150.
Spacing
Use the following properties to specify the space between paragraphs and between lines in a paragraph:
| Property | Description |
|---|---|
| SpacingBefore | Gets or sets the spacing before the paragraph in document units. |
| SpacingAfter | Gets or sets the spacing after the paragraph in document units. |
| ContextualSpacing | Gets or sets whether to ignore spacing before and after the paragraph if adjacent paragraphs have the same style. |
| LineSpacing | Gets or sets line spacing in the paragraph. |
Use the following ParagraphLineSpacing members to create a line spacing value:
| Member | Line Spacing |
|---|---|
| ParagraphLineSpacing.Single, ParagraphLineSpacing.OneAndHalf, ParagraphLineSpacing.Double | Single, 1.5, and double line spacing. |
| ParagraphLineSpacing.Multiple(multiplier) | Returns a line spacing value that is a multiple of single line spacing. |
| ParagraphLineSpacing.Exactly(height) | Returns a line spacing value that specifies a fixed line height. |
| ParagraphLineSpacing.AtLeast(height) | Returns a line spacing value that specifies the minimum line height. |
Pagination and Text Flow
Use the following properties to control how paragraphs break across pages:
| Property | Description |
|---|---|
| KeepWithNext | Gets or sets whether the paragraph stays on the same page as the next paragraph. |
| KeepLinesTogether | Gets or sets whether all paragraph lines stay on the same page. |
| PageBreakBefore | Gets or sets whether the paragraph starts on a new page. |
| WidowOrphanControl | Gets or sets whether to prevent the first or last paragraph line from appearing alone on a page. |
| SuppressHyphenation | Gets or sets whether to disable automatic hyphenation for the paragraph. |
| SuppressLineNumbers | Gets or sets whether to suppress line numbers for the paragraph. |
Outline Level
Use the OutlineLevel property to specify the paragraph level in the document outline. The 0 value specifies body text. Values from 1 to 9 specify outline levels. Microsoft Word displays paragraphs with outline levels in the Navigation pane.
Borders and Shading
Use the Borders property to access paragraph borders. The ParagraphBorders object contains the following borders:
| Property | Description |
|---|---|
| LeftBorder | Gets the left paragraph border. |
| TopBorder | Gets the top paragraph border. |
| RightBorder | Gets the right paragraph border. |
| BottomBorder | Gets the bottom paragraph border. |
| HorizontalBorder | Gets the border between paragraphs with the same border settings. |
Use the following ParagraphBorder properties to customize a border:
| Property | Description |
|---|---|
| LineStyle | Gets or sets the border line style. |
| LineWidth | Gets or sets the border line width in Document units (1/300 of an inch). |
| LineColor | Gets or sets the border line color. |
| Offset | Gets or sets the distance between the border and paragraph text in Document units (1/300 of an inch). |
Use the BackColor property to specify the paragraph background color.
The following code snippet adds a box border and a background color to a paragraph:
using System.Drawing;
using System.IO;
using DevExpress.Docs;
using DevExpress.Docs.Word;
using var document = new WordDocument();
var note = document.Body.AddParagraph("The service is unavailable during scheduled maintenance.");
var properties = note.Properties;
properties.BackColor = new OfficeColor(Color.LightYellow);
var borders = properties.Borders;
foreach (var border in new[] { borders.LeftBorder, borders.TopBorder, borders.RightBorder, borders.BottomBorder }) {
border.LineStyle = BorderLineStyle.Single;
// 1.5 points in Document units (1/300 of an inch).
border.LineWidth = 6.25f;
border.LineColor = new OfficeColor(Color.SteelBlue);
// 3 points in Document units.
border.Offset = 12.5f;
}
Directory.CreateDirectory("output");
using var stream = File.Create(Path.Combine("output", "Document.docx"));
document.Save(stream, DocumentFormat.Docx);
Tab Stops
Use the TabStops property to access custom tab stops in a paragraph. A TabStop value specifies the tab stop position, alignment, and leader characters. Pass a TabStop value to the TabStopCollection.Add(item) method to add a tab stop.
The TabStopCollection sorts tab stops by position. A paragraph can contain a single tab stop at a position. If the collection contains a tab stop at the same position, the Add method replaces this tab stop.
Call the following methods to find and remove tab stops:
| Method | Description |
|---|---|
| TabStopCollection.Contains(position) | Returns whether the collection contains a tab stop at the specified position. |
| TabStopCollection.TryGet(position, out tabStop) | Returns whether the collection contains a tab stop at the specified position and gets this tab stop. |
| TabStopCollection.Remove(item) | Removes the specified tab stop from the collection. |
| TabStopCollection.RemoveAtPosition(position) | Removes the tab stop at the specified position. |
| TabStopCollection.RemoveAt(index) | Removes the tab stop at the specified index. |
| TabStopCollection.Clear() | Removes all tab stops from the collection. |
The following code snippet adds a right-aligned tab stop with a dot leader to paragraphs and creates a list of document sections with page numbers:
using System.IO;
using DevExpress.Docs.Word;
using var document = new WordDocument();
var entries = new[] { "Introduction\t1", "Project Scope\t3", "Schedule\t7" };
foreach (var entry in entries) {
var paragraph = document.Body.AddParagraph(entry);
// 6.5 inches in Document units (1/300 of an inch).
paragraph.Properties.TabStops.Add(new TabStop(1950, TabAlignment.Right, TabLeader.Dots));
}
Directory.CreateDirectory("output");
using var stream = File.Create(Path.Combine("output", "Document.docx"));
document.Save(stream, DocumentFormat.Docx);
Reuse Formatting Settings
To apply the same formatting settings to multiple text fragments or paragraphs, create a CharacterProperties or ParagraphProperties object and assign it to TextFragment.CharacterProperties or Paragraph.Properties properties. You can also pass a CharacterProperties object to the TextFragment(text, characterProperties) constructor.
Call the CharacterProperties.Clone() or ParagraphProperties.Clone() method to copy formatting settings from one text fragment or paragraph to another.
The following code snippet creates a text fragment with bold dark red text and copies paragraph formatting settings from the first paragraph to the second paragraph:
var warning = new CharacterProperties {
Bold = true,
ForeColor = new OfficeColor(Color.DarkRed)
};
var first = document.Body.AddParagraph();
first.InlineElements.Add(new TextFragment("Warning: ", warning));
first.AddText("Back up the database before the upgrade.");
first.Properties.SpacingAfter = 50;
first.Properties.Borders.LeftBorder.LineStyle = BorderLineStyle.Thick;
var second = document.Body.AddParagraph("Stop the application service.");
second.Properties = first.Properties.Clone();
Clear Direct Formatting
To remove direct formatting settings, use one of the following techniques:
- Set a property to
null(Nothingin VB.NET) to remove a single setting (for example,CharacterProperties.Bold). - Set the
TextFragment.CharacterPropertiesorParagraph.Propertiesproperty tonullto remove all direct formatting settings. The property gets a new object with no settings. - Call the ParagraphBorders.Reset() method to remove all paragraph borders, or the ParagraphBorder.Reset() method to remove a single border.
- Call the
TabStopCollection.Clear()method to remove custom tab stops.
After you remove direct formatting settings, text fragments and paragraphs get formatting settings from applied styles.
The following code snippet removes direct formatting settings from paragraphs and text fragments at the top level of the document body:
foreach (var paragraph in document.Body.OfType<Paragraph>()) {
paragraph.Properties = null;
foreach (var fragment in paragraph.InlineElements.OfType<TextFragment>())
fragment.CharacterProperties = null;
}
Specify Default Formatting for a Document
Document defaults specify formatting settings for all text and paragraphs in a document. Document defaults have the lowest priority among formatting sources. A text fragment or paragraph gets a default setting if direct formatting and applied styles do not specify this setting.
Use the following properties to access document defaults:
| Property | Description |
|---|---|
| WordDocument.DefaultCharacterProperties | Gets default character formatting settings for the document. |
| WordDocument.DefaultParagraphProperties | Gets default paragraph formatting settings for the document. |
DocumentDefaultCharacterProperties and DocumentDefaultParagraphProperties classes contain the same formatting properties as CharacterProperties and ParagraphProperties classes (except tab stops). If you modify document defaults, existing document content reflects the modified settings.
If a DocumentDefaultCharacterProperties property is set to null, document defaults do not specify the corresponding setting.
Document defaults must define every paragraph setting except the background color. If you set a DocumentDefaultParagraphProperties property other than BackColor to null, the API throws an InvalidOperationException.
To apply document defaults to a text fragment or paragraph as direct formatting, call the DocumentDefaultCharacterProperties.Clone() or DocumentDefaultParagraphProperties.Clone() method. Assign the result to the TextFragment.CharacterProperties or Paragraph.Properties property.
The following code snippet specifies the default font, font size, spacing after paragraphs, and line spacing for a document:
using System.IO;
using DevExpress.Docs.Word;
using var document = new WordDocument();
// Specify default character formatting settings.
var characterDefaults = document.DefaultCharacterProperties;
characterDefaults.Font.Name = "Arial";
characterDefaults.FontSize = 12;
// Specify default paragraph formatting settings.
// Spacing is in document units (1/300 of an inch).
var paragraphDefaults = document.DefaultParagraphProperties;
paragraphDefaults.SpacingAfter = 50;
paragraphDefaults.LineSpacing = ParagraphLineSpacing.Multiple(1.15f);
document.Body.AddParagraph("Paragraphs and text without direct formatting use document defaults.");
document.Body.AddParagraph("Styles and direct formatting take precedence over document defaults.");
Directory.CreateDirectory("output");
using var stream = File.Create(Path.Combine("output", "Document.docx"));
document.Save(stream, DocumentFormat.Docx);