Created
March 28, 2021 06:46
-
-
Save GroupDocsGists/3f18a8d8601ba835d6bd33991f42cbdd to your computer and use it in GitHub Desktop.
Edit Word Document in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Edit Word document in C# using GroupDocs document editing and automation API | |
using (FileStream fs = File.OpenRead("filepath/document.docx")) | |
{ // Load Document | |
Options.WordProcessingLoadOptions loadOptions = new WordProcessingLoadOptions(); | |
loadOptions.Password = "password-if-any"; | |
// Edit Document | |
using (Editor editor = new Editor(delegate { return fs; }, delegate { return loadOptions; })) | |
{ | |
Options.WordProcessingEditOptions editOptions = new WordProcessingEditOptions(); | |
editOptions.FontExtraction = FontExtractionOptions.ExtractEmbeddedWithoutSystem; | |
editOptions.EnableLanguageInformation = true; | |
editOptions.EnablePagination = true; | |
using (EditableDocument beforeEdit = editor.Edit(editOptions)) | |
{ | |
string originalContent = beforeEdit.GetContent(); | |
List<IHtmlResource> allResources = beforeEdit.AllResources; | |
string editedContent = originalContent.Replace("document", "edited document"); | |
// Save Document | |
using (EditableDocument afterEdit = EditableDocument.FromMarkup(editedContent, allResources)) | |
{ | |
WordProcessingFormats docxFormat = WordProcessingFormats.Docx; | |
Options.WordProcessingSaveOptions saveOptions = new WordProcessingSaveOptions(docxFormat); | |
saveOptions.EnablePagination = true; | |
saveOptions.Locale = System.Globalization.CultureInfo.GetCultureInfo("en-US"); | |
saveOptions.OptimizeMemoryUsage = true; | |
saveOptions.Password = "password"; | |
saveOptions.Protection = new WordProcessingProtection(WordProcessingProtectionType.ReadOnly, "write_password"); | |
using (FileStream outputStream = File.Create("filepath/editedDocument.docx")) | |
{ | |
editor.Save(afterEdit, outputStream, saveOptions); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment