ReplaceTextFmt.cs
C# VB
//// This code is part of Document Solutions for Word demos.// Copyright (c) MESCIUS inc. All rights reserved.//using System;using System.IO;using System.Drawing;using System.Linq;using GrapeCity.Documents.Word;
namespace DsWordWeb.Demos{ // This sample shows how to replace all occurrences of a string // in a DOCX document (see JsFrameworkExcerpt) using the // RangeBase.Replace extension method provided by the // RangeBaseFindReplaceExtensions class. // This sample is similar to ReplaceText, with the addition of // also updating the replacement's style. public class ReplaceTextFmt { public GcWordDocument CreateDocx() { // The document to replace text in: var path = Path.Combine("Resources", "WordDocs", "JsFrameworkExcerpt.docx"); // The text to find: const string tFind = "javascript"; // The replacement: const string tRepl = "ArabicaScroll"; // Name for the replacement's style: const string styleName = "my new style";
// Load the source document: var doc = new GcWordDocument(); doc.Load(path);
// The new style for replaced text: var style = doc.Styles.Add(styleName, StyleType.Character); style.Font.Color.RGB = Color.Red;
// Replace text and replacements' style: var nreplacements = doc.Body.Replace(tFind, tRepl, new FindReplaceOptions(doc) { IgnoreCase = true, ReplacedCallback = (args_) => args_.ReplacedRange.Runs.ToList().ForEach(r_ => r_.Style = style) });
// Add a note at the end of the document: doc.Body.Sections.Last.GetRange().Paragraphs.Add( $"DsWord replaced {nreplacements} occurrences of '{tFind}' with '{tRepl}' on {Util.TimeNow():R}.");
// Done: return doc; } }}