Lavorare con i commenti

Aspose.Words consente agli utenti di lavorare con i commenti: i commenti in un documento in Aspose.Words sono rappresentati dalla classe Comment. Utilizzare anche le classi CommentRangeStart e CommentRangeEnd per specificare l’area di testo che deve essere associata a un commento.

Aggiungi un commento

Aspose.Words consente di aggiungere commenti in diversi modi:

  1. Utilizzo della classe Comment
  2. Utilizzo delle classi CommentRangeStart e CommentRangeEnd

L’esempio di codice seguente mostra come aggiungere un commento a un paragrafo utilizzando la classe Comment:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
String dataDir = Utils.getDataDir(AddComments.class);
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.write("Some text is added.");
Comment comment = new Comment(doc, "Awais Hafeez", "AH", new Date());
builder.getCurrentParagraph().appendChild(comment);
comment.getParagraphs().add(new Paragraph(doc));
comment.getFirstParagraph().getRuns().add(new Run(doc, "Comment text."));
doc.save(dataDir + "output.doc");

Nell’esempio di codice seguente viene illustrato come aggiungere un commento a un paragrafo utilizzando un’area di testo e le classi CommentRangeStart e CommentRangeEnd:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
String dataDir = Utils.getDataDir(AnchorComment.class);
Document doc = new Document();
Paragraph para1 = new Paragraph(doc);
Run run1 = new Run(doc, "Some ");
Run run2 = new Run(doc, "text ");
para1.appendChild(run1);
para1.appendChild(run2);
doc.getFirstSection().getBody().appendChild(para1);
Paragraph para2 = new Paragraph(doc);
Run run3 = new Run(doc, "is ");
Run run4 = new Run(doc, "added ");
para2.appendChild(run3);
para2.appendChild(run4);
doc.getFirstSection().getBody().appendChild(para2);
Comment comment = new Comment(doc, "Awais Hafeez", "AH", new Date());
comment.getParagraphs().add(new Paragraph(doc));
comment.getFirstParagraph().getRuns().add(new Run(doc, "Comment text."));
CommentRangeStart commentRangeStart = new CommentRangeStart(doc, comment.getId());
CommentRangeEnd commentRangeEnd = new CommentRangeEnd(doc, comment.getId());
run1.getParentNode().insertAfter(commentRangeStart, run1);
run3.getParentNode().insertAfter(commentRangeEnd, run3);
commentRangeEnd.getParentNode().insertAfter(comment, commentRangeEnd);
doc.save(dataDir + "output.doc");

Estrarre o rimuovere i commenti

L’utilizzo dei commenti in un documento Word (oltre a tenere traccia delle modifiche) è una pratica comune durante la revisione dei documenti, in particolare quando ci sono più revisori. Ci possono essere situazioni in cui l’unica cosa di cui hai bisogno da un documento sono i commenti. Supponiamo che tu voglia generare un elenco di risultati delle recensioni, o forse hai raccolto tutte le informazioni utili dal documento e vuoi semplicemente rimuovere i commenti non necessari. Potresti voler visualizzare o rimuovere i commenti di un determinato revisore.

In questo esempio, esamineremo alcuni metodi semplici sia per raccogliere informazioni dai commenti all’interno di un documento che per rimuovere i commenti da un documento. In particolare, copriremo come:

  • Estrarre tutti i commenti da un documento o solo quelli fatti da un particolare autore.
  • Rimuovere tutti i commenti da un documento o solo da un determinato autore.

Come estrarre o rimuovere i commenti

Il codice in questo esempio è abbastanza semplice e tutti i metodi sono basati sullo stesso approccio. Un commento in un documento di Word è rappresentato da un oggetto Comment nel modello a oggetti del documento Aspose.Words. Per raccogliere tutti i commenti in un documento utilizzare il metodo getChildNodes con il primo parametro impostato su NodeType.Comment. Assicurarsi che il secondo parametro del metodo getChildNodes sia impostato su true: questo costringe il getChildNodes a selezionare ricorsivamente da tutti i nodi figlio, piuttosto che raccogliere solo i figli immediati.

