Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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