Replace text and images in a .docx file
masterTo modify a Microsoft Word document, use docx.ReadDocxFile to load the document, call .Editable() to get an editable instance, and then perform replacements. The library supports replacing text in the main body, headers, footers, hyperlinks, and images. Finally, save the changes using .WriteToFile() or .Write().
package main
import (
"strconv"
"github.com/nguyenthenguyen/docx"
)
func main() {
// 1. Read the file
r, err := docx.ReadDocxFile("./TestDocument.docx")
if err != nil {
panic(err)
}
defer r.Close()
// 2. Create an editable instance
docx1 := r.Editable()
// 3. Perform replacements
docx1.Replace("old_text", "new_text", -1) // -1 replaces all occurrences
docx1.ReplaceLink("http://old.com", "https://new.com", 1)
docx1.ReplaceHeader("old header", "new header")
docx1.ReplaceFooter("old footer", "new footer")
// 4. Save the result
docx1.WriteToFile("./new_result.docx")
}