Lucrul cu comentarii

Aspose.Words permite utilizatorilor să lucreze cu comentarii-comentariile dintr-un document din Aspose.Words sunt reprezentate de clasa Comment. De asemenea, utilizați clasele CommentRangeStart și CommentRangeEnd pentru a specifica regiunea de text care ar trebui asociată cu un comentariu.

Adaugă un comentariu

Aspose.Words vă permite să adăugați comentarii în mai multe moduri:

  1. Folosind clasa Comment
  2. Folosind clasele CommentRangeStart și CommentRangeEnd

Următorul exemplu de cod arată cum să adăugați un comentariu la un paragraf folosind clasa Comment:

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_WorkingWithComments();
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->Write(u"Some text is added.");
System::SharedPtr<Comment> comment = System::MakeObject<Comment>(doc, u"Awais Hafeez", u"AH", System::DateTime::get_Today());
builder->get_CurrentParagraph()->AppendChild(comment);
comment->get_Paragraphs()->Add(System::MakeObject<Paragraph>(doc));
comment->get_FirstParagraph()->get_Runs()->Add(System::MakeObject<Run>(doc, u"Comment text."));
System::String outputPath = outputDataDir + u"AddComments.doc";
// Save the document.
doc->Save(outputPath);

Următorul exemplu de cod arată cum să adăugați un comentariu la un paragraf folosind o regiune de text și clasele CommentRangeStart și CommentRangeEnd:

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_WorkingWithComments();
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<Paragraph> para1 = System::MakeObject<Paragraph>(doc);
System::SharedPtr<Run> run1 = System::MakeObject<Run>(doc, u"Some ");
System::SharedPtr<Run> run2 = System::MakeObject<Run>(doc, u"text ");
para1->AppendChild(run1);
para1->AppendChild(run2);
doc->get_FirstSection()->get_Body()->AppendChild(para1);
System::SharedPtr<Paragraph> para2 = System::MakeObject<Paragraph>(doc);
System::SharedPtr<Run> run3 = System::MakeObject<Run>(doc, u"is ");
System::SharedPtr<Run> run4 = System::MakeObject<Run>(doc, u"added ");
para2->AppendChild(run3);
para2->AppendChild(run4);
doc->get_FirstSection()->get_Body()->AppendChild(para2);
System::SharedPtr<Comment> comment = System::MakeObject<Comment>(doc, u"Awais Hafeez", u"AH", System::DateTime::get_Today());
comment->get_Paragraphs()->Add(System::MakeObject<Paragraph>(doc));
comment->get_FirstParagraph()->get_Runs()->Add(System::MakeObject<Run>(doc, u"Comment text."));
System::SharedPtr<CommentRangeStart> commentRangeStart = System::MakeObject<CommentRangeStart>(doc, comment->get_Id());
System::SharedPtr<CommentRangeEnd> commentRangeEnd = System::MakeObject<CommentRangeEnd>(doc, comment->get_Id());
run1->get_ParentNode()->InsertAfter(commentRangeStart, run1);
run3->get_ParentNode()->InsertAfter(commentRangeEnd, run3);
commentRangeEnd->get_ParentNode()->InsertAfter(comment, commentRangeEnd);
System::String outputPath = outputDataDir + u"AnchorComment.doc";
// Save the document.
doc->Save(outputPath);

Extrageți sau eliminați comentariile

Utilizarea comentariilor într-un document Word (în plus față de modificările de urmărire) este o practică obișnuită atunci când revizuiți documente, în special atunci când există mai mulți recenzenți. Pot exista situații în care singurul lucru de care aveți nevoie dintr-un document sunt comentariile. Spuneți că doriți să generați o listă de constatări ale revizuirii sau poate că ați colectat toate informațiile utile din document și pur și simplu doriți să eliminați comentariile inutile. Poate doriți să vizualizați sau să eliminați comentariile unui anumit recenzent.

În acest eșantion, vom analiza câteva metode simple atât pentru colectarea informațiilor din comentariile dintr-un document, cât și pentru eliminarea comentariilor dintr-un document. Mai exact, vom acoperi cum să:

  • Extrageți toate comentariile dintr-un document sau numai cele făcute de un anumit autor.
  • Eliminați toate comentariile dintr-un document sau numai de la un anumit autor.

Cum să extrageți sau să eliminați comentariile

Codul din acest eșantion este de fapt destul de simplu și toate metodele se bazează pe aceeași abordare. Un comentariu într-un document Word este reprezentat de un obiect Comment în modelul de obiect document Aspose.Words. Pentru a colecta toate comentariile dintr-un document, utilizați metoda GetChildNodes cu primul parametru setat la NodeType.Comment. Asigurați-vă că al doilea parametru al metodei GetChildNodes este setat la true: acest lucru forțează GetChildNodes să selecteze recursiv din toate nodurile copil, mai degrabă decât să colecteze doar copiii imediati.

