Back to Devexpress

Text Formatting

wpf-118199-controls-and-libraries-rich-text-editor-text-formatting.md

latest27.3 KB
Original Source

Text Formatting

  • Feb 24, 2025
  • 11 minutes to read

The Rich Text Editor provides two ways to format document text in code and via User Interface.

Direct FormattingAllows you to change individual formatting attributes for a given range.Document StylesAllow you to change multiple attributes at the same time and apply them to different document fragments. Styles created in code are automatically available to end users. If you change the style settings, all linked document fragments will be updated automatically.

Default Formatting

Use the following properties to set the default character and paragraph formatting for a loaded or newly created document.

The code snippet below illustrates how to apply default formatting to a loaded document.

csharp
private void RichEditControl1_DocumentLoaded(object sender, EventArgs e)
{
    // Set the default font, size and forecolor
    richEditControl.Document.DefaultCharacterProperties.FontName = "Arial";
    richEditControl.Document.DefaultCharacterProperties.FontSize = 16;
    richEditControl.Document.DefaultCharacterProperties.ForeColor = Color.Red;

    // Specify the default alignment
    richEditControl.Document.DefaultParagraphProperties.Alignment = ParagraphAlignment.Center;
    richEditControl.Document.AppendText("Document created at " + DateTime.Now.ToLongTimeString());
}
vb
Private Sub RichEditControl1_DocumentLoaded(ByVal sender As Object, ByVal e As EventArgs)
    ' Set the default font, size and forecolor
    richEditControl.Document.DefaultCharacterProperties.FontName = "Arial"
    richEditControl.Document.DefaultCharacterProperties.FontSize = 16
    richEditControl.Document.DefaultCharacterProperties.ForeColor = Color.Red

    ' Specify the default alignment
    richEditControl.Document.DefaultParagraphProperties.Alignment = ParagraphAlignment.Center
    richEditControl.Document.AppendText("Document created at " & Date.Now.ToLongTimeString())
End Sub

The static RichEditControlCompatibility.DefaultFontSize and RichEditControlCompatibility.DefaultFontName properties set the default font settings for all RichEditControl instances in the application. Specify these properties before initialization of all controls, in the Main method, as illustrated in the following code.

View Example

csharp
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    DevExpress.XtraRichEdit.RichEditControlCompatibility.DefaultFontSize = 8;
    DevExpress.XtraRichEdit.RichEditControlCompatibility.DefaultFontName = "Tahoma";
    Application.Run(new Form1());
}
vb
<STAThread> _
Shared Sub Main()
    Application.EnableVisualStyles()
    Application.SetCompatibleTextRenderingDefault(False)
    DevExpress.XtraRichEdit.RichEditControlCompatibility.DefaultFontSize = 8
    DevExpress.XtraRichEdit.RichEditControlCompatibility.DefaultFontName = "Tahoma"
    Application.Run(New Form1())
End Sub

Important

Starting with v19.2, the Rich Text Editor uses document themes to retrieve default font information. As such, the RichEditControlCompatibility.DefaultFontName property does no longer affect the default document font. Set the RichEditControlCompatibility.UseThemeFonts property to false to restore previous behavior and use the DefaultFontName property.

Direct Formatting

Use both character and paragraph formatting for a specific document range, for instance, for the document title as shown below.

Format Characters

The following members allow you to change character formatting for a given range.

MemberDescription
SubDocument.BeginUpdateCharactersInitiates the update session and provides access to CharacterProperties for the specified range.
CharacterPropertiesHolds the character formatting options.
SubDocument.EndUpdateCharactersFinalizes the character formatting update.

The code sample below uses this API to modify the text color and the font type.

View Example

csharp
//The target range is the first paragraph
DocumentRange range = document.Paragraphs[0].Range;

//Provide access to the character properties
CharacterProperties titleFormatting = document.BeginUpdateCharacters(range);

//Set the character size, font name and color
titleFormatting.FontSize = 20;
titleFormatting.FontName = "Helvetica";
titleFormatting.ForeColor = Color.DarkBlue;

document.EndUpdateCharacters(titleFormatting);
vb
'The target range is the first paragraph
Dim range As DocumentRange = document.Paragraphs(0).Range

