This example demonstrates how to use fields in Word documents using go-docx v2.
Fields are dynamic elements in Word documents that can automatically calculate and display values. They are updated when:
- The document is opened in Word
- The user presses F9 (Update Field)
- The document is printed or converted to PDF
PAGE: Current page numberNUMPAGES: Total page count- Used in headers/footers for page numbering
- Automatically generated from heading styles
- Supports custom heading levels (e.g., 1-3)
- Includes hyperlinks to sections
- Updates automatically when headings change
HYPERLINK: Links to external URLs or internal bookmarks- Displays custom text while linking to a URL
- Can be styled with color and underline
STYLEREF: References text with a specific style- Useful for running headers (e.g., chapter titles)
SEQ: Automatic numbering for figures, tables, equations- Maintains separate counters for different categories
DATE: Current dateTIME: Current time- Supports custom formatting
cd examples/04_fields
go run main.goThis will create fields_example.docx with:
- A Table of Contents at the beginning
- Multiple sections with headings
- Page numbers in the footer ("Page X of Y")
- Sample hyperlinks
- Various content to demonstrate field functionality
// Create page number field
pageField := docx.NewPageNumberField()
run.AddField(pageField)
// Create TOC with custom options
tocOptions := map[string]string{
"levels": "1-3", // Include heading levels 1-3
"hyperlinks": "true", // Enable hyperlinks
}
tocField := docx.NewTOCField(tocOptions)
// Create hyperlink
hyperlinkField := docx.NewHyperlinkField(
"https://example.com",
"Example Link",
)
run.AddField(hyperlinkField)Fields display placeholder values until updated in Word. To update:
- Open the document in Microsoft Word
- Press Ctrl+A (Select All)
- Press F9 (Update Fields)
- Or right-click on a field and select "Update Field"
You can view the underlying field codes in Word:
- Press Alt+F9 to toggle field code display
- Right-click a field and select "Toggle Field Codes"
The TOC field supports many switches:
\o "1-3": Use heading levels 1-3\h: Include hyperlinks\z: Hide tab leader in Web Layout\u: Use outline levels\n: Hide page numbers\p: Use paragraph formatting
field := docx.NewField(docx.FieldTypeCustom)
field.SetCode(`STYLEREF "Heading 1" \* MERGEFORMAT`)tocOptions := map[string]string{
"levels": "1-5", // Deeper hierarchy
"hidePageNumbers": "true", // No page numbers
"hideTabLeader": "true", // No dots
}// Reference a bookmark
refField := docx.NewField(docx.FieldTypeRef)
refField.SetCode(`REF MyBookmark \h`)- Example 01: Hello World - Basic document creation
- Example 02: Formatted Text - Text formatting
- Example 03: Table of Contents - TOC generation
- API Documentation
- OOXML Field Reference