Example #1
0
        public void W005_AddCommentsPart()
        {
            const string author   = "Some Name";
            const string comment  = "A comment.";
            const string initials = "ABC";
            const string id       = "0";

            using (var stream = GetStream(TestFiles.Plain, true))
                using (var doc = WordprocessingDocument.Open(stream, true))
                {
                    W.Paragraph firstParagraph =
                        doc.MainDocumentPart.Document.Descendants <W.Paragraph>().First();
                    W.Comments comments = null;

                    WordprocessingCommentsPart commentPart =
                        doc.MainDocumentPart.AddNewPart <WordprocessingCommentsPart>();
                    commentPart.Comments = new W.Comments();
                    comments             = commentPart.Comments;

                    var p   = new W.Paragraph(new W.Run(new W.Text(comment)));
                    var cmt =
                        new W.Comment()
                    {
                        Id       = id,
                        Author   = author,
                        Initials = initials,
                        Date     = DateTime.Now,
                    };
                    cmt.AppendChild(p);
                    comments.AppendChild(cmt);
                    comments.Save();

                    firstParagraph.InsertBefore(
                        new W.CommentRangeStart()
                    {
                        Id = id
                    },
                        firstParagraph.GetFirstChild <W.Run>());

                    var cmtEnd = firstParagraph.InsertAfter(
                        new W.CommentRangeEnd()
                    {
                        Id = id
                    },
                        firstParagraph.Elements <W.Run>().Last());

                    firstParagraph.InsertAfter(new W.Run(new W.CommentReference()
                    {
                        Id = id
                    }), cmtEnd);
                    var v    = new OpenXmlValidator(FileFormatVersions.Office2013);
                    var errs = v.Validate(doc);

                    Assert.Empty(errs);
                }
        }