|
| 1 | +using Syncfusion.DocIO.DLS; |
| 2 | + |
| 3 | +namespace Find_Text_and_Make_it_Editable |
| 4 | +{ |
| 5 | + public class Program |
| 6 | + { |
| 7 | + public static void Main(string[] args) |
| 8 | + { |
| 9 | + //Loads template document |
| 10 | + WordDocument document = new WordDocument(Path.GetFullPath(@"Data/Template.docx")); |
| 11 | + // Find all instances of the target text (text, case-insensitive, whole word match) |
| 12 | + TextSelection[] textSelections = document.FindAll("Adventure Works Cycles", false, true); |
| 13 | + |
| 14 | + // Append editable ranges around each matched text. |
| 15 | + foreach (var selection in textSelections) |
| 16 | + { |
| 17 | + AppendEditableRange(selection); |
| 18 | + } |
| 19 | + // save and close the document |
| 20 | + document.Save(Path.GetFullPath(Path.GetFullPath(@"../../../Output/Result.docx"))); |
| 21 | + document.Close(); |
| 22 | + } |
| 23 | + |
| 24 | + public static void AppendEditableRange(TextSelection selection) |
| 25 | + { |
| 26 | + // Get the text range from the selection. |
| 27 | + WTextRange[] textRanges = selection.GetRanges(); |
| 28 | + if (textRanges.Length > 0) |
| 29 | + { |
| 30 | + // Get the first and last text ranges in the selection. |
| 31 | + WTextRange startTextRange = textRanges[0]; |
| 32 | + WTextRange endTextRange = textRanges[textRanges.Length - 1]; |
| 33 | + // Get the paragraph that owns the start text range. |
| 34 | + WParagraph paragraph = startTextRange.OwnerParagraph; |
| 35 | + // Create a new EditableRangeStart and assign it to everyone by default. |
| 36 | + EditableRangeStart editableRangeStart = new EditableRangeStart(paragraph.Document); |
| 37 | + editableRangeStart.EditorGroup = EditorType.Everyone; |
| 38 | + // Find the index of the start text range within the paragraph's child entities. |
| 39 | + int startTextRangeIndex = paragraph.ChildEntities.IndexOf(startTextRange); |
| 40 | + // Insert the editable range start before the start text range. |
| 41 | + paragraph.ChildEntities.Insert(startTextRangeIndex, editableRangeStart); |
| 42 | + // Create a new EditableRangeEnd linked to the start. |
| 43 | + EditableRangeEnd editableRangeEnd = new EditableRangeEnd(paragraph.Document, editableRangeStart); |
| 44 | + // Find the index of the end text range and insert the editable range end after it. |
| 45 | + int endTextRangeIndex = paragraph.ChildEntities.IndexOf(endTextRange); |
| 46 | + paragraph.ChildEntities.Insert(endTextRangeIndex + 1, editableRangeEnd); |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | +} |
0 commit comments