'Provide access to the character properties
Dim titleFormatting As CharacterProperties = document.BeginUpdateCharacters(range)

'Set the character size, font name and color
titleFormatting.FontSize = 20
titleFormatting.FontName = "Helvetica"
titleFormatting.ForeColor = Color.DarkBlue

document.EndUpdateCharacters(titleFormatting)

Tip

You can embed fonts used in a document so that the document can be viewed and printed on any computer, regardless of whether the font is installed on that computer. To do that, set the Document.EmbedFonts property to true before saving the document. Refer to the following example for a complete cod sample: How to: Embed Fonts Used in a Document.

Theme Fonts

The Rich Text Editor supports theme fonts. A document theme contains two sets of fonts (Headings and Body). Each set includes font names for different languages. You can use the following properties to specify these fonts for a specific document range:

PropertyDescription
CharacterPropertiesBase.ThemeFontAsciiSpecifies the theme font used to format Unicode (U+0000–U+007F) characters. If the ThemeFontAscii is not specified, CharacterPropertiesBase.FontNameAscii property determines the theme font.
CharacterPropertiesBase.ThemeFontEastAsiaSpecifies the theme font used to format East Asian Unicode characters. If the ThemeFontEastAsia is not specified, the CharacterPropertiesBase.FontNameEastAsia property determines the theme font.
CharacterPropertiesBase.ThemeFontHighAnsiSpecifies the theme font used to format High ANSI characters. If the ThemeFontHighAnsi is not specified, the CharacterPropertiesBase.FontNameHighAnsi property determines the theme font.
CharacterPropertiesBase.ThemeFontComplexScriptSpecifies the name of the Complex Script theme font. If the ThemeFontComplexScript is not specified, the CharacterPropertiesBase.FontNameComplexScript property determines the theme font.

You can use the Document.Theme property to specify Body and Heading fonts used in the document for Latin, Complex Script and East Asian languages. Create a new DocumentTheme object and pass it as the Theme property value, as shown in the code sample below:

csharp
//Create a new DocumentTheme object:
DocumentTheme theme = new DocumentTheme();

//Specify Body and Heading fonts for Complex Script...
theme.BodyComplexScript = "Microsoft Sans Serif";
theme.HeadingsComplexScript = "Tahoma";

//...Latin...
theme.HeadingsLatin = "Segoe UI Semilight";
theme.BodyLatin = "Times New Roman";

//..and East Asian languages:
theme.HeadingsEastAsia = "DengXian Light";
theme.BodyEastAsia = "DengXian";

//Set the created object as the Theme property value:
doc.Theme = theme;

// Specify theme font types used for Complex Script and East Asian languages:
CharacterProperties fontProperties = doc.BeginUpdateCharacters(doc.Range);

fontProperties.ThemeFontComplexScript = ThemeFont.HeadingsComplexScript;
fontProperties.ThemeFontEastAsia = ThemeFont.BodyEastAsia;

doc.EndUpdateCharacters(fontProperties);

//Save the result:
doc.SaveDocument("123456.docx", DocumentFormat.Docx);
vb
'Create a new DocumentTheme object:
Dim theme As New DocumentTheme()

'Specify Body and Heading fonts for Complex Script...
theme.BodyComplexScript = "Microsoft Sans Serif"
theme.HeadingsComplexScript = "Tahoma"

'...Latin...
theme.HeadingsLatin = "Segoe UI Semilight"
theme.BodyLatin = "Times New Roman"

'..and East Asian languages:
theme.HeadingsEastAsia = "DengXian Light"
theme.BodyEastAsia = "DengXian"

'Set the created object as the Theme property value:
doc.Theme = theme

'Specify theme font types used for Complex Script and East Asian languages:
Dim fontProperties As CharacterProperties = doc.BeginUpdateCharacters(doc.Range)
fontProperties.ThemeFontComplexScript = ThemeFont.HeadingsComplexScript
fontProperties.ThemeFontEastAsia = ThemeFont.BodyEastAsia
doc.EndUpdateCharacters(fontProperties)

'Save the result:
doc.SaveDocument("123456.docx", DocumentFormat.Docx)

Custom Fonts