Pentru a ilustra modul de extragere și eliminare a comentariilor dintr-un document, vom parcurge următorii pași:

  1. Deschideți un document Word folosind clasa Document
  2. Obțineți toate comentariile din document într-o colecție
  3. Pentru a extrage comentarii:
    1. Parcurgeți colecția folosind operatorul foreach
    2. Extrageți și listați numele autorului, data și ora și textul tuturor comentariilor
    3. Extrageți și listați numele autorului, data și ora și textul comentariilor scrise de un anumit autor, în acest caz, autorul’ks'
  4. Pentru a elimina comentariile:
    1. Mergeți înapoi prin colecție folosind pentru operator
    2. Eliminați comentariile
  5. Salvați modificările

Cum să extrageți toate comentariile

Metoda GetChildNodes este foarte utilă și o puteți folosi de fiecare dată când aveți nevoie pentru a obține o listă de noduri de documente de orice tip. Colecția rezultată nu creează o cheltuială imediată, deoarece nodurile sunt selectate în această colecție numai atunci când enumerați sau accesați elemente din ea.

Următorul exemplu de cod arată cum să extrageți numele autorului, data și ora și textul tuturor comentariilor din document:

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
std::vector<System::String> ExtractComments(const System::SharedPtr<Document>& doc)
{
std::vector<System::String> collectedComments;
// Collect all comments in the document
System::SharedPtr<NodeCollection> comments = doc->GetChildNodes(NodeType::Comment, true);
// Look through all comments and gather information about them.
for (System::SharedPtr<Comment> comment : System::IterateOver<System::SharedPtr<Comment>>(comments))
{
collectedComments.push_back(comment->get_Author() + u" " + comment->get_DateTime() + u" " + System::StaticCast<Node>(comment)->ToString(SaveFormat::Text));
}
return collectedComments;
}

Cum să extrageți comentariile unui autor specificat

După ce ați selectat nodurile de comentarii într-o colecție, tot ce trebuie să faceți este să extrageți informațiile de care aveți nevoie. În acest eșantion, inițialele autorului, data, ora și textul simplu al comentariului sunt combinate într-un singur șir; puteți alege să îl stocați în alte moduri.

Metoda supraîncărcată care extrage comentariile de la un anumit autor este aproape aceeași, doar verifică numele autorului înainte de a adăuga informațiile în matrice.

Următorul exemplu de cod arată cum să extrageți numele autorului,data și ora și textul comentariilor de către autorul specificat:

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
std::vector<System::String> ExtractComments(const System::SharedPtr<Document>& doc, const System::String& authorName)
{
std::vector<System::String> collectedComments;
// Collect all comments in the document
System::SharedPtr<NodeCollection> comments = doc->GetChildNodes(NodeType::Comment, true);
// Look through all comments and gather information about those written by the authorName author.
for (System::SharedPtr<Comment> comment : System::IterateOver<System::SharedPtr<Comment>>(comments))
{
if (comment->get_Author() == authorName)
{
collectedComments.push_back(comment->get_Author() + u" " + comment->get_DateTime() + u" " + System::StaticCast<Node>(comment)->ToString(SaveFormat::Text));
}
}
return collectedComments;
}

Cum să eliminați comentariile

Dacă eliminați toate comentariile, nu este nevoie să treceți prin colecție ștergând comentariile unul câte unul; le puteți elimina apelând NodeCollection.Clear din colecția de comentarii.

Următorul exemplu de cod arată cum să eliminați toate comentariile din document:

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
void RemoveComments(const System::SharedPtr<Document>& doc)
{
// Collect all comments in the document
System::SharedPtr<NodeCollection> comments = doc->GetChildNodes(NodeType::Comment, true);
// Remove all comments.
comments->Clear();
}

Când trebuie să eliminați selectiv comentariile, procesul devine mai asemănător cu codul pe care l-am folosit pentru extragerea comentariilor.

Următorul exemplu de cod arată cum să eliminați comentariile autorului specificat:

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
void RemoveComments(const System::SharedPtr<Document>& doc, const System::String& authorName)
{
// Collect all comments in the document
System::SharedPtr<NodeCollection> comments = doc->GetChildNodes(NodeType::Comment, true);
// Look through all comments and remove those written by the authorName author.
for (int32_t i = comments->get_Count() - 1; i >= 0; i--)
{
System::SharedPtr<Comment> comment = System::DynamicCast<Comment>(comments->idx_get(i));
if (comment->get_Author() == authorName)
{
comment->Remove();
}
}
}

