Пример #1
0
        //.....................................................................
        /// <summary>
        /// https://docs.microsoft.com/zh-cn/dotnet/api/documentformat.openxml.packaging.maindocumentpart?view=openxml-2.8.1
        ///
        /// </summary>
        /// <param name="docxname"></param>
        public void ShowComments(string docxname)
        {
            //string docxname = @"C:\Users\Public\Documents\MainDocumentPartEx.docx";
            string comments = null;

            //List<string> listing = new List<string>( );

            // Open the file read-only.
            using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(docxname, false))
            {
                MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;

                WordprocessingCommentsPart docxprocCommentsPart = mainPart.WordprocessingCommentsPart;

                // Read the comments using a stream reader.
                using (StreamReader streamReader = new StreamReader(docxprocCommentsPart.GetStream( )))
                {
                    comments = streamReader.ReadToEnd( );
                }
            }

            FileInfo fileinfo = new FileInfo(docxname);
            string   msgname  = fileinfo.FullName + "-comments.txt";

            File.WriteAllText(msgname, comments, Encoding.Default);

            //Console.WriteLine( comments );
            //Console.ReadKey( );

            return;
        }
Пример #2
0
        public override string ReadContents()
        {
            string documentContent = null;

            Stream stream = new MemoryStream(File.ReadAllBytes(_FilePath));

            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(stream, false))
            {
                using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
                {
                    documentContent = sr.ReadToEnd();

                    // Now search any Comments in the document as well.
                    WordprocessingCommentsPart wordProcessingCommentsPart = wordDoc.MainDocumentPart.WordprocessingCommentsPart;
                    if (wordProcessingCommentsPart != null)
                    {
                        using (StreamReader sr1 = new StreamReader(wordProcessingCommentsPart.GetStream()))
                        {
                            documentContent += sr1.ReadToEnd();
                        }
                    }
                }
            }
            return(documentContent);
        }
Пример #3
0
        //gavdcodeend 15

        //gavdcodebegin 16
        public static void WordOpenXmlDeleteComments()
        {
            using (WordprocessingDocument myWordDoc =
                       WordprocessingDocument.Open(@"C:\Temporary\WordDoc01.docx", true))
            {
                WordprocessingCommentsPart commentPart =
                    myWordDoc.MainDocumentPart.WordprocessingCommentsPart;

                if (commentPart == null)
                {
                    return;
                }

                List <Comment> commentsToDelete =
                    commentPart.Comments.Elements <Comment>().ToList();
                if (!String.IsNullOrEmpty("OtherAuthor"))
                {
                    commentsToDelete = commentsToDelete.
                                       Where(aut => aut.Author == "OtherAuthor").ToList();
                }
                IEnumerable <string> commentIds =
                    commentsToDelete.Select(del => del.Id.Value);

                foreach (Comment cmt in commentsToDelete)
                {
                    cmt.Remove();
                }

                commentPart.Comments.Save();

                Document myDoc = myWordDoc.MainDocumentPart.Document;

                List <CommentRangeStart> commentRangeStartToDelete =
                    myDoc.Descendants <CommentRangeStart>().
                    Where(cmt => commentIds.Contains(cmt.Id.Value)).ToList();
                foreach (CommentRangeStart oneComment in commentRangeStartToDelete)
                {
                    oneComment.Remove();
                }

                List <CommentRangeEnd> commentRangeEndToDelete =
                    myDoc.Descendants <CommentRangeEnd>().
                    Where(cmt => commentIds.Contains(cmt.Id.Value)).ToList();
                foreach (CommentRangeEnd oneComment in commentRangeEndToDelete)
                {
                    oneComment.Remove();
                }

                List <CommentReference> commentRangeReferenceToDelete =
                    myDoc.Descendants <CommentReference>().
                    Where(cmt => commentIds.Contains(cmt.Id.Value)).ToList();
                foreach (CommentReference oneComment in commentRangeReferenceToDelete)
                {
                    oneComment.Remove();
                }

                myDoc.Save();
            }
        }
Пример #4
0
        /// <summary>
        /// CommentEx object, Get support mothod.
        /// </summary>
        /// <param name="commentsPart">Target comment include commentsPart</param>
        /// <param name="commentsExPart">Target comment include commentsExPart</param>
        /// <param name="commentID">Comment ID</param>
        /// <returns>CommentEx Object</returns>
        private W15.CommentEx GetCommentEx(WordprocessingCommentsPart commentsPart, WordprocessingCommentsExPart commentsExPart, string commentID)
        {
            Comment   comment = GetComment(commentsPart, commentID);
            Paragraph p       = comment.Descendants <Paragraph>().First();

            W15.CommentEx commentEx = commentsExPart.CommentsEx.Descendants <W15.CommentEx>().Where(e => e.ParaId.Value == p.ParagraphId.Value).Single();

            return(commentEx);
        }
Пример #5
0
        /// <summary>
        /// Comment object, Get support mothod.
        /// </summary>
        /// <param name="commentsPart">Target comment include commentsPart</param>
        /// <param name="commentID">Comment ID</param>
        /// <returns>Comment Object</returns>
        public static Comment GetComment(WordprocessingCommentsPart commentsPart, string commentID)
        {
            if (commentsPart is null)
            {
                throw new System.ArgumentNullException(nameof(commentsPart));
            }

            return(commentsPart.Comments.Descendants <Comment>().Where(e => e.Id == commentID).Single());
        }
