docx Go Library

repository·master·Indexed 20 days ago

https://github.com/nguyenthenguyen/docx

A Go library for programmatic text and image replacement within Microsoft Word (.docx) files. It supports replacing text in the main body, headers, footers, and hyperlinks, as well as swapping images of the same format. The library provides methods to load documents from file paths, memory, or filesystem objects, and allows saving modified content via WriteToFile or Write.

Tokens
2.1K
Snippets
8
Records
8
Agent score
20%

What's inside docx

  1. Replace text and images in a .docx file

    master

    To 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")
    }
  2. Read a .docx file from disk or memory

    master

    To begin editing a document, you must first load it into a *ReplaceDocx object using one of the following methods:

    1. From a file path: Use ReadDocxFile(path string) to open a file directly from the filesystem.
    2. From an in-memory reader: Use ReadDocxFromMemory(data io.ReaderAt, size int64) if you have the file content in memory.
    3. From a filesystem abstraction: Use ReadDocxFromFS(file string, fs fs.FS) for compatibility with Go's io/fs interface.

    Once loaded, you can call .Editable() to obtain a *Docx object, which provides the methods for text, link, header, footer, and image replacement.

    package main
    
    import "github.com/nguyenthenguyen/nguyenthenguyen/docx"
    
    func main() {
        // Load from file
        replaceDocx, err := docx.ReadDocxFile("template.docx")
        if err != nil {
            panic(err)
        }
        defer replaceDocx.Close()
    
        // Transition to the editable Docx object
        d := replaceDocx.Editable()
    
        // Perform replacements...
        d.Replace("{{Name}}", "John Doe", -1)
    
        // Save the result
        err = d.WriteToFile("output.docx")
        if err != nil {
            panic(err)
        }
    }
  3. Replace images in a .docx file

    master

    You can replace existing images within a document using ReplaceImage. Note that the library currently only supports swapping images of the same format (e.g., .png to .png), not converting between formats (e.g., .png to .jpeg).

    To find the correct path for an image, you can use ImagesLen() to determine the total number of images and construct the internal path (typically word/media/imageX.png).

    docx3 := r.Editable()
    
    // Replace a specific image by its internal path
    docx3.ReplaceImage("word/media/image1.png", "./new.png")
    
    // Replace the last image in the document
    imageIndex := docx3.ImagesLen()
    docx3.ReplaceImage("word/media/image"+strconv.Itoa(imageIndex)+".png", "./new.png")
    
    docx3.WriteToFile("./new_result_3.docx")
  4. Read DOCX files from different sources

    master

    The docx package provides three ways to load a document into memory:

    1. From a file path: Use docx.ReadDocxFile(path string).
    2. From memory: Use docx.ReadDocxFromMemory(data io.ReaderAt, size int64).
    3. From a filesystem object: Use docx.ReadDocxFromFS(file string, fs fs.FS).
    r, err := docx.ReadDocxFile("./TestDocument.docx")
    // OR
    r, err := docx.ReadDocxFromMemory(data, size)
    // OR
    r, err := docx.ReadDocxFromFS("file.docx", fs)
  5. Save the modified document

    master

    After performing replacements, you must write the changes back to a file or an io.Writer.

    • WriteToFile(path string): Creates a new file at the specified path and writes the modified .docx content to it.
    • Write(ioWriter io.Writer): Writes the modified .docx content to any provided io.Writer (e.g., a buffer or a network stream).
    // Save to a file
    d.WriteToFile("final_document.docx")
    
    // Or write to a buffer
    var buf bytes.Buffer
    d.Write(&buf)
  6. Replace text in the main document body

    master

    The Replace method allows you to replace occurrences of a string within the main document body. It automatically handles XML encoding for special characters (like newlines and tabs) to ensure the resulting .docx file remains valid.

    • Replace(oldString string, newString string, num int): Replaces num occurrences of oldString with newString. Use -1 to replace all occurrences.
    • ReplaceRaw(oldString string, newString string, num int): Performs a raw string replacement without XML encoding. Use this only if you are providing pre-encoded XML content.
    // Replace all occurrences of {{key}} with a value
    d.Replace("{{key}}", "value", -1)
  7. Replace links, headers, and footers

    master

    The Docx object provides specific methods to target different parts of the document structure:

    • Links: ReplaceLink(oldString string, newString string, num int) replaces text within the document's relationship files (e.g., hyperlinks).
    • Headers: ReplaceHeader(oldString string, newString string) replaces text across all header sections.
    • Footers: ReplaceFooter(oldString string, newString string) replaces text across all footer sections.

    All these methods automatically handle XML encoding for the replacement strings.

    d.ReplaceLink("http://old-url.com", "http://new-url.com", -1)
    d.ReplaceHeader("{{HeaderText}}", "Company Confidential")
    d.ReplaceFooter("Page {{Page}}", "Page")
  8. Reference: Docx replacement methods

    master

    Methods available on the *Docx type for modifying document content.

    func (d *Docx) GetContent() string
    func (d *Docx) SetContent(content string)
    func (d *Docx) ReplaceRaw(oldString string, newString string, num int)
    func (d *Docx) Replace(oldString string, newString string, num int) (err error)
    func (d *Docx) ReplaceLink(oldString string, newString string, num int) (err error)
    func (d *Docx) ReplaceHeader(oldString string, newString string) (err error)
    func (d *Docx) ReplaceFooter(oldString string, newString string) (err error)
    func (d *Docx) WriteToFile(path string) (err error)
    func (d *Docx) Write(ioWriter io.Writer) (err error)
    func (d *Docx) ReplaceImage(oldImage string, newImage string) (err error)
    func (d *Docx) ImagesLen() int