Per illustrare come estrarre e rimuovere i commenti da un documento, passeremo attraverso i seguenti passaggi:

  1. Aprire un documento Word usando la classe Document
  2. Ottenere tutti i commenti dal documento in una raccolta
  3. Per estrarre i commenti:
    1. Passare attraverso la raccolta utilizzando il per l’operatore
    2. Estrarre ed elencare il nome dell’autore, la data e l’ora e il testo di tutti i commenti
    3. Estrarre ed elencare il nome dell’autore, la data e l’ora e il testo dei commenti scritti da un autore specifico, in questo caso, l’autore’ks'
  4. Per rimuovere i commenti:
    1. Andare indietro attraverso la raccolta usando il per l’operatore
    2. Rimuovi commenti
  5. Salva le modifiche.

Useremo il seguente documento Word per questo esercizio:

extract-remove-comments-aspose-words-java-1

Come puoi vedere, contiene diversi commenti di due autori con le iniziali “pm"e " ks”.

Come estrarre tutti i commenti

Il metodo getChildNodes è molto utile e puoi usarlo ogni volta che hai bisogno di ottenere un elenco di nodi di documenti di qualsiasi tipo. La raccolta risultante non crea un overhead immediato perché i nodi vengono selezionati in questa raccolta solo quando si enumerano o si accedono agli elementi in essa contenuti.

Il seguente esempio di codice mostra come estrarre il nome dell’autore, la data e l’ora e il testo di tutti i commenti nel documento:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
ArrayList collectedComments = new ArrayList();
// Collect all comments in the document
NodeCollection comments = doc.getChildNodes(NodeType.COMMENT, true);
// Look through all comments and gather information about them.
for (Comment comment : (Iterable<Comment>) comments) {
collectedComments.add(comment.getAuthor() + " " + comment.getDateTime() + " " + comment.toString(SaveFormat.TEXT));
}
return collectedComments;

Come estrarre i commenti di un autore specificato

Dopo aver selezionato i nodi di commento in una raccolta, tutto ciò che devi fare è estrarre le informazioni necessarie. In questo esempio, le iniziali dell’autore, la data, l’ora e il testo normale del commento sono combinati in un’unica stringa; è possibile scegliere di memorizzarlo in altri modi.

Il metodo sovraccarico che estrae i commenti da un particolare autore è quasi lo stesso, controlla solo il nome dell’autore prima di aggiungere le informazioni nell’array.

L’esempio di codice seguente mostra come estrarre il nome dell’autore, la data e l’ora e il testo dei commenti dell’autore specificato:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
ArrayList collectedComments = new ArrayList();
// Collect all comments in the document
NodeCollection comments = doc.getChildNodes(NodeType.COMMENT, true);
// Look through all comments and gather information about those written by the authorName author.
for (Comment comment : (Iterable<Comment>) comments) {
if (comment.getAuthor().equals(authorName))
collectedComments.add(comment.getAuthor() + " " + comment.getDateTime() + " " + comment.toString(SaveFormat.TEXT));
}
return collectedComments;

Come rimuovere i commenti

Se si rimuovono tutti i commenti, non è necessario spostarsi nella raccolta eliminando i commenti uno per uno; è possibile rimuoverli chiamando clear nella raccolta commenti.

Il seguente esempio di codice mostra come rimuovere tutti i commenti nel documento:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// Collect all comments in the document
NodeCollection comments = doc.getChildNodes(NodeType.COMMENT, true);
// Remove all comments.
comments.clear();

Quando è necessario rimuovere selettivamente i commenti, il processo diventa più simile al codice che abbiamo usato per l’estrazione dei commenti.

L’esempio di codice seguente mostra come rimuovere i commenti dall’autore specificato:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// Collect all comments in the document
NodeCollection comments = doc.getChildNodes(NodeType.COMMENT, true);
// Look through all comments and remove those written by the authorName author.
for (int i = comments.getCount() - 1; i >= 0; i--) {
Comment comment = (Comment) comments.get(i);
if (comment.getAuthor().equals(authorName))
comment.remove();
}
}

Il punto principale da evidenziare qui è l’uso dell’operatore for. A differenza della semplice estrazione, qui si desidera eliminare un commento. Un trucco adatto è quello di iterare la raccolta all’indietro dall’ultimo commento al primo. La ragione di ciò se si inizia dalla fine e si sposta all’indietro, l’indice degli elementi precedenti rimane invariato e si può tornare al primo elemento della raccolta.

Il seguente esempio di codice mostra i metodi per l’estrazione e la rimozione dei commenti:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ProcessComments.class);
// Open the document.
Document doc = new Document(dataDir + "TestFile.doc");
for (String comment : (Iterable<String>) extractComments(doc))
System.out.print(comment);
// Remove comments by the "pm" author.
removeComments(doc, "pm");
System.out.println("Comments from \"pm\" are removed!");
// Extract the information about the comments of the "ks" author.
for (String comment : (Iterable<String>) extractComments(doc, "ks"))
System.out.print(comment);
//Read the comment's reply and resolve them.
System.out.println("Read the comment's reply and resolve them.");
CommentResolvedandReplies(doc);
// Remove all comments.
removeComments(doc);
System.out.println("All comments are removed!");
// Save the document.
doc.save(dataDir + "output.doc");

Quando viene avviato, il campione visualizza i seguenti risultati. Innanzitutto, elenca tutti i commenti di tutti gli autori, quindi elenca solo i commenti dell’autore selezionato. Infine, il codice rimuove tutti i commenti.

extract-remove-comments-aspose-words-java-2

Il documento di Word di output ha ora i commenti rimossi da esso:

extract-remove-comments-aspose-words-java-3

Come rimuovere il testo tra CommentRangeStart e CommentRangeEnd

Usando Aspose.Words puoi anche rimuovere i commenti tra i nodi CommentRangeStart e CommentRangeEnd.

Il seguente esempio di codice mostra come rimuovere il testo tra CommentRangeStart e CommentRangeEnd:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(RemoveCommentRegionText.class);
// Open the document.
Document doc = new Document(dataDir + "TestFile.doc");
CommentRangeStart commentStart = (CommentRangeStart) doc.getChild(NodeType.COMMENT_RANGE_START, 0, true);
CommentRangeEnd commentEnd = (CommentRangeEnd) doc.getChild(NodeType.COMMENT_RANGE_END, 0, true);
Node currentNode = commentStart;
Boolean isRemoving = true;
while (currentNode != null && isRemoving) {
if (currentNode.getNodeType() == NodeType.COMMENT_RANGE_END)
isRemoving = false;
Node nextNode = currentNode.nextPreOrder(doc);
currentNode.remove();
currentNode = nextNode;
}
doc.save(dataDir + "output.doc");

Aggiungere o rimuovere la risposta del commento

Il metodo addReply aggiunge una risposta a questo commento. Si noti che a causa delle limitazioni esistenti di MS Office è consentito solo un (1) livello di risposte nel documento. Un’eccezione di tipo InvalidOperationException verrà sollevata se questo metodo viene chiamato sul commento di risposta esistente.

È possibile utilizzare il metodo removeReply per rimuovere la risposta specificata a questo commento.

L’esempio di codice seguente mostra come aggiungere una risposta a un commento e rimuovere la risposta di un commento:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
Document doc = new Document(dataDir + "TestFile.doc");
Comment comment = (Comment) doc.getChild(NodeType.COMMENT, 0, true);
//Remove the reply
comment.removeReply(comment.getReplies().get(0));
//Add a reply to comment
comment.addReply("John Doe", "JD", new Date(), "New reply");
dataDir = dataDir + "TestFile_Out.doc";
// Save the document to disk.
doc.save(dataDir);

Leggi la risposta del commento

Aspose.Words supporto per leggere la risposta di un commento. La proprietà Replies restituisce una raccolta degli oggetti Comment che sono figli immediati del commento specificato.

Il seguente esempio di codice mostra come scorrere le risposte di un commento e risolverle:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
static void CommentResolvedandReplies(Document doc) {
NodeCollection<Comment> comments = doc.getChildNodes(NodeType.COMMENT, true);
Comment parentComment = (Comment) comments.get(0);
for (Comment childComment : parentComment.getReplies()) {
// Get comment parent and status.
System.out.println(childComment.getAncestor().getId());
System.out.println(childComment.getDone());
// And update comment Done mark.
childComment.setDone(true);
}
}