Пример #6
0
        /// <summary>
        /// Verify Comment and CommentEx
        /// </summary>
        /// <param name="filePath">Verifying target file path</param>
        /// <param name="log">Logger</param>
        public void VerifyElements(string filePath, VerifiableLog log)
        {
            using (WordprocessingDocument package = WordprocessingDocument.Open(filePath, false))
            {
                WordprocessingCommentsPart   commentPart   = package.MainDocumentPart.WordprocessingCommentsPart;
                WordprocessingCommentsExPart commentExPart = package.MainDocumentPart.WordprocessingCommentsExPart;
                Comment       comment   = null;
                W15.CommentEx commentEx = null;

                //2.1 Verifying comment text
                comment = GetComment(commentPart, CommentIDs.CommentID1);
                Text text = comment.Descendants <Text>().First();
                log.Verify(text.Text == CommentStrings.CommentChangeString1, "Verify comment text.");

                //2.2 Verifying commnet initials attribute
                comment = GetComment(commentPart, CommentIDs.CommentID1);
                log.Verify(comment.Initials == CommentInitials.Initial2, "Verify comment attribute of initials.");

                //2.2 Verifying commnet date attribute
                log.Verify(comment.Date.Value.Year == 2015 &&
                           comment.Date.Value.Month == 12 &&
                           comment.Date.Value.Day == 24 &&
                           comment.Date.Value.Hour == 12 &&
                           comment.Date.Value.Minute == 34 &&
                           comment.Date.Value.Second == 56 &&
                           comment.Date.Value.Millisecond == 77, "Verify comment attribute of date.");

                //2.2 Verifying commnet author attribute
                log.Verify(comment.Author == CommentAuthors.Author2, "Verify comment attribute of author.");

                //2.3 Verifying comment parent-child relationship, Case of parent attribute deleteing.
                commentEx = GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID2);
                log.Verify(commentEx.ParaIdParent == null, "Verify parent-child relationship. Parent is null.");

                //2.3 Verifying comment parent-child relationship, Case of parent attribute appending.
                commentEx = GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID3);
                W15.CommentEx comEx = GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID2);
                log.Verify(commentEx.ParaIdParent.Value == GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID2).ParaId.Value, "Verify parent-child relationship. This ID is [{0}]. Parent ID is [{0}].", commentEx.ParaId, commentEx.ParaIdParent);

                //2.4 Verifying CommnetEx done attribute, Case of value "1" setting.
                log.Verify(GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID1).Done == true, "Verify CommentEx attribute of done.");

                //2.4 Verifying CommnetEx done attribute, Case of value "0" setting.
                log.Verify(GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID3).Done == false, "Verify CommentEx attribute of done.");

                //2.5 Verifying comment and CommentEx append.
                log.Verify(GetComment(commentPart, CommentIDs.CommentID4) != null &&
                           GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID4) != null, "Verify Comment and CommentEx append.");

                //2.5 Verifying comment and CommentEx append.
                log.Verify(GetComment(commentPart, CommentIDs.CommentID5) != null &&
                           GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID5) != null &&
                           GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID5).ParaIdParent.Value == GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID4).ParaId.Value,
                           "Verify Comment and CommentEx append, And CommentEx parent-child relationship");
            }
        }
Пример #7
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);
                }
        }
Пример #8
0
        /// <summary>
        /// Verify Comment and CommentEx
        /// </summary>
        /// <param name="stream">Package stream</param>
        /// <param name="log">Logger</param>
        public static void VerifyElements(Stream stream)
        {
            using (WordprocessingDocument package = WordprocessingDocument.Open(stream, false))
            {
                WordprocessingCommentsPart   commentPart   = package.MainDocumentPart.WordprocessingCommentsPart;
                WordprocessingCommentsExPart commentExPart = package.MainDocumentPart.WordprocessingCommentsExPart;
                Comment       comment   = null;
                W15.CommentEx commentEx = null;

                //2.1 Verifying comment text
                comment = GetComment(commentPart, CommentIDs.CommentID1);
                Text text = comment.Descendants <Text>().First();
                Assert.Equal(text.Text, CommentStrings.CommentChangeString1);

                //2.2 Verifying comment initials attribute
                comment = GetComment(commentPart, CommentIDs.CommentID1);
                Assert.Equal(comment.Initials, CommentInitials.Initial2);

                //2.2 Verifying comment date attribute
                Assert.Equal(2015, comment.Date.Value.Year);
                Assert.Equal(12, comment.Date.Value.Month);
                Assert.Equal(24, comment.Date.Value.Day);
                Assert.Equal(12, comment.Date.Value.Hour);
                Assert.Equal(34, comment.Date.Value.Minute);
                Assert.Equal(56, comment.Date.Value.Second);
                Assert.Equal(77, comment.Date.Value.Millisecond);

                //2.2 Verifying comment author attribute
                Assert.Equal(comment.Author, CommentAuthors.Author2);

                //2.3 Verifying comment parent-child relationship, Case of parent attribute deletion.
                commentEx = GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID2);
                Assert.Null(commentEx.ParaIdParent);

                //2.3 Verifying comment parent-child relationship, Case of parent attribute appending.
                commentEx = GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID3);
                W15.CommentEx comEx = GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID2);
                Assert.Equal(commentEx.ParaIdParent.Value, GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID2).ParaId.Value);

                //2.4 Verifying commentEx done attribute, Case of value "1" setting.
                Assert.True(GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID1).Done);

                //2.4 Verifying commentEx done attribute, Case of value "0" setting.
                Assert.False(GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID3).Done);

                //2.5 Verifying comment and CommentEx append.
                Assert.NotNull(GetComment(commentPart, CommentIDs.CommentID4));
                Assert.NotNull(GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID4));

                //2.5 Verifying comment and CommentEx append.
                Assert.NotNull(GetComment(commentPart, CommentIDs.CommentID5));
                Assert.NotNull(GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID5));
                Assert.Equal(GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID5).ParaIdParent.Value, GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID4).ParaId.Value);
            }
        }
Пример #9
0
        /// <summary>
        /// Returns all comments included into a document
        /// </summary>
        private IEnumerable <XElement> CommentContents()
        {
            IEnumerable <XElement>     results      = null;
            WordprocessingCommentsPart commentsPart = parentDocument.Document.MainDocumentPart.WordprocessingCommentsPart;

            if (commentsPart != null)
            {
                XDocument commentsPartDocument = parentDocument.GetXDocument(commentsPart);

                results = commentsPartDocument.Element(ns + "comments").Elements(ns + "comment");
            }
            return(results);
        }
