docxr

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 15, 2025 License: AGPL-3.0 Imports: 10 Imported by: 0

README

docxr

Go Report Card GoDoc

docxr is a lightweight Go library for generating .docx Word documents from templates. It leverages Go's built-in text/template package, allowing you to use familiar template syntax directly within your Word documents.

This library is useful for generating reports, invoices, or any other document where the structure is fixed but the content is dynamic.

Rendered Output Example

before after

Features

  • Go Template Syntax: Use the full power of Go's text/template package, including control structures like {{if .Condition}} and {{range .Items}}, directly in your .docx file.
  • Headers and Footers: Template rendering works for headers and footers, in addition to the main document body.
  • Automatic Tag Merging: Intelligently merges template tags that Microsoft Word may split across separate internal XML elements (e.g., <w:t>{{.Na</w:t> and <w:t>me}}</w:t> are automatically combined into {{.Name}} before processing).
  • Flexible I/O: Read templates from files, io.Reader, or byte slices, and write the output to files or any io.Writer.
  • Lightweight: A minimal API with only one external dependency for XML parsing.

Installation

go get github.com/otfot/docxr

Examples

Reading a Document From a File

This example reads a .docx file named template.docx from the disk.

dx := docxr.NewDocx()
err := dx.ReadFromFile("template.docx")
if err != nil {
    log.Fatal(err)
}
Reading a Document From a Byte Slice

This is useful if you have the .docx file's content in memory (e.g., loaded from a database or a web request).

// templateBytes is a []byte containing the docx file content
dx := docxr.NewDocx()
err := dx.ReadFromBytes(templateBytes)
if err != nil {
    log.Fatal(err)
}
Rendering the Template

Once a document is loaded, you can render it with your data. The data can be a struct or a map[string]interface{}. docxr uses Go's text/template engine.

Assume template.docx contains: Hello, {{.Name}}!

data := struct{ Name string }{"World"}
err := dx.Render(data)
if err != nil {
    log.Fatal(err)
}
Writing the Document to a File

After rendering, you can save the result to a new .docx file.

err := dx.WriteToFile("output.docx")
if err != nil {
    log.Fatal(err)
}
Writing the Document to an io.Writer

This allows streaming the output, for example, to an HTTP response.

var buf bytes.Buffer
_, err := dx.WriteTo(&buf)
if err != nil {
    log.Fatal(err)
}
// buf now contains the bytes of the generated .docx file
Complete Example: File to File

This example combines the steps above to perform a complete transformation.

package main

import (
	"log"
	"github.com/otfot/docxr"
)

func main() {
	dx := docxr.NewDocx()

	// Read
	if err := dx.ReadFromFile("template.docx"); err != nil {
		log.Fatalf("Read failed: %v", err)
	}

	// Prepare data
	data := map[string]string{
		"Name": "John Doe",
	}

	// Render
	if err := dx.Render(data); err != nil {
		log.Fatalf("Render failed: %v", err)
	}

	// Write
	if err := dx.WriteToFile("output.docx"); err != nil {
		log.Fatalf("Write failed: %v", err)
	}
}

How It Works

A .docx file is a zip archive containing a collection of XML files and other assets. docxr leverages this structure to provide its templating capabilities:

  1. Unzip: The input .docx file is read as a zip archive.
  2. Find & Parse: The library finds the core XML files that contain visible text (document.xml, header1.xml, etc.) and parses them.
  3. Merge Tags: It scans the parsed XML for text nodes and merges any template tags that have been split by the word processor. This is a crucial step that makes templating reliable.
  4. Render: The text content of each XML file is then processed as a Go text/template, and the provided data is rendered into it.
  5. Re-zip: The final rendered XML is placed back into the archive, and a new .docx file is written to the output stream.

Acknowledgements

This project was inspired by and built upon the ideas from several excellent Go projects:

Documentation

Overview

Package docxr provides functionality for reading, manipulating, and writing Word documents (DOCX).

Package docxr provides functionality for reading, manipulating, and writing Word documents (DOCX).

Package docxr provides functionality for reading, manipulating, and writing Word documents (DOCX).

Index

Constants

View Source
const (
	WordDocument = "word/document.xml"
	WordHeader1  = "word/header1.xml"
	WordHeader2  = "word/header2.xml"
	WordHeader3  = "word/header3.xml"
	WordFooter1  = "word/footer1.xml"
	WordFooter2  = "word/footer2.xml"
)

These constants define the paths to various XML files within a DOCX archive that are supported for templating and rendering by the docxr package.

Variables

This section is empty.

Functions

This section is empty.

Types

type Docx

type Docx struct {
	// contains filtered or unexported fields
}

Docx represents a Word document. It is used to read, manipulate, and write Word documents. It is not thread-safe.

func NewDocx

func NewDocx() *Docx

NewDocx creates and returns a new empty Docx document.

func (*Docx) ReadFrom

func (dx *Docx) ReadFrom(r io.Reader) (int64, error)

ReadFrom reads a DOCX document from the provided io.Reader. It returns the number of bytes read and an error, if any. Note: For non-seekable readers, the entire content is read into memory, which may be inefficient for very large files.

func (*Docx) ReadFromBytes

func (dx *Docx) ReadFromBytes(b []byte) error

ReadFromBytes reads a DOCX document from the provided byte slice. It returns an error if the byte slice cannot be parsed as a DOCX.

func (*Docx) ReadFromFile

func (dx *Docx) ReadFromFile(path string) error

ReadFromFile reads a DOCX document from the specified file path. It returns an error if the file cannot be opened or read.

func (*Docx) Render

func (dx *Docx) Render(data any) error

Render applies the provided data to the document's templates. It processes all supported XML files within the DOCX (e.g., document.xml, headers, footers) and replaces template tags (e.g., `{{.FieldName}}`) with corresponding values from `data`. The `data` parameter can be any type that is compatible with Go's text/template package. It returns an error if templating fails.

func (*Docx) WriteTo

func (dx *Docx) WriteTo(w io.Writer) (_ int64, err error)

WriteTo writes the current state of the DOCX document to the provided io.Writer. This includes both the templated content and original files. It returns the number of bytes written and an error, if any.

func (*Docx) WriteToFile

func (dx *Docx) WriteToFile(path string) error

WriteToFile writes the current state of the DOCX document to the specified file path. It returns an error if the file cannot be created or written to.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL