Articles in this section
Category / Section

How to apply bold formatting to the content between placeholders in a Word document

8 mins read

Syncfusion® Essential® DocIO is a .NET Word library used to create, read, edit, and convert Word documents programmatically without Microsoft Word or interop dependencies. Using this library, you can apply bold formatting to the content between placeholders in a Word document using C#.

To achieve this, follow the steps below,

  • Find Text with Tags: Use a regular expression (<b>…</b>) to find all occurrences .
  • Extract Components: Iterate each occurrence and split the text into three parts: the opening tag , the bold text (content within the tags), and the closing tag.
  • Apply Bold Formatting: Apply bold formatting to the text using CharacterFormat.Bold.
  • Clone Text Ranges: Create separate text ranges for the opening tag, bold text, and closing tag by cloning the original text range.
  • Remove and insert Content: Remove and insert the matched text with the formatted text ranges, ensuring proper placement in the paragraph.

Steps to apply bold formatting to the content between placeholders in a Word document:

  1. Create a new .NET Core console application project. Create console application in Visual Studio
  2. Install the Syncfusion.DocIO.Net.Core NuGet package as a reference to your project from NuGet.org.
    Add DocIO NuGet package reference to the project

Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to the link to learn about generating and registering a Syncfusion® license key in your application to use the components without trail message.

  1. Include the following namespaces in Program.cs file
    C#
using Syncfusion.DocIO.DLS;
using Syncfusion.DocIO; 
  1. Use the following code example to apply bold formatting to the content between placeholders in a Word document.
    C#
// Create a WordDocument instance by loading the DOCX file from the file stream.
using (WordDocument document = new WordDocument(inputFileStream, FormatType.Docx))
{
   // Apply bold formatting to specific text using a regular expression.
   ApplyBoldFormatting(document);

   // Save the modified document to an output file.
   using (FileStream outputFileStream = new FileStream(Path.GetFullPath(@"Output/Result.docx"), FileMode.OpenOrCreate, FileAccess.ReadWrite))
   {
       // Save the modified Word document to the specified file path.
       document.Save(outputFileStream, FormatType.Docx);
   }
}
  1. Use the following helper method to apply bold formatting to text enclosed in tags in the Word document.
    C#
/// <summary>
/// Applies bold formatting to text enclosed in <b>...</b> tags in the Word document.
/// </summary>
static void ApplyBoldFormatting(WordDocument document)
{
   // Define a regular expression to find all occurrences of <b>...</b>.
   Regex regex = new Regex("<b>(.*?)</b>");

   // Find all matches of the regex pattern in the document.
   TextSelection[] matches = document.FindAll(regex);

   // Iterate through each match found in the document.
   foreach (TextSelection match in matches)
   {
       // Get the entire text range of the matched content.
       WTextRange textRange = match.GetAsOneRange();

       // Extract the full text of the match.
       string fullText = textRange.Text;

       // Define the length of the opening tag <b>.
       int startTagLength = "<b>".Length;

       // Find the index of the closing tag </b>.
       int endTagIndex = fullText.LastIndexOf("</b>");

       // Extract the opening tag, bold text, and closing tag as separate strings.
       string startTag = fullText.Substring(0, startTagLength);
       string boldText = fullText.Substring(startTagLength, endTagIndex - startTagLength);
       string endTag = fullText.Substring(endTagIndex);

       // Create new text ranges for each part (opening tag, bold text, and closing tag).
       WTextRange startTextRange = CreateTextRange(textRange, startTag);
       WTextRange boldTextRange = CreateTextRange(textRange, boldText);
       WTextRange endTextRange = CreateTextRange(textRange, endTag);

       // Apply bold formatting to the text range containing the bold text.
       boldTextRange.CharacterFormat.Bold = true;

       // Replace the original text range with the newly created text ranges in the paragraph.
       WParagraph paragraph = textRange.OwnerParagraph;

       // Get the index of the original text range within the paragraph.
       int index = paragraph.ChildEntities.IndexOf(textRange);

       // Remove the original text range from the paragraph.
       paragraph.ChildEntities.RemoveAt(index);

       // Insert the new text ranges (in order: closing tag, bold text, opening tag) into the paragraph.
       paragraph.ChildEntities.Insert(index, endTextRange);
       paragraph.ChildEntities.Insert(index, boldTextRange);
       paragraph.ChildEntities.Insert(index, startTextRange);
   }
}

  1. Use the following helper method to create a new text range by cloning an existing range and updating its text.
    C#
/// <summary>
/// Creates a new text range with the specified text, copying formatting from the original range.
/// </summary>
static WTextRange CreateTextRange(WTextRange original, string text)
{
   // Clone the original text range to preserve its formatting.
   WTextRange newTextRange = original.Clone() as WTextRange;

   // Set the text for the new text range.
   newTextRange.Text = text;

   return newTextRange;
}

You can download a complete working sample to apply bold formatting to the content between placeholders in a Word document from the GitHub.

By executing the program, you will get the Word document as follows.

Output Word document

Take a moment to peruse the documentation where you can find basic Word document processing options along with the features like mail merge, merge, split, and compare Word documents, find and replace text in the Word document, protect the Word documents, and most importantly, the PDF and Image conversions with code examples.

Conclusion

I hope you enjoyed learning about how to apply bold formatting to the content between placeholders in a Word document

You can refer to our ASP.NET Core DocIO feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our ASP.NET Core DocIO example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied