This demo uses the DevExpress Word Processing Document API to manage comments in a sample Word document.
Specify the required action, comment text, and author. Use the Modify Comments and Save as... dropdown button to select the output format, apply changes, and download the result.
Sample Document
Comments_template.docx
using DevExpress.XtraRichEdit;
using DevExpress.XtraRichEdit.API.Native;
Stream AddNewComment(Stream inputStream, string commentText, string author, DocumentFormat outputFormat) {
using var wordProcessor = new RichEditDocumentServer();
wordProcessor.LoadDocument(inputStream);
var document = wordProcessor.Document;
Paragraph paragraph = document.Paragraphs[0];
Comment comment = document.Comments.Create(paragraph.Range, author);
SubDocument commentDoc = comment.BeginUpdate();
commentDoc.InsertText(commentDoc.Range.Start, commentText);
comment.EndUpdate(commentDoc);
var outputStream = new MemoryStream();
wordProcessor.SaveDocument(outputStream, outputFormat);
outputStream.Position = 0;
return outputStream;
}
Stream ReplyToComment(Stream inputStream, string replyText, string author, DocumentFormat outputFormat) {
using var wordProcessor = new RichEditDocumentServer();
wordProcessor.LoadDocument(inputStream);
var document = wordProcessor.Document;
// Reply to the first comment
if(document.Comments.Count > 0) {
Comment parentComment = document.Comments[0];
Comment replyComment = document.Comments.Create(author, parentComment);
SubDocument replyDoc = replyComment.BeginUpdate();
replyDoc.InsertText(replyDoc.Range.Start, replyText);
replyComment.EndUpdate(replyDoc);
}
var outputStream = new MemoryStream();
wordProcessor.SaveDocument(outputStream, outputFormat);
outputStream.Position = 0;
return outputStream;
}
Stream RemoveComments(Stream inputStream, bool removeAll, string authorFilter, DocumentFormat outputFormat) {
using var wordProcessor = new RichEditDocumentServer();
wordProcessor.LoadDocument(inputStream);
var document = wordProcessor.Document;
if(removeAll) {
for(int i = document.Comments.Count - 1; i >= 0; i--)
document.Comments.Remove(document.Comments[i]);
} else if(!string.IsNullOrWhiteSpace(authorFilter)) {
for(int i = document.Comments.Count - 1; i >= 0; i--) {
if(string.Equals(document.Comments[i].Author, authorFilter, StringComparison.OrdinalIgnoreCase)) {
document.Comments.Remove(document.Comments[i]);
}
}
}
var outputStream = new MemoryStream();
wordProcessor.SaveDocument(outputStream, outputFormat);
outputStream.Position = 0;
return outputStream;
}