How to Set Word Paragraph Shading in C#

By shading words or paragraphs in a word document, we can emphasize the message and catch others' eyes easily. This article will show you how to set paragraph shading in C# with the help of Spire.Doc.

Firstly, download Spire.Doc and install on your system. The Spire.Doc installation is clean, professional and wrapped up in a MSI installer.

Then, adds Spire.Doc.dll as reference in the downloaded Bin folder though the below path: "..\Spire.Doc\Bin\NET4.0\ Spire.Doc.dll".

Now it comes to the steps of how to set the background color for text or paragraph.

Step 1: Create a new word document and load from the file.

[C#]
Document document = new Document();
document.LoadFromFile(@"..\..\Sample.docx");

Step 2: Get a paragraph.

[C#]
Paragraph paragaph = document.Sections[0].Paragraphs[0];

Step 3: Shading the paragraph or the selected words.

[C#]
//Set background color for the paragraph
paragaph.Format.BackColor = Color.Yellow;

//Set background color for the selected text of paragraph
paragaph = document.Sections[0].Paragraphs[1];
TextSelection selection= paragaph.Find("Blues",true,false);
TextRange range = selection.GetAsOneRange();
range.CharacterFormat.TextBackgroundColor = Color.Yellow;

Step 4: Save the document to file.

[C#]
document.SaveToFile("sample.docx",FileFormat.Docx);

Effected Screenshot:

Set Word Paragraph Shading

Full codes:

[C#]
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace SetWordParagh
{
    class Program
    {
       static void Main(string[] args)
        {
            Document document = new Document();
            document.LoadFromFile(@"..\..\Sample.docx");
            Paragraph paragaph = document.Sections[0].Paragraphs[0];

            //Set background color for the paragraph
            paragaph.Format.BackColor = Color.Yellow;

            //Set background color for the selected text of paragraph
            paragaph = document.Sections[0].Paragraphs[1];
            TextSelection selection= paragaph.Find("Blues",true,false);
            TextRange range = selection.GetAsOneRange();
            range.CharacterFormat.TextBackgroundColor = Color.Yellow;

            document.SaveToFile("sample.docx",FileFormat.Docx);
        }
        }
    }