The Rich Text Editor ships with the DXFontRepository class that allows you to use fonts that are not installed on the current operating system. When you load a document that uses such fonts, the Rich Text Editor substitutes missing fonts with the fonts available on the current machine. The DXFontRepository class allows you to load and use custom fonts in your application to prevent font substitution when documents are displayed, printed, or exported to PDF.

Refer to this help topic for details: How to: Load and Use Custom Fonts in the Rich Text Editor.

Format Paragraphs

Use the following API to change the title’s alignment, left indent or any other paragraph option.

MemberDescription
SubDocument.BeginUpdateParagraphsInitiates the update session and provides access to the ParagraphProperties for the specified range.
ParagraphPropertiesSpecifies the paragraph formatting properties.
SubDocument.EndUpdateParagraphsFinalizes the character formatting update.

View Example

csharp
//The target range is the first paragraph
DocumentRange titleParagraph = document.Paragraphs[0].Range;

//Provide access to the paragraph options 
ParagraphProperties titleParagraphFormatting = document.BeginUpdateParagraphs(titleParagraph);

//Set the paragraph alignment
titleParagraphFormatting.Alignment = ParagraphAlignment.Center;

//Set left indent at 0.5".
//Default unit is 1/300 of an inch (a document unit).
titleParagraphFormatting.LeftIndent = Units.InchesToDocumentsF(0.5f);
titleParagraphFormatting.SpacingAfter = Units.InchesToDocumentsF(0.3f);

//Set tab stop at 1.5"
TabInfoCollection tbiColl = titleParagraphFormatting.BeginUpdateTabs(true);
TabInfo tbi = new TabInfo();
tbi.Alignment = TabAlignmentType.Center;
tbi.Position = Units.InchesToDocumentsF(1.5f);
tbiColl.Add(tbi);
titleParagraphFormatting.EndUpdateTabs(tbiColl);

document.EndUpdateParagraphs(titleParagraphFormatting);
vb
'The target range is the first paragraph
Dim titleParagraph As DocumentRange = document.Paragraphs(0).Range

'Provide access to the paragraph options 
Dim titleParagraphFormatting As ParagraphProperties = document.BeginUpdateParagraphs(titleParagraph)

'Set the paragraph alignment
titleParagraphFormatting.Alignment = ParagraphAlignment.Center

'Set left indent at 0.5".
'Default unit is 1/300 of an inch (a document unit).
titleParagraphFormatting.LeftIndent = Units.InchesToDocumentsF(0.5F)
titleParagraphFormatting.SpacingAfter = Units.InchesToDocumentsF(0.3F)

'Set tab stop at 1.5"
Dim tbiColl As TabInfoCollection = titleParagraphFormatting.BeginUpdateTabs(True)
Dim tbi As New TabInfo()
tbi.Alignment = TabAlignmentType.Center
tbi.Position = Units.InchesToDocumentsF(1.5F)
tbiColl.Add(tbi)
titleParagraphFormatting.EndUpdateTabs(tbiColl)

document.EndUpdateParagraphs(titleParagraphFormatting)

Document Styles

The Rich Text Editor supports paragraph and character styles. The character style can be used if only the character options need to be modified. Use the paragraph style to change both character (a font type, size, color, etc.) and paragraph (alignment, spacing before and after, etc.) attributes as in the current example.

The image below demonstrates chapter titles modified using the paragraph style.

The Rich Text Editor doesn’t have any predefined document styles. Use the members from the table below to create a new document style.

|

Member

|

Description

| | --- | --- | |

SubDocument.BeginUpdate

|

Opens the document for editing.

| |

Document.CharacterStyles

Document.ParagraphStyles

|

Provides access to the CharacterStyleCollection

Provides access to the ParagraphStyleCollection.

| |

CharacterStyleCollection.CreateNew

ParagraphStyleCollection.CreateNew

|

Creates a new CharacterStyle object.

Creates a new ParagraphStyle object.

| |

CharacterStyle.Parent

ParagraphStyle.Parent

|

Specifies the base style for the created instance.

| |

CharacterStyle.LinkedStyle

ParagraphStyle.LinkedStyle

|

Allows you to synchronize the character and paragraph styles to create a linked style.

