Retrieve Comments

This guide will show the process of retrieving comments from docx document using unioffice.

Before you begin

You should get your API key from your UniCloud account.

If this is your first time using UniOffice SDK, follow this guide to set up a local development environment.

Clone the project repository

In your terminal, clone the examples repository. It contains the Go code we will be using for this guide.

git clone https://github.com/unidoc/unioffice-examples

To get the example navigate to the path document/document/comment-list/ folder in the unioffice-examples directory.

cd unioffice-examples/document/document/comment-list/

How it works

/*
* Copyright 2025 FoxyUtils ehf. All rights reserved.
*
* This example demonstrates how to retrieve and display comments stored within a DOCX file.
*/
package main
import (
"fmt"
"log"
"os"
"github.com/unidoc/unioffice/v2/common/license"
"github.com/unidoc/unioffice/v2/document"
)
func init() {
// Make sure to load your metered License API key prior to using the library.
// If you need a key, you can sign up and create a free one at https://cloud.unidoc.io
err := license.SetMeteredKey(os.Getenv(`UNIDOC_LICENSE_API_KEY`))
if err != nil {
panic(err)
}
}
func main() {
doc, err := document.Open("sample.docx")
if err != nil {
log.Fatalf("error opening document: %s", err)
}
defer doc.Close()
// Check if the document has comments.
if !doc.HasComments() {
fmt.Println("Document has no comment")
return
}
comments := doc.Comments()
fmt.Printf("Document has %d comments:\n", len(comments))
// Iterate through the comments structure and display the comment text.
for _, c := range comments {
cmt := c.X()
fmt.Printf("%d. Comment by %s: ", cmt.IdAttr, cmt.AuthorAttr)
for _, ble := range cmt.EG_BlockLevelElts {
for _, cbc := range ble.BlockLevelEltsChoice.EG_ContentBlockContent {
for _, p := range cbc.ContentBlockContentChoice.P {
for _, pc := range p.EG_PContent {
for _, crc := range pc.PContentChoice.EG_ContentRunContent {
for _, ric := range crc.ContentRunContentChoice.R.EG_RunInnerContent {
if ric.RunInnerContentChoice.T != nil {
fmt.Println(ric.RunInnerContentChoice.T.Content)
}
}
}
}
}
}
}
}
}

The example code starts by the import section followed by the init function in lines 9-25. With these the necessary dependencies are imported and the api key is set respectively.

The main function which contains the main code is defined in lines 27-72. It starts by checking the arguments given in the command line. In line 33, it sets the inputPath variable with the path to the docx file provided in the second argument. Line 35 opens this document using document.Open(inputPath). Line 42 checks if the document contains comments by calling the doc.HasComments() method. If the document has comments, they are retrieved using doc.Comments() in line 47. Then the multiple nested for loops in lines 52-72 iterates through each comment and print its content.

Got any Questions?

We're here to help you.