Пример #10
0
        /// <summary>
        /// Removes all of the comments existing in the document
        /// </summary>
        public void RemoveAll()
        {
            //Removes comment-related tags inside the main document part
            IEnumerable <XElement> commentReferences = CommentReferences().ToList();

            commentReferences.Remove();

            WordprocessingCommentsPart commentsPart = parentDocument.Document.MainDocumentPart.WordprocessingCommentsPart;

            if (commentsPart != null)
            {
                parentDocument.RemovePart(commentsPart);
            }
        }
        public static void RetrieveCommentsFeature()
        {
            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(MyDir + "Comments.docx", false))
            {
                WordprocessingCommentsPart commentsPart = wordDoc.MainDocumentPart.WordprocessingCommentsPart;

                if (commentsPart?.Comments != null)
                {
                    foreach (Comment comment in commentsPart.Comments.Elements <Comment>())
                    {
                        Console.WriteLine(comment.InnerText);
                    }
                }
            }
        }
Пример #12
0
 private void GetComments(WordprocessingCommentsPart commentsPart)
 {
     if (commentsPart?.Comments != null)
     {
         foreach (var comment in commentsPart.Comments.Elements <Comment>())
         {
             var commentToken = new Token {
                 Content = comment.InnerText, Type = Token.TokenType.CommentStart
             };
             commentToken.Author = comment.Author;
             commentToken.Date   = comment.Date;
             _comments.Add(commentToken);
         }
     }
 }
Пример #13
0
        /// <summary>
        /// Добавление комментария к параграфу в документе
        /// </summary>
        /// <param name="document">WordprocessingDocument файла результатов</param>
        /// <param name="ind">Индекс параграфа в документе</param>
        /// <param name="comment">Комментарий к ошибке (текст комментария)</param>
        private static void AddCommentOnParagraph(WordprocessingDocument document, int ind, string comment)
        {
            Paragraph paragraph = document.MainDocumentPart.Document.Descendants <Paragraph>().ElementAt(ind);
            Comments  comments  = null;
            int       id        = 0;

            if (document.MainDocumentPart.GetPartsOfType <WordprocessingCommentsPart>().Count() > 0)
            {
                comments = document.MainDocumentPart.WordprocessingCommentsPart.Comments;
                if (comments.HasChildren)
                {
                    id = int.Parse(comments.Descendants <Comment>().Select(e => e.Id.Value).Max()) + 1;
                }
            }
            else
            {
                WordprocessingCommentsPart commentPart = document.MainDocumentPart.AddNewPart <WordprocessingCommentsPart>();
                commentPart.Comments = new Comments();
                comments             = commentPart.Comments;
            }

            Paragraph p   = new Paragraph(new Run(new Text(comment)));
            Comment   cmt = new Comment()
            {
                Id       = id.ToString(),
                Author   = new StringValue("Программа проверки"),
                Initials = new StringValue("Программа проверки"),
                Date     = DateTime.Now
            };

            cmt.AppendChild(p);
            comments.AppendChild(cmt);
            comments.Save();

            paragraph.InsertBefore(new CommentRangeStart()
            {
                Id = id.ToString()
            }, paragraph.GetFirstChild <Run>());
            CommentRangeEnd cmtEnd = paragraph.InsertAfter(new CommentRangeEnd()
            {
                Id = id.ToString()
            }, paragraph.Elements().Last());

            paragraph.InsertAfter(new Run(new CommentReference()
            {
                Id = id.ToString()
            }), cmtEnd);
        }
Пример #14
0
        public static void SimplifyMarkup(WordprocessingDocument doc, SimplifyMarkupSettings settings)
        {
            if (settings.RemoveMarkupForDocumentComparison)
            {
                settings.RemoveRsidInfo = true;
                RemoveElementsForDocumentComparison(doc);
            }

            if (settings.RemoveRsidInfo)
            {
                RemoveRsidInfoInSettings(doc);
            }

            if (settings.AcceptRevisions)
            {
                RevisionAccepter.AcceptRevisions(doc);
            }

            foreach (OpenXmlPart part in doc.ContentParts())
            {
                SimplifyMarkupForPart(part, settings);
            }

            if (doc.MainDocumentPart.StyleDefinitionsPart != null)
            {
                SimplifyMarkupForPart(doc.MainDocumentPart.StyleDefinitionsPart, settings);
            }

            if (doc.MainDocumentPart.StylesWithEffectsPart != null)
            {
                SimplifyMarkupForPart(doc.MainDocumentPart.StylesWithEffectsPart, settings);
            }

            if (settings.RemoveComments)
            {
                WordprocessingCommentsPart commentsPart = doc.MainDocumentPart.WordprocessingCommentsPart;
                if (commentsPart != null)
                {
                    doc.MainDocumentPart.DeletePart(commentsPart);
                }

                WordprocessingCommentsExPart commentsExPart = doc.MainDocumentPart.WordprocessingCommentsExPart;
                if (commentsExPart != null)
                {
                    doc.MainDocumentPart.DeletePart(commentsExPart);
                }
            }
        }
Пример #15
0
        public static void GetCommentsFromDocument(string fileName)
        {
            using (WordprocessingDocument wordDoc =
                       WordprocessingDocument.Open(fileName, false))
            {
                WordprocessingCommentsPart commentsPart =
                    wordDoc.MainDocumentPart.WordprocessingCommentsPart;

                if (commentsPart != null && commentsPart.Comments != null)
                {
                    foreach (Comment comment in commentsPart.Comments.Elements <Comment>())
                    {
                        Console.WriteLine(comment.InnerText);
                    }
                }
            }
        }
Пример #16
0
        /// <summary>
        /// 获取文档内容
        /// </summary>
        /// <param name="document"></param>
        /// <returns></returns>
        public static string GetCommentsFromDocument(string document)
        {
            string comments = null;

            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, false))
            {
                MainDocumentPart           mainPart = wordDoc.MainDocumentPart;
                WordprocessingCommentsPart WordprocessingCommentsPart = mainPart.WordprocessingCommentsPart;
                Stream stream = WordprocessingCommentsPart.GetStream();

                using (StreamReader streamReader = new StreamReader(stream))
                {
                    comments = streamReader.ReadToEnd();
                }
            }
            return(comments);
        }