Principalul punct de evidențiat aici este utilizarea operatorului for. Spre deosebire de extragerea simplă, aici doriți să ștergeți un comentariu. Un truc potrivit este să iterați colecția înapoi de la ultimul comentariu la primul. Motivul pentru aceasta dacă începeți de la sfârșit și vă deplasați înapoi, indexul articolelor precedente rămâne neschimbat și vă puteți întoarce la primul articol din colecție.

Următorul exemplu de cod prezintă metodele de extragere și eliminare a comentariilor:

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_WorkingWithComments();
System::String outputDataDir = GetOutputDataDir_WorkingWithComments();
// Open the document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile.doc");
// Extract the information about the comments of all the authors.
for (System::String const &comment : ExtractComments(doc))
{
std::cout << comment.ToUtf8String();
}
// Remove comments by the "pm" author.
RemoveComments(doc, u"pm");
std::cout << "Comments from \"pm\" are removed!" << std::endl;
// Extract the information about the comments of the "ks" author.
for (System::String const &comment: ExtractComments(doc, u"ks"))
{
std::cout << comment.ToUtf8String();
}
//Read the comment's reply and resolve them.
CommentResolvedandReplies(doc);
// Remove all comments.
RemoveComments(doc);
std::cout << "All comments are removed!" << std::endl;
System::String outputPath = outputDataDir + u"ProcessComments.doc";
// Save the document.
doc->Save(outputPath);

Cum să eliminați un comentariu între CommentRangeStart și CommentRangeEnd

Folosind Aspose.Words de asemenea, puteți elimina comentariile dintre nodurile CommentRangeStart și CommentRangeEnd.

Următorul exemplu de cod arată cum să eliminați textul între CommentRangeStart și CommentRangeEnd:

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_WorkingWithComments();
System::String outputDataDir = GetOutputDataDir_WorkingWithComments();
// Open the document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile.doc");
System::SharedPtr<CommentRangeStart> commentStart = System::DynamicCast<CommentRangeStart>(doc->GetChild(NodeType::CommentRangeStart, 0, true));
System::SharedPtr<CommentRangeEnd> commentEnd = System::DynamicCast<CommentRangeEnd>(doc->GetChild(NodeType::CommentRangeEnd, 0, true));
System::SharedPtr<Node> currentNode = commentStart;
bool isRemoving = true;
while (currentNode != nullptr && isRemoving)
{
if (currentNode->get_NodeType() == NodeType::CommentRangeEnd)
{
isRemoving = false;
}
System::SharedPtr<Node> nextNode = currentNode->NextPreOrder(doc);
currentNode->Remove();
currentNode = nextNode;
}
System::String outputPath = outputDataDir + u"RemoveRegionText.doc";
// Save the document.
doc->Save(outputPath);

Adăugați și eliminați răspunsul comentariului

Metoda AddReply adaugă un răspuns la acest comentariu. Vă rugăm să rețineți că, din cauza limitărilor Microsoft Office existente, numai 1 Nivelul de răspunsuri este permis în document. O excepție de tip InvalidOperationException va fi ridicată dacă această metodă este apelată la comentariul de răspuns existent.

Puteți utiliza metoda RemoveReply pentru a elimina răspunsul specificat la acest comentariu.

Următorul exemplu de cod arată cum să adăugați un răspuns la comentariu și să eliminați răspunsul comentariului:

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_WorkingWithComments();
System::String outputDataDir = GetOutputDataDir_WorkingWithComments();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile.doc");
System::SharedPtr<Comment> comment = System::DynamicCast<Comment>(doc->GetChild(NodeType::Comment, 0, true));
//Remove the reply
comment->RemoveReply(comment->get_Replies()->idx_get(0));
//Add a reply to comment
comment->AddReply(u"John Doe", u"JD", System::DateTime(2017, 9, 25, 12, 15, 0), u"New reply");
System::String outputPath = outputDataDir + u"CommentReply.doc";
// Save the document to disk.
doc->Save(outputPath);

Citiți răspunsul comentariului

Proprietatea Replies returnează o colecție de obiecte Comment care sunt copii imediați ai comentariului specificat.

Următorul exemplu de cod arată cum să iterați răspunsurile unui comentariu și să le rezolvați:

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
void CommentResolvedandReplies(const System::SharedPtr<Document>& doc)
{
System::SharedPtr<NodeCollection> comments = doc->GetChildNodes(NodeType::Comment, true);
System::SharedPtr<Comment> parentComment = System::DynamicCast<Comment>(comments->idx_get(0));
for (System::SharedPtr<Comment> childComment : System::IterateOver<System::SharedPtr<Comment>>(parentComment->get_Replies()))
{
// Get comment parent and status.
std::cout << childComment->get_Ancestor()->get_Id() << std::endl << childComment->get_Done() << std::endl;
// And update comment Done mark.
childComment->set_Done(true);
}
}