Skip to content

Instantly share code, notes, and snippets.

@GroupDocsGists
Created March 28, 2021 06:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GroupDocsGists/3f18a8d8601ba835d6bd33991f42cbdd to your computer and use it in GitHub Desktop.
Save GroupDocsGists/3f18a8d8601ba835d6bd33991f42cbdd to your computer and use it in GitHub Desktop.
Edit Word Document in C#
// 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