Пример #17
0
        public RecordsList GetCommentsWithText()
        {
            RecordsList records = new RecordsList();

            WordprocessingCommentsPart commentsPart = wordDocument.MainDocumentPart.WordprocessingCommentsPart;

            if (commentsPart != null && commentsPart.Comments != null)
            {
                foreach (Comment comment in commentsPart.Comments.Elements <Comment>())
                {
                    OpenXmlElement rangeStart = wordDocument.MainDocumentPart.Document.Descendants <CommentRangeStart>().Where(c => c.Id == comment.Id).FirstOrDefault();
                    //bool breakLoop = false;
                    //rangeStart = rangeStart.Parent;
                    rangeStart = rangeStart.NextSibling();
                    string commentText = "";
                    while (!(rangeStart is CommentRangeEnd))
                    {
                        try
                        {
                            if (!string.IsNullOrWhiteSpace(rangeStart.InnerText))
                            {
                                commentText += rangeStart.InnerText;
                            }
                            rangeStart = rangeStart.NextSibling();
                        }
                        catch (NullReferenceException ex)
                        {
                            Console.WriteLine(ex.Message);
                            Console.WriteLine("NullReference Exception on " + comment.InnerText + " with highlited text: " + commentText);
                            commentText += " !!!ERROR WHILE EXTRACTING THIS TEXT!!!";
                            break;
                        }
                    }
                    Record record = new Record(comment.Id, comment.InnerText, commentText);
                    records.Add(record);
                }
            }
            else
            {
                return(records);
            }
            return(records);
        }
Пример #18
0
        //gavdcodeend 14

        //gavdcodebegin 15
        public static void WordOpenXmlFindCommentsinDocument()
        {
            using (WordprocessingDocument myWordDoc =
                       WordprocessingDocument.Open(@"C:\Temporary\WordDoc01.docx", false))
            {
                WordprocessingCommentsPart commentsPart =
                    myWordDoc.MainDocumentPart.WordprocessingCommentsPart;

                if (commentsPart != null && commentsPart.Comments != null)
                {
                    IEnumerable <Comment> allComments =
                        commentsPart.Comments.Elements <Comment>();
                    foreach (Comment oneComment in allComments)
                    {
                        Console.WriteLine(oneComment.InnerText);
                    }
                }
            }
        }
Пример #19
0
        public List <string> GetComments()
        {
            List <string> comments = new List <string>();

            WordprocessingCommentsPart commentsPart = wordDocument.MainDocumentPart.WordprocessingCommentsPart;

            if (commentsPart != null && commentsPart.Comments != null)
            {
                foreach (Comment comment in commentsPart.Comments.Elements <Comment>())
                {
                    comments.Add(comment.InnerText);
                }
            }
            else
            {
                return(comments);
            }
            return(comments);
        }
Пример #20
0
        /// <summary>
        /// Removes all of the comments existing in the document
        /// </summary>
        public static OpenXmlPowerToolsDocument RemoveAll(WmlDocument doc)
        {
            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
            {
                using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
                {
                    //Removes comment-related tags inside the main document part
                    IEnumerable <XElement> commentReferences = CommentReferences(document).ToList();
                    commentReferences.Remove();
                    document.MainDocumentPart.PutXDocument();

                    WordprocessingCommentsPart commentsPart = document.MainDocumentPart.WordprocessingCommentsPart;
                    if (commentsPart != null)
                    {
                        commentsPart.RemovePart();
                    }
                }
                return(streamDoc.GetModifiedDocument());
            }
        }
Пример #21
0
        public static POCO.DocumentText GetCommentsFromDocument(WordprocessingDocument wordDocument)
        {
            POCO.DocumentText text = new POCO.DocumentText();

            WordprocessingCommentsPart commentsPart =
                wordDocument.MainDocumentPart.WordprocessingCommentsPart;

            int counterComments = 0;

            if (commentsPart != null && commentsPart.Comments != null)
            {
                foreach (Comment comment in commentsPart.Comments.Elements <Comment>())
                {
                    counterComments++;
                    POCO.DocumentPart part = new POCO.DocumentPart();
                    part.body       = comment.InnerText;
                    part.partnumber = counterComments;
                    text.parts.Add(part);
                }
            }

            return(text);
        }
Пример #22
0
        private List <Comments> GetCommentsFromDocument(string fileName)
        {
            List <Comments> listComments = new List <Comments>();

            using (WordprocessingDocument wordDoc =
                       WordprocessingDocument.Open(fileName, false))
            {
                WordprocessingCommentsPart commentsPart =
                    wordDoc.MainDocumentPart.WordprocessingCommentsPart;

                if (commentsPart != null && commentsPart.Comments != null)
                {
                    foreach (Comment comment in commentsPart.Comments.Elements <Comment>())
                    {
                        Comments eachComment = new Comments();
                        eachComment.Text      = comment.InnerText;
                        eachComment.Commenter = comment.Author;
                        listComments.Add(eachComment);
                    }
                }
            }
            return(listComments);
        }
Пример #23
0
        public static object GetAllComments(WmlDocument doc, CommentFormat format)
        {
            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
                using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
                {
                    IEnumerable <XElement>     comments     = null;
                    WordprocessingCommentsPart commentsPart = document.MainDocumentPart.WordprocessingCommentsPart;
                    if (commentsPart != null)
                    {
                        XDocument commentsPartDocument = commentsPart.GetXDocument();
                        comments = commentsPartDocument.Element(W.comments).Elements(W.comment);
                    }
                    if (comments != null)
                    {
                        XDocument commentsDocument =
                            new XDocument(
                                new XElement(W.comments,
                                             new XAttribute(XNamespace.Xmlns + "w", W.w),
                                             comments
                                             )
                                );
                        switch (format)
                        {
                        case CommentFormat.PlainText:
                            return(commentsDocument.ToString());

                        case CommentFormat.Xml:
                            return(commentsDocument);

                        case CommentFormat.Docx:
                            return(CreateCommentsDocument(comments));
                        }
                    }
                    return(null);
                }
        }
Пример #24
0
        /// <summary>
        /// Edit Comment and CommentEx
        /// </summary>
        /// <param name="stream">Package stream</param>
        /// <param name="log">Logger</param>
        public static void EditElements(Stream stream)
        {
            using (WordprocessingDocument package = WordprocessingDocument.Open(stream, true))
            {
                WordprocessingCommentsPart   commentPart   = package.MainDocumentPart.WordprocessingCommentsPart;
                WordprocessingCommentsExPart commentExPart = package.MainDocumentPart.WordprocessingCommentsExPart;
                Comment       comment   = null;
                W15.CommentEx commentEx = null;

                //2.1 Change comment text
                comment = GetComment(commentPart, CommentIDs.CommentID1);
                Text text = comment.Descendants <Text>().First();
                text.Text = CommentStrings.CommentChangeString1;

                //2.2 Change comment initials attribute
                comment = GetComment(commentPart, CommentIDs.CommentID1);

                comment.Initials = CommentInitials.Initial2;

                //2.2 Change comment date attribute
                comment.Date = new DateTimeValue(new DateTime(2015, 12, 24, 12, 34, 56, 77));

                //2.2 Change comment author attribute
                comment.Author = CommentAuthors.Author2;

                //2.3 Change comment parent-child relationship, Case of parent attribute deletion.
                commentEx = GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID2);
                commentEx.ParaIdParent = null;

                //2.3 Change comment parent-child relationship, Case of parent attribute appending.
                commentEx = GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID3);
                W15.CommentEx comEx = GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID2);
                commentEx.ParaIdParent = comEx.ParaId;

                //2.4 Change commentEx done attribute, Case of value "1" setting.
                GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID1).Done = true;

                //2.4 Change commentEx done attribute, Case of value "0" setting.
                GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID3).Done = false;

                //2.5 Add comment and CommentEx.
                CommentRangeStart commentRangeStart1 = new CommentRangeStart();
                commentRangeStart1.Id = CommentIDs.CommentID4;
                CommentRangeEnd CommentRangeEnd1 = new CommentRangeEnd();
                CommentRangeEnd1.Id = CommentIDs.CommentID4;

                Paragraph paragraph1 = package.MainDocumentPart.Document.Descendants <Paragraph>().Where(e => e.InnerText == CommentBodyStrings.Comment2).First();
                paragraph1.Descendants <Run>().Where(e => e.InnerText == CommentBodyStrings.Comment2).First().InsertBeforeSelf <CommentRangeStart>(commentRangeStart1);
                paragraph1.Descendants <Run>().Where(e => e.InnerText == CommentBodyStrings.Comment2).First().InsertAfterSelf <CommentRangeEnd>(CommentRangeEnd1);

                CommentReference commentReference1 = new CommentReference();
                commentReference1.Id = CommentIDs.CommentID4;
                Run run1 = new Run();
                run1.AppendChild <CommentReference>(commentReference1);

                paragraph1.AppendChild <Run>(run1);
                Comment comment1 = (Comment)GetComment(commentPart, CommentIDs.CommentID1).Clone();
                comment1.Id = CommentIDs.CommentID4;
                comment1.Descendants <Text>().First().Text             = CommentStrings.CommentAppendString1;
                comment1.Descendants <Paragraph>().First().ParagraphId = AppendCommentExIDs.AppendCommentID1;

                commentPart.Comments.AppendChild <Comment>(comment1);

                W15.CommentEx commentEx1 = new W15.CommentEx();
                commentEx1.ParaId = AppendCommentExIDs.AppendCommentID1;
                commentExPart.CommentsEx.AppendChild <W15.CommentEx>(commentEx1);

                //2.5 Add comment and CommentEx.
                CommentRangeStart commentRangeStart2 = new CommentRangeStart();
                commentRangeStart2.Id = CommentIDs.CommentID5;
                CommentRangeEnd CommentRangeEnd2 = new CommentRangeEnd();
                CommentRangeEnd2.Id = CommentIDs.CommentID5;

                Paragraph paragraph2 = package.MainDocumentPart.Document.Descendants <Paragraph>().Where(e => e.InnerText == CommentBodyStrings.Comment2).First();
                paragraph2.Descendants <Run>().Where(e => e.InnerText == CommentBodyStrings.Comment2).First().InsertBeforeSelf <CommentRangeStart>(commentRangeStart2);
                paragraph2.Descendants <Run>().Where(e => e.InnerText == CommentBodyStrings.Comment2).First().InsertAfterSelf <CommentRangeEnd>(CommentRangeEnd2);

                CommentReference commentReference2 = new CommentReference();
                commentReference2.Id = CommentIDs.CommentID5;
                Run run2 = new Run();
                run2.AppendChild <CommentReference>(commentReference2);

                paragraph2.AppendChild <Run>(run2);
                Comment comment2 = (Comment)GetComment(commentPart, CommentIDs.CommentID2).Clone();
                comment2.Id = CommentIDs.CommentID5;
                comment2.Descendants <Text>().First().Text             = CommentStrings.CommentAppendString2;
                comment2.Descendants <Paragraph>().First().ParagraphId = AppendCommentExIDs.AppendCommentID2;

                commentPart.Comments.AppendChild <Comment>(comment2);

                W15.CommentEx commentEx2 = new W15.CommentEx();
                commentEx2.ParaId       = AppendCommentExIDs.AppendCommentID2;
                commentEx2.ParaIdParent = AppendCommentExIDs.AppendCommentID1;
                commentExPart.CommentsEx.AppendChild <W15.CommentEx>(commentEx2);
            }
        }
Пример #25
0
        private void AddComment(/*Paragraph textPart, */ Run textPoint, string comment)
        {
            Paragraph textPart = textPoint.Parent as Paragraph;

            if (textPart == null)
            {
                return;
            }
            Comments comments = null;
            string   id       = "0";

            // Verify that the document contains a
            // WordProcessingCommentsPart part; if not, add a new one.
            if (_document.MainDocumentPart.GetPartsCountOfType <WordprocessingCommentsPart>() > 0)
            {
                comments =
                    _document.MainDocumentPart.WordprocessingCommentsPart.Comments;
                if (comments.HasChildren)
                {
                    // Obtain an unused ID.
                    id = comments.Descendants <Comment>().Select(e => e.Id.Value).Max();
                }
            }
            else
            {
                // No WordprocessingCommentsPart part exists, so add one to the package.
                WordprocessingCommentsPart commentPart =
                    _document.MainDocumentPart.AddNewPart <WordprocessingCommentsPart>();
                commentPart.Comments = new Comments();
                comments             = commentPart.Comments;
            }

            // Compose a new Comment and add it to the Comments part.
            Paragraph p   = new Paragraph(new Run(new Text(comment)));
            Comment   cmt =
                new Comment()
            {
                Id       = id,
                Author   = _author,
                Initials = _initials,
                Date     = DateTime.Now
            };

            cmt.AppendChild(p);
            comments.AppendChild(cmt);
            comments.Save();
            //Коммент ставить перед Runnom

            // Specify the text range for the Comment.
            // Insert the new CommentRangeStart before the first run of paragraph.
            textPart.InsertBefore(new CommentRangeStart()
            {
                Id = id
            }, textPoint);
            var cmtEnd = textPart.InsertAfter(new CommentRangeEnd()
            {
                Id = id
            }, textPoint);

            // Insert the new CommentRangeEnd after last run of paragraph.


            // Compose a run with CommentReference and insert it.
            textPart.InsertAfter(new Run(new CommentReference()
            {
                Id = id
            }), cmtEnd);
        }
Пример #26
0
        public static void DeleteComments(WordprocessingDocument document, string author = "")
        {
            // Get an existing Wordprocessing document.

            // Set commentPart to the document WordprocessingCommentsPart,
            // if it exists.
            WordprocessingCommentsPart commentPart =
                document.MainDocumentPart.WordprocessingCommentsPart;

            // If no WordprocessingCommentsPart exists, there can be no comments.
            // Stop execution and return from the method.
            if (commentPart == null)
            {
                return;
            }

            List <Comment> commentsToDelete =
                commentPart.Comments.Elements <Comment>().ToList();

            // Create a list of comments by the specified author.
            if (!String.IsNullOrEmpty(author))
            {
                commentsToDelete = commentsToDelete.
                                   Where(c => c.Author == author).ToList();
            }
            IEnumerable <string> commentIds =
                commentsToDelete.Select(r => r.Id.Value);

            // Delete each comment in commentToDelete from the
            // Comments collection.
            foreach (Comment c in commentsToDelete)
            {
                c.Remove();
            }

            // Save comment part change.
            //commentPart.Comments.Save();

            Document doc = document.MainDocumentPart.Document;

            // Delete CommentRangeStart within main document.
            List <CommentRangeStart> commentRangeStartToDelete =
                doc.Descendants <CommentRangeStart>().
                Where(c => commentIds.Contains(c.Id.Value)).ToList();

            foreach (CommentRangeStart c in commentRangeStartToDelete)
            {
                c.Remove();
            }

            // Delete CommentRangeEnd within the main document.
            List <CommentRangeEnd> commentRangeEndToDelete =
                doc.Descendants <CommentRangeEnd>().
                Where(c => commentIds.Contains(c.Id.Value)).ToList();

            foreach (CommentRangeEnd c in commentRangeEndToDelete)
            {
                c.Remove();
            }

            // Delete CommentReference within main document.
            List <CommentReference> commentRangeReferenceToDelete =
                doc.Descendants <CommentReference>().
                Where(c => commentIds.Contains(c.Id.Value)).ToList();

            foreach (CommentReference c in commentRangeReferenceToDelete)
            {
                c.Remove();
            }

            // Save changes back to the MainDocumentPart part.
        }
Пример #27
0
 /// <summary>
 /// Comment object, Get support mothod.
 /// </summary>
 /// <param name="commentsPart">Target comment include commentsPart</param>
 /// <param name="commentID">Comment ID</param>
 /// <returns>Comment Object</returns>
 private Comment GetComment(WordprocessingCommentsPart commentsPart, string commentID)
 {
     return(commentsPart.Comments.Descendants <Comment>().Where(e => e.Id == commentID).Single());
 }
Пример #28
0
        /// <summary>
        /// Edit Comment and CommentEx
        /// </summary>
        /// <param name="filePath">Editing target file path</param>
        /// <param name="log">Logger</param>
        public void EditElements(string filePath, VerifiableLog log)
        {
            using (WordprocessingDocument package = WordprocessingDocument.Open(filePath, true))
            {
                WordprocessingCommentsPart   commentPart   = package.MainDocumentPart.WordprocessingCommentsPart;
                WordprocessingCommentsExPart commentExPart = package.MainDocumentPart.WordprocessingCommentsExPart;
                Comment       comment   = null;
                W15.CommentEx commentEx = null;

                try
                {
                    //2.1 Change comment text
                    comment = GetComment(commentPart, CommentIDs.CommentID1);
                    Text text = comment.Descendants <Text>().First();
                    text.Text = CommentStrings.CommentChangeString1;

                    log.Pass("Edited comment text. comment ID=[{0}]. comment text=[{1}].", CommentIDs.CommentID1, CommentStrings.CommentChangeString1);
                }
                catch (Exception e)
                {
                    log.Fail(e.Message);
                }

                try
                {
                    //2.2 Change commnet initials attribute
                    comment = GetComment(commentPart, CommentIDs.CommentID1);

                    comment.Initials = CommentInitials.Initial2;
                    log.Pass("Edited comment attribute of Initials. comment ID=[{0}]. Initials=[{1}].", CommentIDs.CommentID1, CommentInitials.Initial2);

                    //2.2 Change commnet date attribute
                    comment.Date = new DateTimeValue(new DateTime(2015, 12, 24, 12, 34, 56, 77));
                    log.Pass("Edited comment attribute of Date. comment ID=[{0}]. Date=[{1}/{2}/{3}-{4}:{5}:{6}-{7}].", CommentIDs.CommentID1, 12, 24, 2015, 12, 34, 56, 77);

                    //2.2 Change commnet author attribute
                    comment.Author = CommentAuthors.Author2;
                    log.Pass("Edited comment attribute of Author. comment ID=[{0}]. Author=[{1}].", CommentIDs.CommentID1, CommentAuthors.Author2);
                }
                catch (Exception e)
                {
                    log.Fail(e.Message);
                }

                try
                {
                    //2.3 Change comment parent-child relationship, Case of parent attribute deleteing.
                    commentEx = GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID2);
                    commentEx.ParaIdParent = null;
                    log.Pass("Edited CommentEx parent-child relationship, Set CommentEx parent id is null. comment ID=[{0}]. CommentEx.ParaIdParent=[null].", CommentIDs.CommentID2);

                    //2.3 Change comment parent-child relationship, Case of parent attribute appending.
                    commentEx = GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID3);
                    W15.CommentEx comEx = GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID2);
                    commentEx.ParaIdParent = comEx.ParaId;
                    log.Pass("Edited CommentEx parent-child relationship, Set CommentEx parent id is comment(id=1) have id. comment ID=[{0}]. CommentEx.ParaIdParent=[{1}].", CommentIDs.CommentID3, comEx.ParaId.Value);
                }
                catch (Exception e)
                {
                    log.Fail(e.Message);
                }

                try
                {
                    //2.4 Change CommnetEx done attribute, Case of value "1" setting.
                    GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID1).Done = true;
                    log.Pass("Edited CommentEx attribute of Done. comment ID=[{0}]. Done=[true].", CommentIDs.CommentID1);

                    //2.4 Change CommnetEx done attribute, Case of value "0" setting.
                    GetCommentEx(commentPart, commentExPart, CommentIDs.CommentID3).Done = false;
                    log.Pass("Edited CommentEx attribute of Done. comment ID=[{0}]. Done=[false].", CommentIDs.CommentID3);
                }
                catch (Exception e)
                {
                    log.Fail(e.Message);
                }

                try
                {
                    //2.5 Add comment and CommentEx.
                    CommentRangeStart commentRangeStart1 = new CommentRangeStart();
                    commentRangeStart1.Id = CommentIDs.CommentID4;
                    CommentRangeEnd CommentRangeEnd1 = new CommentRangeEnd();
                    CommentRangeEnd1.Id = CommentIDs.CommentID4;

                    Paragraph paragraph1 = package.MainDocumentPart.Document.Descendants <Paragraph>().Where(e => e.InnerText == CommentBodyStrings.Comment2).First();
                    paragraph1.Descendants <Run>().Where(e => e.InnerText == CommentBodyStrings.Comment2).First().InsertBeforeSelf <CommentRangeStart>(commentRangeStart1);
                    paragraph1.Descendants <Run>().Where(e => e.InnerText == CommentBodyStrings.Comment2).First().InsertAfterSelf <CommentRangeEnd>(CommentRangeEnd1);

                    CommentReference commentReference1 = new CommentReference();
                    commentReference1.Id = CommentIDs.CommentID4;
                    Run run1 = new Run();
                    run1.AppendChild <CommentReference>(commentReference1);

                    paragraph1.AppendChild <Run>(run1);
                    Comment comment1 = (Comment)GetComment(commentPart, CommentIDs.CommentID1).Clone();
                    comment1.Id = CommentIDs.CommentID4;
                    comment1.Descendants <Text>().First().Text             = CommentStrings.CommentAppendString1;
                    comment1.Descendants <Paragraph>().First().ParagraphId = AppendCommentExIDs.AppendCommentID1;

                    commentPart.Comments.AppendChild <Comment>(comment1);

                    W15.CommentEx commentEx1 = new W15.CommentEx();
                    commentEx1.ParaId = AppendCommentExIDs.AppendCommentID1;
                    commentExPart.CommentsEx.AppendChild <W15.CommentEx>(commentEx1);

                    log.Pass("Append new comment. comment ID=[{0}]. comment text=[{1}]. CommentEx.ParaIdParent=[null].", CommentIDs.CommentID4, CommentStrings.CommentAppendString1);

                    //2.5 Add comment and CommentEx.
                    CommentRangeStart commentRangeStart2 = new CommentRangeStart();
                    commentRangeStart2.Id = CommentIDs.CommentID5;
                    CommentRangeEnd CommentRangeEnd2 = new CommentRangeEnd();
                    CommentRangeEnd2.Id = CommentIDs.CommentID5;

                    Paragraph paragraph2 = package.MainDocumentPart.Document.Descendants <Paragraph>().Where(e => e.InnerText == CommentBodyStrings.Comment2).First();
                    paragraph2.Descendants <Run>().Where(e => e.InnerText == CommentBodyStrings.Comment2).First().InsertBeforeSelf <CommentRangeStart>(commentRangeStart2);
                    paragraph2.Descendants <Run>().Where(e => e.InnerText == CommentBodyStrings.Comment2).First().InsertAfterSelf <CommentRangeEnd>(CommentRangeEnd2);

                    CommentReference commentReference2 = new CommentReference();
                    commentReference2.Id = CommentIDs.CommentID5;
                    Run run2 = new Run();
                    run2.AppendChild <CommentReference>(commentReference2);

                    paragraph2.AppendChild <Run>(run2);
                    Comment comment2 = (Comment)GetComment(commentPart, CommentIDs.CommentID2).Clone();
                    comment2.Id = CommentIDs.CommentID5;
                    comment2.Descendants <Text>().First().Text             = CommentStrings.CommentAppendString2;
                    comment2.Descendants <Paragraph>().First().ParagraphId = AppendCommentExIDs.AppendCommentID2;

                    commentPart.Comments.AppendChild <Comment>(comment2);

                    W15.CommentEx commentEx2 = new W15.CommentEx();
                    commentEx2.ParaId       = AppendCommentExIDs.AppendCommentID2;
                    commentEx2.ParaIdParent = AppendCommentExIDs.AppendCommentID1;
                    commentExPart.CommentsEx.AppendChild <W15.CommentEx>(commentEx2);

                    log.Pass("Append new comment. comment ID=[{0}]. comment text=[{1}]. CommentEx.ParaIdParent=[{2}].", CommentIDs.CommentID5, CommentStrings.CommentAppendString2, AppendCommentExIDs.AppendCommentID1);
                }
                catch (Exception e)
                {
                    log.Fail(e.Message);
                }
            }
        }
Пример #29
0
        private void SetupStyles()
        {
            WordprocessingCommentsPart commentsPart        = AddTemplatePart <WordprocessingCommentsPart>(this.document, CommentsStyleResource);
            EndnotesPart             endNotesPart          = AddTemplatePart <EndnotesPart>(this.document, EndNotesStyleResource);
            FontTablePart            fontTablePart         = AddTemplatePart <FontTablePart>(this.document, FontsTableStyleResource);
            FootnotesPart            footnotesPart         = AddTemplatePart <FootnotesPart>(this.document, FootNotesStyleResource);
            HeaderPart               headerPart            = AddTemplatePart <HeaderPart>(this.document, HeaderStyleResource);
            DocumentSettingsPart     settingsPart          = AddTemplatePart <DocumentSettingsPart>(this.document, SettingsStyleResource);
            StyleDefinitionsPart     styles                = AddTemplatePart <StyleDefinitionsPart>(this.document, StylesStyleResource);
            StylesWithEffectsPart    stylesWithEffectsPart = AddTemplatePart <StylesWithEffectsPart>(this.document, StylesWithEffectsStyleResource);
            WebSettingsPart          webSettingsPart       = AddTemplatePart <WebSettingsPart>(this.document, WebSettingsStyleResource);
            ThemePart                themePart             = AddTemplatePart <ThemePart>(this.document, ThemeStyleResource);
            NumberingDefinitionsPart numberingPart         = AddTemplatePart <NumberingDefinitionsPart>(this.document, NumberingStyleResource);

            // Initialize the comments manager with the comments part
            this.commentManager = new CommentManager(commentsPart.Comments);

            // Initialize the footer
            string     footerTitle      = this.implementationGuide.GetDisplayName();
            DateTime   footerDate       = this.implementationGuide.PublishDate != null ? this.implementationGuide.PublishDate.Value : DateTime.Now;
            string     footerDateString = footerDate.ToString("m");
            FooterPart newFooterPart    = this.document.MainDocumentPart.AddNewPart <FooterPart>();
            Footer     newFooter        = new Footer();
            Paragraph  pFooter          = new Paragraph(
                new ParagraphProperties(
                    new ParagraphStyleId()
            {
                Val = "Footer"
            }));

            pFooter.Append(
                new Run(
                    new Text(footerTitle)),
                new Run(
                    new TabChar(),
                    new Text(footerDateString)
            {
                Space = SpaceProcessingModeValues.Preserve
            }),
                new Run(
                    new TabChar(),
                    new Text("Page ")
            {
                Space = SpaceProcessingModeValues.Preserve
            }),
                new Run(
                    new FieldChar()
            {
                FieldCharType = FieldCharValues.Begin
            }),
                new Run(
                    new FieldCode(" PAGE ")
            {
                Space = SpaceProcessingModeValues.Preserve
            }),
                new Run(
                    new FieldChar()
            {
                FieldCharType = FieldCharValues.Separate
            }),
                new Run(
                    new RunProperties(
                        new NoProof()),
                    new Text("54")),
                new Run(
                    new FieldChar()
            {
                FieldCharType = FieldCharValues.End
            }));
            newFooter.Append(pFooter);
            newFooterPart.Footer = newFooter;

            // Add numbering for templates
            foreach (Template cTemplate in this.templates)
            {
                NumberingInstance ni = new NumberingInstance(
                    new AbstractNumId()
                {
                    Val = 3
                })
                {
                    NumberID = GenerationConstants.BASE_TEMPLATE_INDEX + (int)cTemplate.Id
                };

                for (int i = 0; i < 9; i++)
                {
                    ni.Append(new LevelOverride(
                                  new StartOverrideNumberingValue()
                    {
                        Val = 1
                    })
                    {
                        LevelIndex = i
                    });
                }

                numberingPart.Numbering.Append(ni);
            }
        }
Пример #30
0
        //gavdcodeend 13

        //gavdcodebegin 14
        public static void WordOpenXmlAddComment()
        {
            using (WordprocessingDocument myWordDoc =
                       WordprocessingDocument.Open(@"C:\Temporary\WordDoc01.docx", true))
            {
                // Locate the first paragraph in the document.
                Paragraph firstParagraph =
                    myWordDoc.MainDocumentPart.Document.Descendants <Paragraph>().First();
                Comments myComments = null;
                string   id         = "0";

                if (myWordDoc.MainDocumentPart.
                    GetPartsOfType <WordprocessingCommentsPart>().Count() > 0)
                {
                    myComments =
                        myWordDoc.MainDocumentPart.WordprocessingCommentsPart.Comments;
                    if (myComments.HasChildren)
                    {
                        id = myComments.Descendants <Comment>().Select
                                 (e => e.Id.Value).Max();
                    }
                }
                else
                {
                    WordprocessingCommentsPart commentPart =
                        myWordDoc.MainDocumentPart.AddNewPart <WordprocessingCommentsPart>();
                    commentPart.Comments = new Comments();
                    myComments           = commentPart.Comments;
                }

                Paragraph myParagraph = new Paragraph(
                    new Run(new Text("This is a new comment")));
                Comment newComment =
                    new Comment()
                {
                    Id       = id,
                    Author   = "OtherAuthor",
                    Initials = "ioa",
                    Date     = DateTime.Now
                };
                newComment.AppendChild(myParagraph);
                myComments.AppendChild(newComment);
                myComments.Save();

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

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

                firstParagraph.InsertAfter(new Run(
                                               new CommentReference()
                {
                    Id = id
                }), commentEnd);
            }
        }