| |

CharacterStyleCollection.Add

ParagraphStyleCollection.Add

|

Adds the created style to the collection.

| |

Paragraph.Style

|

Sets the style to the given paragraph.

| |

CharacterProperties.Style

|

Specifies the style to the given character range.

| |

SubDocument.EndUpdate

|

Finalizes style creation.

|

The code sample below demonstrates how to create a new paragraph style and apply it to every chapter.

View Example

csharp
//Open the document for editing
document.BeginUpdate();

//Create a new paragraph style instance
//and specify the required properties
ParagraphStyle chapterStyle = document.ParagraphStyles.CreateNew();
chapterStyle.Name = "MyTitleStyle";
chapterStyle.ForeColor = Color.SteelBlue;
chapterStyle.FontSize = 16;
chapterStyle.FontName = "Segoe UI Semilight";
chapterStyle.Alignment = ParagraphAlignment.Left;
chapterStyle.SpacingBefore = Units.InchesToDocumentsF(0.2f);
chapterStyle.SpacingAfter = Units.InchesToDocumentsF(0.2f);
chapterStyle.OutlineLevel = 2;

//Add the object to the document collection
document.ParagraphStyles.Add(chapterStyle);

//Finalize the editing
document.EndUpdate();

//Apply the created style to every chapter in the document 
for (int i = 0; i < document.Paragraphs.Count; i++)
{
    string var = document.GetText(document.Paragraphs[i].Range);
    if (var.Contains("Chapter "))
    {
        document.Paragraphs[i].Style = chapterStyle;
    }
}
return;
vb
'Open the document for editing
document.BeginUpdate()

'Create a new paragraph style instance
'and specify the required properties
Dim chapterStyle As ParagraphStyle = document.ParagraphStyles.CreateNew()
chapterStyle.Name = "MyTitleStyle"
chapterStyle.ForeColor = Color.SteelBlue
chapterStyle.FontSize = 16
chapterStyle.FontName = "Segoe UI Semilight"
chapterStyle.Alignment = ParagraphAlignment.Left
chapterStyle.SpacingBefore = Units.InchesToDocumentsF(0.2F)
chapterStyle.SpacingAfter = Units.InchesToDocumentsF(0.2F)
chapterStyle.OutlineLevel = 2

'Add the object to the document collection
document.ParagraphStyles.Add(chapterStyle)

'Finalize the editing
document.EndUpdate()

'Apply the created style to every chapter in the document 
For i As Integer = 0 To document.Paragraphs.Count - 1
    Dim var As String = document.GetText(document.Paragraphs(i).Range)
    If var.Contains("Chapter ") Then
        document.Paragraphs(i).Style = chapterStyle
    End If
Next i
Return

If the loaded document already has document styles, they are automatically added to the document’s StyleCollection and you can use them as shown in the code snippet below.

csharp
//Apply style to the paragraph
richEditControl.Document.Paragraphs[1].Style = richEditControl.Document.ParagraphStyles["Heading 2"];

//Apply style to the character range
DocumentRange range = richEditControl.Document.Paragraphs[1].Range;
CharacterProperties rangeProperties = richEditControl.Document.BeginUpdateCharacters(range);
rangeProperties.Style = richEditControl.Document.CharacterStyles["Heading 2"];
richEditControl.Document.EndUpdateCharacters(rangeProperties);
vb
'Apply style to the paragraph
richEditControl.Document.Paragraphs(1).Style = richEditControl.Document.ParagraphStyles("Heading 2")

'Apply style to the character range
Dim range As DocumentRange = richEditControl.Document.Paragraphs(1).Range
Dim rangeProperties As CharacterProperties = richEditControl.Document.BeginUpdateCharacters(range)
rangeProperties.Style = richEditControl.Document.CharacterStyles("Heading 2")
richEditControl.Document.EndUpdateCharacters(rangeProperties)

Linked Styles

Use a linked style to format the document annotation. A linked style carries both character and paragraph formatting rules, but applies them according to the target object. If the style is applied to the Paragraph instance, both formatting options will be applied. Only character formatting is used if the style is applied to the DocumentRange instance.

The code sample below demonstrates how to synchronize a paragraph and character style to create a linked style.

View Example

csharp
ParagraphStyle annotationStyle = document.ParagraphStyles["Annotation"];

document.BeginUpdate();

//Create a new paragraph style
//and set the required settings
annotationStyle = document.ParagraphStyles.CreateNew();
annotationStyle.Name = "Annotation";
annotationStyle.Alignment = ParagraphAlignment.Right;            
annotationStyle.LineSpacingMultiplier = 1.5f;
annotationStyle.FirstLineIndentType = ParagraphFirstLineIndent.Hanging;
annotationStyle.FirstLineIndent = 3;
document.ParagraphStyles.Add(annotationStyle);

//Create a new character style and link it
//to the custom paragraph style
CharacterStyle annotationCharStyle = document.CharacterStyles.CreateNew();
annotationCharStyle.Name = "AnnotationChar";
document.CharacterStyles.Add(annotationCharStyle);
annotationCharStyle.LinkedStyle = annotationStyle;

//Specify the style options
annotationCharStyle.Italic = true;
annotationCharStyle.FontSize = 12;
annotationCharStyle.FontName = "Segoe UI";
annotationCharStyle.ForeColor = Color.Gray;
document.EndUpdate();

//Apply the created style to the first paragraph of the annotation
document.Paragraphs[1].Style = annotationStyle;

//Apply the linked style to the range of the annotation's second paragraph
CharacterProperties annotationProperties = document.BeginUpdateCharacters(document.Paragraphs[2].Range);
annotationProperties.Style = annotationCharStyle;
document.EndUpdateCharacters(annotationProperties);
vb
Dim annotationStyle As ParagraphStyle = document.ParagraphStyles("Annotation")

document.BeginUpdate()

'Create a new paragraph style
'and set the required settings
annotationStyle = document.ParagraphStyles.CreateNew()
annotationStyle.Name = "Annotation"
annotationStyle.Alignment = ParagraphAlignment.Right
annotationStyle.LineSpacingMultiplier = 1.5F
annotationStyle.FirstLineIndentType = ParagraphFirstLineIndent.Hanging
annotationStyle.FirstLineIndent = 3
document.ParagraphStyles.Add(annotationStyle)

'Create a new character style and link it
'to the custom paragraph style
Dim annotationCharStyle As CharacterStyle = document.CharacterStyles.CreateNew()
annotationCharStyle.Name = "AnnotationChar"
document.CharacterStyles.Add(annotationCharStyle)
annotationCharStyle.LinkedStyle = annotationStyle

'Specify the style options
annotationCharStyle.Italic = True
annotationCharStyle.FontSize = 12
annotationCharStyle.FontName = "Segoe UI"
annotationCharStyle.ForeColor = Color.Gray
document.EndUpdate()

'Apply the created style to the first paragraph of the annotation
document.Paragraphs(1).Style = annotationStyle

'Apply the linked style to the range of the annotation's second paragraph
Dim annotationProperties As CharacterProperties = document.BeginUpdateCharacters(document.Paragraphs(2).Range)
annotationProperties.Style = annotationCharStyle
document.EndUpdateCharacters(annotationProperties)

The image below illustrates the result of the code execution.

Text Formatting In the User Interface

End users can change the required format settings using the Font and Paragraph groups of the Home ribbon tab.

The Style Gallery allows end users to preview and apply the desired document style to the selected text fragment.

Refer to the How to: Create a Simple Word Processor with a Ribbon UI topic for an example on how to provide the application with the Ribbon Command UI.

The Rich Text Editor application ships with the following dialogs.

You can prevent end users from formatting the document. As a result, the corresponding ribbon buttons and the context menu items will be disabled or hidden.

The following members allow you to accomplish this task.

|

Member

|

Description

| | --- | --- | |

DXRichEditDocumentCapabilitiesOptions.CharacterFormatting

DXRichEditDocumentCapabilitiesOptions.ParagraphFormatting

|

Allows you to restrict end-users from direct formatting.

| |

DXRichEditDocumentCapabilitiesOptions.CharacterStyle

DXRichEditDocumentCapabilitiesOptions.ParagraphStyle

|

Allows you to disable using document styles at runtime.

|