|
| 1 | +using Syncfusion.DocIO; |
| 2 | +using Syncfusion.DocIO.DLS; |
| 3 | + |
| 4 | +namespace Remove_editablerange |
| 5 | +{ |
| 6 | + class Program |
| 7 | + { |
| 8 | + static void Main(string[] args) |
| 9 | + { |
| 10 | + using (FileStream fileStreamPath = new FileStream(Path.GetFullPath(@"Data/Template.docx"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) |
| 11 | + { |
| 12 | + //Creates a new Word document. |
| 13 | + using (WordDocument document = new WordDocument(fileStreamPath, FormatType.Automatic)) |
| 14 | + { |
| 15 | + // Loop through all bookmarks in the document |
| 16 | + for (int i = 0; i < document.Bookmarks.Count; i++) |
| 17 | + { |
| 18 | + Bookmark bookmark = document.Bookmarks[i]; |
| 19 | + // Check and remove editable ranges within the bookmark |
| 20 | + RemoveEditableRange(document, bookmark.Name); |
| 21 | + } |
| 22 | + //Create a file stream. |
| 23 | + using (FileStream outputFileStream = new FileStream(Path.GetFullPath(@"Output/Result.docx"), FileMode.Create, FileAccess.ReadWrite)) |
| 24 | + { |
| 25 | + //Save the Word document to the file stream. |
| 26 | + document.Save(outputFileStream, FormatType.Docx); |
| 27 | + } |
| 28 | + } |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + /// <summary> |
| 33 | + /// Removes any editable ranges found within the bookmark |
| 34 | + /// </summary> |
| 35 | + /// <param name="document"></param> |
| 36 | + /// <param name="bookmarkName"></param> |
| 37 | + private static void RemoveEditableRange(WordDocument document, string bookmarkName) |
| 38 | + { |
| 39 | + // Create a Bookmark Navigator |
| 40 | + BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document); |
| 41 | + // Move to the bookmark |
| 42 | + bookmarkNavigator.MoveToBookmark(bookmarkName); |
| 43 | + // Get the bookmark content as word document |
| 44 | + WordDocument tempDoc = bookmarkNavigator.GetContent().GetAsWordDocument(); |
| 45 | + // Find all entities of type EditableRangeStart within the bookmark |
| 46 | + List<Entity> entity = tempDoc.FindAllItemsByProperty(EntityType.EditableRangeStart, null, null); |
| 47 | + // If any EditableRangeStart entities are found, iterate through them. |
| 48 | + if (entity != null) |
| 49 | + { |
| 50 | + foreach (Entity item in entity) |
| 51 | + { |
| 52 | + // Find the editable range by ID and remove it |
| 53 | + EditableRange editableRange = document.EditableRanges.FindById((item as EditableRangeStart).Id); |
| 54 | + if (editableRange != null) |
| 55 | + document.EditableRanges.Remove(editableRange); |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments