docxtpl

package module
v0.2.7 Latest Latest
Warning

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

Go to latest
Published: Dec 16, 2025 License: MIT Imports: 35 Imported by: 0

README

go-docxgen

A Go library for generating DOCX documents from templates using Go's text/template syntax.

Go Reference

Features

  • Go Template Syntax - Use familiar {{.Field}}, {{range}}, {{if}} syntax directly in Word documents
  • Programmatic Document Creation - Build documents from scratch with fluent API
  • Handles Fragmented Tags - Automatically merges tags split across XML runs by Word's editing
  • Inline Images - Insert images dynamically with automatic sizing and DPI detection
  • Extensible Functions - Register custom functions or use community libraries like Sprig/Sprout
  • Full Document Support - Headers, footers, footnotes, endnotes, and document properties
  • Document Properties - Get/set title, author, subject, keywords, and more
  • Watermarks - Extract and replace watermark text (supports template syntax)
  • Flexible Data Types - Structs, maps, slices, pointers, nested structures, and graceful nil handling

Installation

go get github.com/abdokhaire/go-docxgen@latest

Quick Start

Create a Word document with template placeholders like {{.Name}}, then:

package main

import (
    "os"
    docxtpl "github.com/abdokhaire/go-docxgen"
)

func main() {
    // Parse the template
    doc, err := docxtpl.ParseFromFilename("template.docx")
    if err != nil {
        panic(err)
    }

    // Render with data
    err = doc.Render(map[string]any{
        "Name":    "John Doe",
        "Company": "Acme Corp",
        "Items":   []string{"Item 1", "Item 2", "Item 3"},
    })
    if err != nil {
        panic(err)
    }

    // Save the result
    doc.SaveToFile("output.docx")
}

Programmatic Document Creation

Create documents without templates using the builder API:

package main

import docxtpl "github.com/abdokhaire/go-docxgen"

func main() {
    // Create a new document
    doc := docxtpl.New()

    // Set document properties
    doc.SetTitle("My Report")
    doc.SetAuthor("Go Developer")

    // Add heading and paragraphs
    doc.AddHeading("Introduction", 1)
    doc.AddParagraph("This document was created programmatically.")

    // Add formatted text
    para := doc.AddParagraph("This is ")
    para.AddText("bold").Bold()
    para.AddText(" and this is ").Then().AddText("italic").Italic()

    // Add a table
    doc.AddHeading("Data Table", 2)
    table := doc.AddTable(3, 3)

    // Header row with styling
    table.SetCell(0, 0, "Name").Bold().Background("CCCCCC")
    table.SetCell(0, 1, "Age").Bold().Background("CCCCCC")
    table.SetCell(0, 2, "City").Bold().Background("CCCCCC")

    // Data rows
    table.SetCell(1, 0, "Alice")
    table.SetCell(1, 1, "30")
    table.SetCell(1, 2, "New York")

    doc.SaveToFile("generated.docx")
}
Paragraph Formatting
doc.AddParagraph("Centered text").Center()
doc.AddParagraph("Right aligned").Right()
doc.AddParagraph("Red bold text").Bold().Color("FF0000")
doc.AddParagraph("Large text").SizePoints(16)
doc.AddParagraph("Custom font").Font("Arial")
doc.AddParagraph("Highlighted").Highlight("yellow")
doc.AddParagraph("With background").Background("FFFF00")
Table Builder
// Create table with custom column widths (in twips: 1 inch = 1440 twips)
table := doc.AddTableWithWidths(5, []int{2880, 1440, 1440}) // 2", 1", 1"

// Access and format cells
cell := table.Cell(0, 0)
cell.SetText("Header")
cell.Bold()
cell.Center()
cell.Background("E0E0E0")

// Format entire row
row := table.Row(0)
row.Justify("center")
Document Properties
// Set properties individually
doc.SetTitle("Annual Report 2025")
doc.SetAuthor("Finance Team")
doc.SetSubject("Q4 Financial Summary")
doc.SetKeywords("finance, report, quarterly")
doc.SetContentStatus("Final")

// Or set all at once
props := doc.GetProperties()
props.Title = "My Document"
props.Creator = "Go Application"
doc.SetProperties(props)

Template Syntax

Use standard Go text/template syntax in your DOCX files:

Syntax Description Example
{{.Field}} Simple field {{.Name}}
{{.Nested.Field}} Nested struct/map {{.Person.Address.City}}
{{if .Condition}}...{{end}} Conditional {{if .Active}}Active{{end}}
{{range .Items}}...{{end}} Loop {{range .Products}}{{.Name}}{{end}}
{{.Field | function}} Pipe to function {{.Name | upper}} (requires registered function)
{{function .Args}} Function call {{greet .Name}} (requires registered function)

Template Functions

This library provides a flexible function system. You can register your own custom functions or use popular community function libraries.

Built-in Function

The library includes one built-in function:

Function Example Description
link {{link "https://example.com" "Click here"}} Create a clickable hyperlink
Registering Custom Functions

Register your own functions before rendering:

doc, _ := docxtpl.ParseFromFilename("template.docx")

// Simple function
doc.RegisterFunction("greet", func(name string) string {
    return "Hello, " + name + "!"
})

// Function with multiple parameters
doc.RegisterFunction("formatPrice", func(price float64, currency string) string {
    return fmt.Sprintf("%s%.2f", currency, price)
})

// Function for calculations
doc.RegisterFunction("multiply", func(a, b float64) float64 {
    return a * b
})

doc.Render(data)

Template usage:

{{greet .Name}}
Price: {{formatPrice .Amount "$"}}
Total: {{multiply .Price .Quantity}}
Using Community Function Libraries

For a rich set of template functions, use community libraries like Sprig or Sprout.

Using Sprig (100+ functions)

Sprig provides 100+ template functions for strings, math, dates, and more.

go get github.com/Masterminds/sprig/v3
import (
    "github.com/Masterminds/sprig/v3"
    docxtpl "github.com/abdokhaire/go-docxgen"
)

func main() {
    doc, _ := docxtpl.ParseFromFilename("template.docx")

    // Register all Sprig functions
    doc.RegisterFuncMap(sprig.FuncMap())

    doc.Render(data)
    doc.SaveToFile("output.docx")
}

Template with Sprig functions:

Name: {{.Name | upper}}
Email: {{.Email | lower}}
Date: {{now | date "2006-01-02"}}
Total: {{.Items | len}} items
Status: {{.IsActive | ternary "Active" "Inactive"}}
Using Sprout (Modern Sprig Alternative)

Sprout is a modern, modular alternative to Sprig with better performance.

go get github.com/go-sprout/sprout
import (
    "github.com/go-sprout/sprout"
    docxtpl "github.com/abdokhaire/go-docxgen"
)

func main() {
    doc, _ := docxtpl.ParseFromFilename("template.docx")

    // Register Sprout functions
    handler := sprout.New()
    doc.RegisterFuncMap(handler.Build())

    doc.Render(data)
    doc.SaveToFile("output.docx")
}
Common Functions (via Sprig/Sprout)

Once you register Sprig or Sprout, these functions become available:

Category Functions
Strings upper, lower, title, trim, replace, contains, hasPrefix, hasSuffix
Math add, sub, mul, div, mod, max, min, ceil, floor, round
Dates now, date, dateModify, toDate, dateInZone
Lists list, first, last, append, prepend, concat, join
Logic eq, ne, lt, le, gt, ge, and, or, not, default, ternary
Encoding b64enc, b64dec, toJson, fromJson

See Sprig documentation or Sprout documentation for the complete function reference.

Inline Images

Insert images dynamically using file paths or the InlineImage type:

// Using file path (auto-detected)
data := map[string]any{
    "Logo": "/path/to/logo.png",
}

// Using InlineImage for more control
logo := docxtpl.CreateInlineImage("/path/to/logo.png")
logo.Resize(200, 100) // width, height in pixels

data := map[string]any{
    "Logo": logo,
}

Supported formats: JPEG (.jpg, .jpeg) and PNG (.png)

Working with Document Parts

Get All Placeholders
placeholders := doc.GetPlaceholders()
// Returns: []string{"Name", "Company", "Items", ...}
Watermarks
// Get watermarks from headers
watermarks := doc.GetWatermarks()

// Replace watermark text (supports template syntax)
doc.ReplaceWatermark("DRAFT", "FINAL")

// Or use template syntax in the watermark itself: {{.Status}}
doc.Render(map[string]any{"Status": "APPROVED"})

The Fragmentation Problem

Word processors often split text across multiple XML elements based on editing history, spell-check, or formatting. A placeholder like {{.FirstName}} might appear in the XML as:

<w:r><w:t>{{.First</w:t></w:r>
<w:r><w:t>Name}}</w:t></w:r>

This library automatically detects and merges these fragmented tags before template processing, ensuring reliable placeholder replacement.

API Reference

Parsing
  • Parse(reader io.ReaderAt, size int64) - Parse from reader
  • ParseFromFilename(filename string) - Parse from file path
  • ParseFromBytes(data []byte) - Parse from byte slice
Rendering
  • Render(data any) - Replace placeholders with data
  • RegisterFunction(name string, fn any) - Add custom function
Saving
  • Save(writer io.Writer) - Save to writer
  • SaveToFile(filename string) - Save to file path
Inspection
  • GetPlaceholders() - Get all unique placeholders
  • GetWatermarks() - Get watermark texts
  • ReplaceWatermark(old, new string) - Replace watermark text

Examples

Basic Document with Struct Data

Template (template.docx):

Project: {{.ProjectNumber}}
Client: {{.Client}}
Status: {{.Status}}

Code:

package main

import docxtpl "github.com/abdokhaire/go-docxgen"

func main() {
    doc, _ := docxtpl.ParseFromFilename("template.docx")

    data := struct {
        ProjectNumber string
        Client        string
        Status        string
    }{
        ProjectNumber: "PRJ-2025-001",
        Client:        "Acme Corporation",
        Status:        "In Progress",
    }

    doc.Render(data)
    doc.SaveToFile("output.docx")
}
Tables with Loops

Template (invoice.docx):

Invoice #{{.InvoiceNumber}}
Date: {{.Date}}

| Item | Quantity | Price |
|------|----------|-------|
{{range .Items}}| | | |
|------|----------|-------|
{{.Name}} | {{.Qty}} | {{.PriceFormatted}} |
|------|----------|-------|
{{end}}
|------|----------|-------|

Total: {{.TotalFormatted}}

Code:

type Item struct {
    Name           string
    Qty            int
    Price          float64
    PriceFormatted string
}

data := map[string]any{
    "InvoiceNumber": "INV-001",
    "Date":          "December 5, 2025",
    "Items": []Item{
        {Name: "Widget A", Qty: 10, Price: 29.99, PriceFormatted: "$29.99"},
        {Name: "Widget B", Qty: 5, Price: 49.99, PriceFormatted: "$49.99"},
        {Name: "Service Fee", Qty: 1, Price: 100.00, PriceFormatted: "$100.00"},
    },
    "TotalFormatted": "$549.85",
}

doc.Render(data)
Conditionals

Template:

{{if .IsApproved}}
✓ This document has been approved by {{.ApprovedBy}}
{{else}}
⏳ Pending approval
{{end}}

{{if gt .Amount 1000}}
⚠️ Large transaction - requires manager approval
{{end}}

Code:

data := map[string]any{
    "IsApproved": true,
    "ApprovedBy": "John Smith",
    "Amount":     1500.00,
}
Images in Documents

Template:

Company Logo: {{.Logo}}

Team Members:
{{range .Team}}
  Name: {{.Name}}
  Photo: {{.Photo}}
{{end}}

Code:

// Method 1: Auto-detect from file path
data := map[string]any{
    "Logo": "/path/to/logo.png",
    "Team": []map[string]any{
        {"Name": "Alice", "Photo": "/path/to/alice.jpg"},
        {"Name": "Bob", "Photo": "/path/to/bob.jpg"},
    },
}

// Method 2: Using InlineImage for size control
logo, _ := docxtpl.CreateInlineImage("/path/to/logo.png")
logo.Resize(150, 50) // width x height in pixels

profile, _ := docxtpl.CreateInlineImage("/path/to/profile.jpg")
profile.Resize(100, 100)

data := map[string]any{
    "Logo":    logo,
    "Profile": profile,
}
Using Sprig/Sprout Functions

This example requires registering Sprig or Sprout functions first (see Template Functions).

Template:

Name: {{.Name | upper}}
Email: {{.Email | lower}}
Title: {{.Title | title}}

Joined: {{.JoinDate | date "January 2, 2006"}}
Salary: ${{.Salary | printf "%.2f"}}
Bonus: {{.BonusRate | mul 100 | printf "%.1f"}}%

Status: {{ternary "Active" "Inactive" .IsActive}}
Department: {{default "Unassigned" .Department}}

Tags: {{.Tags | join ", "}}

Code:

import (
    "time"
    "github.com/Masterminds/sprig/v3"
    docxtpl "github.com/abdokhaire/go-docxgen"
)

func main() {
    doc, _ := docxtpl.ParseFromFilename("template.docx")
    doc.RegisterFuncMap(sprig.FuncMap()) // Register Sprig functions

    data := map[string]any{
        "Name":       "john doe",
        "Email":      "JOHN@EXAMPLE.COM",
        "Title":      "senior developer",
        "JoinDate":   time.Now(),
        "Salary":     85000.00,
        "BonusRate":  0.15,
        "IsActive":   true,
        "Department": "", // Will show "Unassigned"
        "Tags":       []string{"golang", "backend", "api"},
    }

    doc.Render(data)
    doc.SaveToFile("output.docx")
}
Custom Functions

Template:

{{greet .Name}}
Order Total: {{calculateTotal .Items}}

Code:

doc, _ := docxtpl.ParseFromFilename("template.docx")

// Register custom functions before rendering
doc.RegisterFunction("greet", func(name string) string {
    return "Welcome, " + name + "!"
})

doc.RegisterFunction("calculateTotal", func(items []map[string]any) string {
    total := 0.0
    for _, item := range items {
        price := item["price"].(float64)
        qty := item["qty"].(int)
        total += price * float64(qty)
    }
    return fmt.Sprintf("$%.2f", total)
})

data := map[string]any{
    "Name": "Alice",
    "Items": []map[string]any{
        {"name": "Item 1", "price": 10.0, "qty": 2},
        {"name": "Item 2", "price": 25.0, "qty": 1},
    },
}

doc.Render(data)
Multi-line Text

Newlines in your data are automatically converted to line breaks:

data := map[string]any{
    "Address": "123 Main Street\nSuite 456\nNew York, NY 10001",
    "Notes":   "Line 1\nLine 2\nLine 3",
}
Loading from Different Sources
// From file path
doc, _ := docxtpl.ParseFromFilename("template.docx")

// From bytes (useful for embedded templates or HTTP responses)
templateBytes, _ := os.ReadFile("template.docx")
doc, _ := docxtpl.ParseFromBytes(templateBytes)

// From io.ReaderAt (useful for http.Response.Body after reading)
file, _ := os.Open("template.docx")
stat, _ := file.Stat()
doc, _ := docxtpl.Parse(file, stat.Size())
Saving to Different Destinations
// To file path
doc.SaveToFile("output.docx")

// To io.Writer (useful for HTTP responses)
func handleDownload(w http.ResponseWriter, r *http.Request) {
    doc, _ := docxtpl.ParseFromFilename("template.docx")
    doc.Render(data)

    w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
    w.Header().Set("Content-Disposition", "attachment; filename=document.docx")
    doc.Save(w)
}
Working with JSON Data
import "encoding/json"

// Load JSON data
jsonData := `{
    "name": "John Doe",
    "company": "Acme Corp",
    "items": [
        {"product": "Widget", "price": 29.99},
        {"product": "Gadget", "price": 49.99}
    ]
}`

var data map[string]any
json.Unmarshal([]byte(jsonData), &data)

doc, _ := docxtpl.ParseFromFilename("template.docx")
doc.Render(data)
doc.SaveToFile("output.docx")
Inspecting Template Placeholders
doc, _ := docxtpl.ParseFromFilename("template.docx")

// Get all placeholders to know what data is needed
placeholders, _ := doc.GetPlaceholders()
fmt.Println("Required fields:", placeholders)
// Output: [{{.Name}} {{.Email}} {{.Items}} ...]

// Useful for validation or building dynamic forms
Complete Example: Generate Report
package main

import (
    "time"
    docxtpl "github.com/abdokhaire/go-docxgen"
)

type Employee struct {
    Name       string
    Department string
    Salary     float64
    Photo      string
}

type Report struct {
    Title       string
    GeneratedAt time.Time
    Author      string
    Employees   []Employee
    TotalBudget float64
    IsFinalized bool
}

func main() {
    doc, err := docxtpl.ParseFromFilename("report_template.docx")
    if err != nil {
        panic(err)
    }

    report := Report{
        Title:       "Q4 2025 Staff Report",
        GeneratedAt: time.Now(),
        Author:      "HR Department",
        Employees: []Employee{
            {Name: "Alice Johnson", Department: "Engineering", Salary: 95000, Photo: "photos/alice.jpg"},
            {Name: "Bob Smith", Department: "Marketing", Salary: 75000, Photo: "photos/bob.jpg"},
            {Name: "Carol White", Department: "Engineering", Salary: 105000, Photo: "photos/carol.jpg"},
        },
        TotalBudget: 275000,
        IsFinalized: true,
    }

    if err := doc.Render(report); err != nil {
        panic(err)
    }

    if err := doc.SaveToFile("Q4_2025_Staff_Report.docx"); err != nil {
        panic(err)
    }
}

Corresponding Template (report_template.docx):

Note: This template uses Sprig functions. Register them with doc.RegisterFuncMap(sprig.FuncMap())

{{.Title | upper}}
Generated: {{.GeneratedAt | date "January 2, 2006"}}
Author: {{.Author}}

{{if .IsFinalized}}✓ FINALIZED{{else}}DRAFT{{end}}

EMPLOYEE ROSTER
{{range .Employees}}
━━━━━━━━━━━━━━━━━━━━
Name: {{.Name}}
Department: {{.Department}}
Salary: ${{.Salary | printf "%.2f"}}
{{.Photo}}
{{end}}

Total Budget: ${{.TotalBudget | printf "%.2f"}}
Employee Count: {{len .Employees}}

Example template files are also available in the test/testdata/templates directory.

Acknowledgements

License

MIT License - see LICENSE for details.

Documentation

Overview

Package docxtpl provides a library for generating DOCX documents from templates using Go's text/template syntax.

This package wraps the go-docx library (github.com/fumiama/go-docx) and adds template rendering capabilities, making it easy to create dynamic Word documents.

Key Features

  • Go template syntax ({{.Field}}, {{range}}, {{if}}) in Word documents
  • Automatic handling of fragmented XML tags (common in Word's editing)
  • Inline image insertion with automatic sizing and DPI detection
  • 60+ built-in template functions for text, math, dates, and more
  • Support for headers, footers, footnotes, endnotes, and watermarks
  • Custom function registration

Basic Usage

Create a Word document with template placeholders like {{.Name}}, then:

doc, err := docxtpl.ParseFromFilename("template.docx")
if err != nil {
    log.Fatal(err)
}

data := map[string]any{
    "Name":    "John Doe",
    "Company": "Acme Corp",
}

if err := doc.Render(data); err != nil {
    log.Fatal(err)
}

if err := doc.SaveToFile("output.docx"); err != nil {
    log.Fatal(err)
}

Template Syntax

The package supports standard Go text/template syntax:

  • Simple fields: {{.Name}}
  • Nested fields: {{.Person.Address.City}}
  • Conditionals: {{if .Active}}...{{end}}
  • Loops: {{range .Items}}{{.Name}}{{end}}
  • Functions: {{.Name | upper}} or {{formatMoney .Price "$"}}

Built-in Functions

The package includes many built-in functions:

Text: upper, lower, title, bold, italic, underline, color, highlight Numbers: formatNumber, formatMoney, formatPercent, add, sub, mul, div Dates: now, formatDate, parseDate, addDays, addMonths, addYears Collections: len, first, last, join, contains, index, slice Logic: eq, ne, lt, le, gt, ge, and, or, not Utilities: default, ternary, trim, replace, truncate, pluralize

Inline Images

Images can be inserted using file paths (auto-detected) or InlineImage:

// Auto-detect from file path
data := map[string]any{
    "Logo": "/path/to/logo.png",
}

// Or use InlineImage for size control
logo, _ := docxtpl.CreateInlineImage("/path/to/logo.png")
logo.Resize(200, 100)
data := map[string]any{
    "Logo": logo,
}

Custom Functions

Register custom template functions before rendering:

doc.RegisterFunction("greet", func(name string) string {
    return "Hello, " + name + "!"
})

Then use in template: {{greet .Name}}

Data Types

The Render method accepts structs or maps with various field types:

  • Primitives: string, int, float64, bool, etc.
  • Structs: regular and nested structs
  • Pointers: automatically dereferenced
  • Slices: []string, []int, []Struct, []*Struct
  • Maps: map[string]any, map[string]string, etc.

Index

Constants

View Source
const (
	EMUS_PER_INCH = 914400
	DEFAULT_DPI   = 72
)
View Source
const (
	PageWidthA4      = 8.27
	PageHeightA4     = 11.69
	PageWidthA3      = 11.69
	PageHeightA3     = 16.54
	PageWidthLetter  = 8.5
	PageHeightLetter = 11.0
	PageWidthLegal   = 8.5
	PageHeightLegal  = 14.0
)

Custom page size constants (in inches)

Variables

This section is empty.

Functions

func BatchProcess added in v0.1.1

func BatchProcess(docs []*DocxTmpl, fn func(*DocxTmpl) error) error

BatchProcess applies a function to each document in a list.

err := docxtpl.BatchProcess(docs, func(doc *DocxTmpl) error {
    doc.ReplaceText("COMPANY", "Acme Corp")
    return nil
})

func CompareMetadata added in v0.1.1

func CompareMetadata(meta1, meta2 *DocumentMetadata) map[string][2]string

CompareMetadata compares document metadata

func CompareStats added in v0.1.1

func CompareStats(stats1, stats2 *DocumentStats) map[string]int

CompareStats compares document statistics

statsDiff := docxtpl.CompareStats(doc1.GetStats(), doc2.GetStats())

func ProcessDirectory added in v0.1.1

func ProcessDirectory(inputDir, outputDir string, processor func(*DocxTmpl) error) error

ProcessDirectory processes all .docx files in a directory.

err := docxtpl.ProcessDirectory("input/", "output/", func(doc *DocxTmpl) error {
    return doc.Render(data)
})

func ReplaceInAll added in v0.1.1

func ReplaceInAll(docs []*DocxTmpl, oldText, newText string)

ReplaceInAll replaces text in all provided documents.

docxtpl.ReplaceInAll(docs, "OLD", "NEW")

func SaveAllToDirectory added in v0.1.1

func SaveAllToDirectory(docs []*DocxTmpl, dirPath string, names []string) error

SaveAllToDirectory saves all documents to a directory with specified names.

err := docxtpl.SaveAllToDirectory(docs, "output/", []string{"doc1.docx", "doc2.docx"})

Types

type ArchiveInfo added in v0.1.1

type ArchiveInfo struct {
	TotalFiles   int      // Total number of files in archive
	XMLFiles     int      // Number of XML files
	MediaFiles   int      // Number of media files
	TotalSize    int64    // Total uncompressed size
	FileList     []string // List of all file paths
	HasComments  bool     // Whether the document has comments.xml
	HasSettings  bool     // Whether the document has settings.xml
	HasFootnotes bool     // Whether the document has footnotes.xml
	HasEndnotes  bool     // Whether the document has endnotes.xml
}

ArchiveInfo returns information about the DOCX archive.

type Bookmark added in v0.1.1

type Bookmark struct {
	ID   int    // Bookmark ID
	Name string // Bookmark name
	Text string // Text content at the bookmark location
}

Bookmark represents a bookmark in the document

type Comment added in v0.1.1

type Comment struct {
	ID        int       // Comment ID
	Author    string    // Comment author
	Initials  string    // Author initials
	Date      time.Time // When the comment was created
	Text      string    // Comment text content
	ParentID  int       // Parent comment ID for replies (-1 if not a reply)
	Paragraph int       // Paragraph index where comment is attached
}

Comment represents a comment in the document

type DiffItem added in v0.1.1

type DiffItem struct {
	Type     DiffType // Type of change
	Location string   // Where the change occurred (paragraph index, table location, etc.)
	OldValue string   // Original value (empty for additions)
	NewValue string   // New value (empty for removals)
}

DiffItem represents a single difference between two documents

type DiffSummary added in v0.1.1

type DiffSummary struct {
	TotalChanges       int
	AddedParagraphs    int
	RemovedParagraphs  int
	ModifiedParagraphs int
	AddedTables        int
	RemovedTables      int
}

DiffSummary contains summary statistics of differences

type DiffType added in v0.1.1

type DiffType string

DiffType represents the type of difference

const (
	DiffTypeAdded    DiffType = "added"
	DiffTypeRemoved  DiffType = "removed"
	DiffTypeModified DiffType = "modified"
)

type DocumentDiff added in v0.1.1

type DocumentDiff struct {
	Added    []DiffItem // Content added in the new document
	Removed  []DiffItem // Content removed from the original
	Modified []DiffItem // Content that was modified
	Summary  DiffSummary
}

DocumentDiff represents the differences between two documents

func CompareDocuments added in v0.1.1

func CompareDocuments(doc1, doc2 *DocxTmpl) *DocumentDiff

CompareDocuments compares two documents and returns their differences.

doc1, _ := docxtpl.ParseFromFilename("version1.docx")
doc2, _ := docxtpl.ParseFromFilename("version2.docx")
diff := docxtpl.CompareDocuments(doc1, doc2)

func (*DocumentDiff) GetChanges added in v0.1.1

func (d *DocumentDiff) GetChanges() []DiffItem

GetChanges returns all changes as a flat list

func (*DocumentDiff) HasChanges added in v0.1.1

func (d *DocumentDiff) HasChanges() bool

HasChanges returns true if there are any differences

func (*DocumentDiff) String added in v0.1.1

func (d *DocumentDiff) String() string

String returns a human-readable summary of changes

type DocumentMetadata added in v0.1.1

type DocumentMetadata struct {
	Title          string
	Subject        string
	Creator        string // Author
	Keywords       string
	Description    string
	LastModifiedBy string
	Revision       string
	Created        time.Time
	Modified       time.Time
	Category       string
	ContentStatus  string
	Language       string
}

DocumentMetadata contains document properties.

type DocumentProperties added in v0.1.1

type DocumentProperties struct {
	Title          string
	Subject        string
	Creator        string // Author
	Keywords       string
	Description    string
	LastModifiedBy string
	Revision       string
	Created        time.Time
	Modified       time.Time
	Category       string
	ContentStatus  string // e.g., "Draft", "Final"
}

DocumentProperties contains the core document metadata.

type DocumentStats added in v0.1.1

type DocumentStats struct {
	ParagraphCount int
	TableCount     int
	WordCount      int
	CharCount      int // without spaces
	CharCountSpace int // with spaces
	LineCount      int
	ImageCount     int
	LinkCount      int
}

DocumentStats contains document statistics.

type DocxTmpl

type DocxTmpl struct {
	*docx.Docx
	// contains filtered or unexported fields
}

func BatchRender added in v0.1.1

func BatchRender(templates []*DocxTmpl, dataList []any) ([]*DocxTmpl, error)

BatchRender renders multiple templates with corresponding data.

docs, err := docxtpl.BatchRender(templates, dataList)

func LoadAllFromDirectory added in v0.1.1

func LoadAllFromDirectory(dirPath string) ([]*DocxTmpl, error)

LoadAllFromDirectory loads all .docx files from a directory.

docs, err := docxtpl.LoadAllFromDirectory("templates/")

func MergeDocuments added in v0.1.1

func MergeDocuments(docs ...*DocxTmpl) (*DocxTmpl, error)

MergeDocuments combines multiple documents into one. Documents are appended in order with page breaks between them.

merged := docxtpl.MergeDocuments(doc1, doc2, doc3)

func New added in v0.1.1

func New() *DocxTmpl

New creates a new empty document from scratch. Use this when you want to build a document programmatically without a template.

doc := docxtpl.New()
doc.AddHeading("My Document", 1)
doc.AddParagraph("Hello, World!")
doc.SaveToFile("output.docx")

func NewWithOptions added in v0.1.1

func NewWithOptions(pageSize ...PageSize) *DocxTmpl

NewWithOptions creates a new document with optional configuration.

doc := docxtpl.NewWithOptions(docxtpl.PageSizeA4)

func PackFromDirectory added in v0.1.1

func PackFromDirectory(dirPath string) (*DocxTmpl, error)

PackFromDirectory creates a DOCX file from an unpacked directory. This is the reverse of UnpackToDirectory.

doc, err := docxtpl.PackFromDirectory("/tmp/unpacked")

func Parse

func Parse(reader io.ReaderAt, size int64) (*DocxTmpl, error)

Parse the document from a reader and store it in memory. You can it invoke from a file.

reader, err := os.Open("path_to_doc.docx")
if err != nil {
	panic(err)
}
fileinfo, err := reader.Stat()
if err != nil {
	panic(err)
}
size := fileinfo.Size()
doc, err := docxtpl.Parse(reader, int64(size))

func ParseFromBytes

func ParseFromBytes(data []byte) (*DocxTmpl, error)

Parse the document from a byte slice and store it in memory. Useful for documents loaded from HTTP responses or other in-memory sources.

data, err := io.ReadAll(resp.Body)
if err != nil {
	panic(err)
}
doc, err := docxtpl.ParseFromBytes(data)

func ParseFromFilename

func ParseFromFilename(filename string) (*DocxTmpl, error)

Parse the document from a filename and store it in memory.

doc, err := docxtpl.ParseFromFilename("path_to_doc.docx")

func (*DocxTmpl) AcceptAllChanges added in v0.1.1

func (d *DocxTmpl) AcceptAllChanges()

AcceptAllChanges accepts all tracked changes, making insertions permanent and removing deleted text. Note: This modifies the processable files (headers, footers, etc.). Document body changes require re-parsing after save.

doc.AcceptAllChanges()

func (*DocxTmpl) AddBulletList added in v0.1.1

func (d *DocxTmpl) AddBulletList(items []string) *List

AddBulletList adds a bullet list to the document. Each string in items becomes a bullet point.

doc.AddBulletList([]string{"First item", "Second item", "Third item"})

func (*DocxTmpl) AddChecklist added in v0.1.1

func (d *DocxTmpl) AddChecklist(items map[string]bool) []*Paragraph

AddChecklist adds a checklist to the document. items is a map of text to checked status.

doc.AddChecklist(map[string]bool{
    "Task 1": true,
    "Task 2": false,
    "Task 3": false,
})

func (*DocxTmpl) AddChecklistItem added in v0.1.1

func (d *DocxTmpl) AddChecklistItem(text string, checked bool) *Paragraph

AddChecklistItem adds a checkbox item to the document. checked determines if the checkbox appears checked.

doc.AddChecklistItem("Complete task", true)
doc.AddChecklistItem("Pending task", false)

func (*DocxTmpl) AddEmptyParagraph added in v0.1.1

func (d *DocxTmpl) AddEmptyParagraph() *Paragraph

AddEmptyParagraph adds an empty paragraph to the document. Useful for adding spacing between elements.

func (*DocxTmpl) AddHeading added in v0.1.1

func (d *DocxTmpl) AddHeading(text string, level int) *Paragraph

AddHeading adds a heading with the specified level (0-9). Level 0 is the document title, level 1 is Heading 1, etc.

doc.AddHeading("Chapter 1", 1)
doc.AddHeading("Section 1.1", 2)

func (*DocxTmpl) AddNestedList added in v0.1.1

func (d *DocxTmpl) AddNestedList(listType ListType, items []ListItem) *List

AddNestedList adds a nested list with multiple levels. Use ListItem.Level to control indentation (0-8). Use ListItem.Children for nested items.

doc.AddNestedList(ListTypeBullet, []ListItem{
    {Text: "Item 1", Children: []ListItem{
        {Text: "Sub-item 1.1"},
        {Text: "Sub-item 1.2"},
    }},
    {Text: "Item 2"},
})

func (*DocxTmpl) AddNumberedList added in v0.1.1

func (d *DocxTmpl) AddNumberedList(items []string) *List

AddNumberedList adds a numbered list to the document. Each string in items becomes a numbered item (1, 2, 3...).

doc.AddNumberedList([]string{"First step", "Second step", "Third step"})

func (*DocxTmpl) AddOrderedChecklist added in v0.1.1

func (d *DocxTmpl) AddOrderedChecklist(items []struct {
	Text    string
	Checked bool
}) []*Paragraph

AddOrderedChecklist adds a checklist with preserved order.

doc.AddOrderedChecklist([]struct{Text string; Checked bool}{
    {"Task 1", true},
    {"Task 2", false},
})

func (*DocxTmpl) AddPageBreak added in v0.1.1

func (d *DocxTmpl) AddPageBreak()

AddPageBreak inserts a page break at the current position.

func (*DocxTmpl) AddParagraph added in v0.1.1

func (d *DocxTmpl) AddParagraph(text string) *Paragraph

AddParagraph adds a new paragraph with the given text to the document. Returns a Paragraph wrapper for further formatting.

para := doc.AddParagraph("Hello, World!")
para.Bold().Color("FF0000")

func (*DocxTmpl) AddSection added in v0.1.1

func (d *DocxTmpl) AddSection() *DocxTmpl

AddSection adds a new section with a page break. This is a convenience method for common use cases.

doc.AddSection()

func (*DocxTmpl) AddSectionBreak added in v0.1.1

func (d *DocxTmpl) AddSectionBreak(breakType SectionBreakType) *DocxTmpl

AddSectionBreak adds a visual section break to the document. For SectionBreakNextPage, this creates a page break. For other types, it creates appropriate spacing.

doc.AddSectionBreak(SectionBreakNextPage)

func (*DocxTmpl) AddTable added in v0.1.1

func (d *DocxTmpl) AddTable(rows, cols int) *Table

AddTable creates a new table with the specified number of rows and columns. Returns a Table wrapper for populating and formatting.

table := doc.AddTable(3, 4) // 3 rows, 4 columns
table.SetCell(0, 0, "Header 1")

func (*DocxTmpl) AddTableFromCSV added in v0.1.1

func (d *DocxTmpl) AddTableFromCSV(csvStr string) (*Table, error)

AddTableFromCSV creates a table from CSV data.

doc.AddTableFromCSV("Name,Age\nJohn,30\nJane,25")

func (*DocxTmpl) AddTableFromJSON added in v0.1.1

func (d *DocxTmpl) AddTableFromJSON(jsonStr string, headers ...string) (*Table, error)

AddTableFromJSON creates a table from JSON data. Accepts either [][]string or []map[string]string format.

doc.AddTableFromJSON(`[["A","B"],["1","2"]]`)
doc.AddTableFromJSON(`[{"Name":"John","Age":"30"}]`)

func (*DocxTmpl) AddTableFromSlice added in v0.1.1

func (d *DocxTmpl) AddTableFromSlice(data [][]string) *Table

AddTableFromSlice creates a table from a 2D string slice.

doc.AddTableFromSlice([][]string{{"A","B"},{"1","2"}})

func (*DocxTmpl) AddTableWithBorders added in v0.1.1

func (d *DocxTmpl) AddTableWithBorders(rows, cols int, colors TableBorderColors) *Table

AddTableWithBorders creates a table with custom border colors. Use TableBorderColors to specify colors for each border type.

doc.AddTableWithBorders(3, 4, TableBorderColors{
    Top: "FF0000", Bottom: "FF0000",
    Left: "0000FF", Right: "0000FF",
    InsideH: "00FF00", InsideV: "00FF00",
})

func (*DocxTmpl) AddTableWithHeaders added in v0.1.1

func (d *DocxTmpl) AddTableWithHeaders(headers []string, data [][]string) *Table

AddTableWithHeaders creates a table with a header row. The first row is automatically bolded and centered.

doc.AddTableWithHeaders([]string{"Name", "Age", "City"}, [][]string{
    {"John", "30", "NYC"},
    {"Jane", "25", "LA"},
})

func (*DocxTmpl) AddTableWithWidths added in v0.1.1

func (d *DocxTmpl) AddTableWithWidths(rows int, colWidths []int) *Table

AddTableWithWidths creates a table with custom column widths (in twips). 1 inch = 1440 twips, 1 cm = 567 twips.

doc.AddTableWithWidths(3, []int{2880, 1440, 1440}) // 3 rows, columns: 2", 1", 1"

func (*DocxTmpl) AllowOnlyComments added in v0.1.1

func (d *DocxTmpl) AllowOnlyComments() error

AllowOnlyComments sets protection to allow only comments.

err := doc.AllowOnlyComments()

func (*DocxTmpl) AllowOnlyFormFilling added in v0.1.1

func (d *DocxTmpl) AllowOnlyFormFilling() error

AllowOnlyFormFilling sets protection to allow only form filling.

err := doc.AllowOnlyFormFilling()

func (*DocxTmpl) AllowOnlyTrackedChanges added in v0.1.1

func (d *DocxTmpl) AllowOnlyTrackedChanges() error

AllowOnlyTrackedChanges sets protection to allow only tracked changes.

err := doc.AllowOnlyTrackedChanges()

func (*DocxTmpl) AppendDocument added in v0.1.1

func (d *DocxTmpl) AppendDocument(other *DocxTmpl)

AppendDocument appends all contents from another document to this document. This is useful for merging multiple documents into one.

doc1, _ := docxtpl.ParseFromFilename("chapter1.docx")
doc2, _ := docxtpl.ParseFromFilename("chapter2.docx")
doc1.AppendDocument(doc2)
doc1.SaveToFile("combined.docx")

func (*DocxTmpl) BookmarksSummary added in v0.1.1

func (d *DocxTmpl) BookmarksSummary() string

BookmarksSummary returns a text summary of all bookmarks.

summary := doc.BookmarksSummary()

func (*DocxTmpl) CleanDocument added in v0.1.1

func (d *DocxTmpl) CleanDocument()

CleanDocument performs common cleanup operations: - Merges runs with same formatting - Removes empty picture references This is useful before saving to reduce file size.

func (*DocxTmpl) Clone added in v0.1.1

func (d *DocxTmpl) Clone() (*DocxTmpl, error)

Clone creates a deep copy of the document. The cloned document can be modified independently.

clone := doc.Clone()
clone.Render(differentData)
clone.SaveToFile("copy.docx")

func (*DocxTmpl) CommentsSummary added in v0.1.1

func (d *DocxTmpl) CommentsSummary() string

CommentsSummary returns a text summary of all comments.

summary := doc.CommentsSummary()
fmt.Println(summary)

func (*DocxTmpl) CountBookmarks added in v0.1.1

func (d *DocxTmpl) CountBookmarks() int

CountBookmarks returns the total number of bookmarks in the document.

count := doc.CountBookmarks()

func (*DocxTmpl) CountComments added in v0.1.1

func (d *DocxTmpl) CountComments() int

CountComments returns the total number of comments in the document.

count := doc.CountComments()

func (*DocxTmpl) CountParagraphs added in v0.1.1

func (d *DocxTmpl) CountParagraphs() int

CountParagraphs returns the number of paragraphs in the document.

func (*DocxTmpl) CountTables added in v0.1.1

func (d *DocxTmpl) CountTables() int

CountTables returns the number of tables in the document.

func (*DocxTmpl) CountTrackedChanges added in v0.1.1

func (d *DocxTmpl) CountTrackedChanges() (insertions, deletions int)

CountTrackedChanges returns the count of tracked changes by type.

ins, del := doc.CountTrackedChanges()

func (*DocxTmpl) DeleteAllComments added in v0.1.1

func (d *DocxTmpl) DeleteAllComments()

DeleteAllComments removes all comments from the document. This modifies the comments.xml file.

doc.DeleteAllComments()

func (*DocxTmpl) DiffWith added in v0.1.1

func (d *DocxTmpl) DiffWith(other *DocxTmpl) *DocumentDiff

DiffWith compares this document with another and returns differences.

diff := doc1.DiffWith(doc2)

func (*DocxTmpl) DisableTrackChanges added in v0.1.1

func (d *DocxTmpl) DisableTrackChanges() error

DisableTrackChanges disables track changes mode in document settings.

doc.DisableTrackChanges()

func (*DocxTmpl) DropAllDrawings added in v0.1.1

func (d *DocxTmpl) DropAllDrawings()

DropAllDrawings removes all shapes, canvases, and groups from the entire document. This is useful for extracting just the text content.

func (*DocxTmpl) DropCanvas added in v0.1.1

func (d *DocxTmpl) DropCanvas()

DropCanvas removes all canvas elements from the entire document.

func (*DocxTmpl) DropEmptyPictures added in v0.1.1

func (d *DocxTmpl) DropEmptyPictures()

DropEmptyPictures removes all nil/empty picture references from the document.

func (*DocxTmpl) DropGroups added in v0.1.1

func (d *DocxTmpl) DropGroups()

DropGroups removes all group elements from the entire document.

func (*DocxTmpl) DropShapes added in v0.1.1

func (d *DocxTmpl) DropShapes()

DropShapes removes all shapes from the entire document.

func (*DocxTmpl) EnableTrackChanges added in v0.1.1

func (d *DocxTmpl) EnableTrackChanges() error

EnableTrackChanges enables track changes mode in document settings. Note: This modifies settings.xml to enable revision tracking. Requires settings.xml to be in processable files.

doc.EnableTrackChanges()

func (*DocxTmpl) EstimatePageCount added in v0.1.1

func (d *DocxTmpl) EstimatePageCount() int

EstimatePageCount estimates the number of pages in the document. This is a rough estimate based on paragraph count and assumes: - Single spacing, 12pt font - About 50 lines per page for Letter size - Tables count as 3 paragraphs

pages := doc.EstimatePageCount()

func (*DocxTmpl) FindText added in v0.1.1

func (d *DocxTmpl) FindText(text string) []string

FindText returns all paragraphs containing the specified text.

func (*DocxTmpl) FindTextMatch added in v0.1.1

func (d *DocxTmpl) FindTextMatch(pattern string) []string

FindTextMatch returns all paragraphs matching the regex pattern.

func (*DocxTmpl) GenerateSampleData added in v0.1.1

func (d *DocxTmpl) GenerateSampleData() map[string]interface{}

GenerateSampleData generates sample data matching the template placeholders. This is useful for testing and documentation.

sample := doc.GenerateSampleData()
func (d *DocxTmpl) GetAllHyperlinks() []HyperlinkInfo

GetAllHyperlinks returns all hyperlinks in the document.

links := doc.GetAllHyperlinks()
for _, link := range links {
    fmt.Printf("%s -> %s\n", link.Text, link.URL)
}

func (*DocxTmpl) GetAllMedia added in v0.1.1

func (d *DocxTmpl) GetAllMedia() []*Media

GetAllMedia returns all embedded media files in the document.

mediaFiles := doc.GetAllMedia()
for _, m := range mediaFiles {
    os.WriteFile(m.Name, m.Data, 0644)
}

func (*DocxTmpl) GetAllStyles added in v0.1.1

func (d *DocxTmpl) GetAllStyles() []string

GetAllStyles returns all paragraph styles used in the document.

styles := doc.GetAllStyles()
// Returns: ["Normal", "Heading1", "Heading2", ...]

func (*DocxTmpl) GetArchiveInfo added in v0.1.1

func (d *DocxTmpl) GetArchiveInfo() *ArchiveInfo

GetArchiveInfo returns information about the DOCX archive structure.

info := doc.GetArchiveInfo()
fmt.Printf("Total files: %d\n", info.TotalFiles)

func (*DocxTmpl) GetBookmarkByName added in v0.1.1

func (d *DocxTmpl) GetBookmarkByName(name string) (Bookmark, bool)

GetBookmarkByName returns a bookmark by its name.

bookmark, found := doc.GetBookmarkByName("Chapter1")

func (*DocxTmpl) GetBookmarkNames added in v0.1.1

func (d *DocxTmpl) GetBookmarkNames() []string

GetBookmarkNames returns just the names of all bookmarks.

names := doc.GetBookmarkNames()

func (*DocxTmpl) GetBookmarks added in v0.1.1

func (d *DocxTmpl) GetBookmarks() []Bookmark

GetBookmarks extracts all bookmarks from the document. Bookmarks are named locations in the document that can be linked to.

bookmarks := doc.GetBookmarks()
for _, b := range bookmarks {
    fmt.Printf("%s (ID: %d)\n", b.Name, b.ID)
}

func (*DocxTmpl) GetChangesByAuthor added in v0.1.1

func (d *DocxTmpl) GetChangesByAuthor(author string) []TrackedChange

GetChangesByAuthor returns tracked changes filtered by author.

claudeChanges := doc.GetChangesByAuthor("Claude")

func (*DocxTmpl) GetCommentAuthors added in v0.1.1

func (d *DocxTmpl) GetCommentAuthors() []string

GetCommentAuthors returns a list of unique comment authors.

authors := doc.GetCommentAuthors()

func (*DocxTmpl) GetCommentReplies added in v0.1.1

func (d *DocxTmpl) GetCommentReplies(commentID int) []Comment

GetCommentReplies returns all replies to a specific comment.

replies := doc.GetCommentReplies(0) // Get replies to comment with ID 0

func (*DocxTmpl) GetComments added in v0.1.1

func (d *DocxTmpl) GetComments() []Comment

GetComments extracts all comments from the document. Returns both top-level comments and replies.

comments := doc.GetComments()
for _, c := range comments {
    fmt.Printf("[%s] %s: %s\n", c.Date.Format("2006-01-02"), c.Author, c.Text)
}

func (*DocxTmpl) GetCommentsByAuthor added in v0.1.1

func (d *DocxTmpl) GetCommentsByAuthor(author string) []Comment

GetCommentsByAuthor returns comments filtered by author name.

myComments := doc.GetCommentsByAuthor("John Doe")

func (*DocxTmpl) GetCommentsInDateRange added in v0.1.1

func (d *DocxTmpl) GetCommentsInDateRange(start, end time.Time) []Comment

GetCommentsInDateRange returns comments within a specific date range.

start := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
end := time.Date(2024, 12, 31, 23, 59, 59, 0, time.UTC)
comments := doc.GetCommentsInDateRange(start, end)

func (*DocxTmpl) GetContentTypesXML added in v0.1.1

func (d *DocxTmpl) GetContentTypesXML() (string, error)

GetContentTypesXML returns the content types XML.

types, err := doc.GetContentTypesXML()

func (*DocxTmpl) GetDeletions added in v0.1.1

func (d *DocxTmpl) GetDeletions() []TrackedChange

GetDeletions returns only deletion changes.

deletions := doc.GetDeletions()

func (*DocxTmpl) GetDocumentXML added in v0.1.1

func (d *DocxTmpl) GetDocumentXML() (string, error)

GetDocumentXML returns the main document XML.

xml, err := doc.GetDocumentXML()

func (*DocxTmpl) GetInsertions added in v0.1.1

func (d *DocxTmpl) GetInsertions() []TrackedChange

GetInsertions returns only insertion changes.

insertions := doc.GetInsertions()
func (d *DocxTmpl) GetInternalLinks() []InternalLink

GetInternalLinks returns all internal hyperlinks (links to bookmarks).

links := doc.GetInternalLinks()

func (*DocxTmpl) GetMedia added in v0.1.1

func (d *DocxTmpl) GetMedia(name string) *Media

GetMedia retrieves an embedded media file by name. Returns nil if the media is not found.

media := doc.GetMedia("image1.png")
if media != nil {
    os.WriteFile("extracted.png", media.Data, 0644)
}

func (*DocxTmpl) GetMetadata added in v0.1.1

func (d *DocxTmpl) GetMetadata() *DocumentMetadata

GetMetadata extracts document metadata from core.xml and app.xml. Returns empty values for fields not found in the document.

meta := doc.GetMetadata()
fmt.Println("Author:", meta.Creator)

func (*DocxTmpl) GetOutline added in v0.1.1

func (d *DocxTmpl) GetOutline() []OutlineItem

GetOutline extracts the document structure as a hierarchical outline. Returns headings organized by their levels.

outline := doc.GetOutline()
for _, item := range outline {
    fmt.Printf("H%d: %s\n", item.Level, item.Text)
}

func (*DocxTmpl) GetParagraphTexts added in v0.1.1

func (d *DocxTmpl) GetParagraphTexts() []string

GetParagraphTexts returns the text content of each paragraph as a slice.

paragraphs := doc.GetParagraphTexts()

func (*DocxTmpl) GetPlaceholderSchema added in v0.1.1

func (d *DocxTmpl) GetPlaceholderSchema() map[string]FieldSchema

GetPlaceholderSchema returns a schema-like map of all placeholders. Useful for generating data templates or documentation.

schema := doc.GetPlaceholderSchema()

func (*DocxTmpl) GetPlaceholders

func (d *DocxTmpl) GetPlaceholders() ([]string, error)

GetPlaceholders returns a list of all unique placeholders found in the document. This is useful for validating templates or showing what data is expected. Placeholders are returned in the format they appear (e.g., "{{.Name}}", "{{range .Items}}").

placeholders, err := doc.GetPlaceholders()
// Returns: []string{"{{.FirstName}}", "{{.LastName}}", "{{range .Items}}", "{{end}}"}

func (*DocxTmpl) GetProperties added in v0.1.1

func (d *DocxTmpl) GetProperties() *DocumentProperties

GetProperties returns the document properties. For documents created from scratch, this returns default/empty properties. For parsed documents, this extracts properties from docProps/core.xml.

func (*DocxTmpl) GetProtectionInfo added in v0.1.1

func (d *DocxTmpl) GetProtectionInfo() *ProtectionInfo

GetProtectionInfo returns information about document protection.

info := doc.GetProtectionInfo()
if info.IsProtected {
    fmt.Printf("Document is protected: %s\n", info.Type)
}

func (*DocxTmpl) GetRegisteredFunctions

func (d *DocxTmpl) GetRegisteredFunctions() *template.FuncMap

Get a pointer to the documents function map. This will include built-in functions.

func (*DocxTmpl) GetRelationships added in v0.1.1

func (d *DocxTmpl) GetRelationships() (string, error)

GetRelationships returns the document relationships.

rels, err := doc.GetRelationships()

func (*DocxTmpl) GetRequiredFields added in v0.1.1

func (d *DocxTmpl) GetRequiredFields() []FieldInfo

GetRequiredFields returns information about all fields required by the template.

fields := doc.GetRequiredFields()
for _, f := range fields {
    fmt.Printf("Field: %s, Occurrences: %d\n", f.Name, f.Occurrences)
}

func (*DocxTmpl) GetRestrictions added in v0.1.1

func (d *DocxTmpl) GetRestrictions() *RestrictionInfo

GetRestrictions returns detailed information about what actions are allowed.

restrictions := doc.GetRestrictions()
if restrictions.CanComment {
    fmt.Println("Comments are allowed")
}

func (*DocxTmpl) GetSettingsXML added in v0.1.1

func (d *DocxTmpl) GetSettingsXML() (string, error)

GetSettingsXML returns the settings XML.

settings, err := doc.GetSettingsXML()

func (*DocxTmpl) GetStats added in v0.1.1

func (d *DocxTmpl) GetStats() *DocumentStats

GetStats returns document statistics including word count, paragraph count, etc.

stats := doc.GetStats()
fmt.Printf("Words: %d, Paragraphs: %d\n", stats.WordCount, stats.ParagraphCount)

func (*DocxTmpl) GetStylesXML added in v0.1.1

func (d *DocxTmpl) GetStylesXML() (string, error)

GetStylesXML returns the styles XML.

styles, err := doc.GetStylesXML()

func (*DocxTmpl) GetTableOfContents added in v0.1.1

func (d *DocxTmpl) GetTableOfContents() []TableOfContentsEntry

GetTableOfContents extracts the table of contents if present. Returns nil if no TOC is found.

toc := doc.GetTableOfContents()

func (*DocxTmpl) GetText added in v0.1.1

func (d *DocxTmpl) GetText() string

GetText extracts all plain text from the document body. Paragraphs are separated by newlines.

text := doc.GetText()

func (*DocxTmpl) GetTextByStyle added in v0.1.1

func (d *DocxTmpl) GetTextByStyle(style string) []string

GetTextByStyle returns all text from paragraphs with the specified style.

headings := doc.GetTextByStyle("Heading1")

func (*DocxTmpl) GetTopLevelComments added in v0.1.1

func (d *DocxTmpl) GetTopLevelComments() []Comment

GetTopLevelComments returns only top-level comments (not replies).

topComments := doc.GetTopLevelComments()

func (*DocxTmpl) GetTrackedChanges added in v0.1.1

func (d *DocxTmpl) GetTrackedChanges() []TrackedChange

GetTrackedChanges extracts all tracked changes from the document. Returns insertions and deletions found in the document XML.

changes := doc.GetTrackedChanges()
for _, change := range changes {
    fmt.Printf("%s by %s: %s\n", change.Type, change.Author, change.Text)
}

func (*DocxTmpl) GetWatermarks

func (d *DocxTmpl) GetWatermarks() []string

GetWatermarks returns all watermark texts found in the document headers. Watermarks are stored as VML shapes with textpath elements in header files.

func (*DocxTmpl) GetXMLContent added in v0.1.1

func (d *DocxTmpl) GetXMLContent(filePath string) (string, error)

GetXMLContent returns the content of a specific XML file within the document.

content, err := doc.GetXMLContent("word/document.xml")

func (*DocxTmpl) GetXMLFiles added in v0.1.1

func (d *DocxTmpl) GetXMLFiles() []string

GetXMLFiles returns a list of all XML files in the document.

files := doc.GetXMLFiles()
for _, f := range files {
    fmt.Println(f)
}

func (*DocxTmpl) HasBookmark added in v0.1.1

func (d *DocxTmpl) HasBookmark(name string) bool

HasBookmark checks if a bookmark with the given name exists.

if doc.HasBookmark("Chapter1") {
    fmt.Println("Found Chapter1 bookmark")
}

func (*DocxTmpl) HasComments added in v0.1.1

func (d *DocxTmpl) HasComments() bool

HasComments returns true if the document contains any comments.

if doc.HasComments() {
    fmt.Println("Document has comments")
}

func (*DocxTmpl) HasTableOfContents added in v0.1.1

func (d *DocxTmpl) HasTableOfContents() bool

HasTableOfContents checks if the document has a table of contents.

if doc.HasTableOfContents() {
    fmt.Println("Document has TOC")
}

func (*DocxTmpl) HasText added in v0.1.1

func (d *DocxTmpl) HasText(text string) bool

HasText checks if the document contains the specified text.

if doc.HasText("confidential") {
    // Handle confidential document
}

func (*DocxTmpl) HasTextMatch added in v0.1.1

func (d *DocxTmpl) HasTextMatch(pattern string) bool

HasTextMatch checks if the document contains text matching the regex pattern.

if doc.HasTextMatch(`\d{3}-\d{2}-\d{4}`) {
    // Document contains SSN pattern
}

func (*DocxTmpl) HasTrackedChanges added in v0.1.1

func (d *DocxTmpl) HasTrackedChanges() bool

HasTrackedChanges returns true if the document contains any tracked changes.

if doc.HasTrackedChanges() {
    fmt.Println("Document has pending changes")
}

func (*DocxTmpl) IsProtected added in v0.1.1

func (d *DocxTmpl) IsProtected() bool

IsProtected returns true if the document has any protection enabled.

if doc.IsProtected() {
    fmt.Println("Document is protected")
}

func (*DocxTmpl) IsReadOnly added in v0.1.1

func (d *DocxTmpl) IsReadOnly() bool

IsReadOnly returns true if the document is read-only protected.

if doc.IsReadOnly() {
    fmt.Println("Document is read-only")
}

func (*DocxTmpl) IsTrackChangesEnabled added in v0.1.1

func (d *DocxTmpl) IsTrackChangesEnabled() bool

IsTrackChangesEnabled checks if track changes mode is enabled.

if doc.IsTrackChangesEnabled() {
    fmt.Println("Track changes is enabled")
}

func (*DocxTmpl) KeepBodyElements added in v0.1.1

func (d *DocxTmpl) KeepBodyElements(names ...string)

KeepBodyElements keeps only specified element types in the document body. Valid names: "*docx.Paragraph", "*docx.Table"

doc.KeepBodyElements("*docx.Paragraph") // Keep only paragraphs, remove tables

func (*DocxTmpl) MailMerge added in v0.1.1

func (d *DocxTmpl) MailMerge(records []map[string]any) ([]*DocxTmpl, error)

MailMerge renders the template with multiple data records. Returns a slice of rendered documents, one per record.

records := []map[string]any{
    {"Name": "John", "Email": "john@example.com"},
    {"Name": "Jane", "Email": "jane@example.com"},
}
docs, err := template.MailMerge(records)

func (*DocxTmpl) MailMergeToFiles added in v0.1.1

func (d *DocxTmpl) MailMergeToFiles(records []map[string]any, filenamePattern string) error

MailMergeToFiles renders the template and saves each result to a file. filenamePattern should contain %d for the record number (e.g., "letter_%d.docx").

err := template.MailMergeToFiles(records, "output/letter_%d.docx")

func (*DocxTmpl) MailMergeToSingle added in v0.1.1

func (d *DocxTmpl) MailMergeToSingle(records []map[string]any) (*DocxTmpl, error)

MailMergeToSingle renders the template with multiple records and combines into a single document with page breaks between each.

merged, err := template.MailMergeToSingle(records)

func (*DocxTmpl) MergeAllRuns added in v0.1.1

func (d *DocxTmpl) MergeAllRuns()

MergeAllRuns merges contiguous runs with same formatting in all paragraphs. This reduces document complexity and can decrease file size.

func (*DocxTmpl) NewListBuilder added in v0.1.1

func (d *DocxTmpl) NewListBuilder(listType ListType) *ListBuilder

NewListBuilder creates a new list builder

list := doc.NewListBuilder(ListTypeBullet).
    Item("First").
    Item("Second").
    Indent().Item("Nested").
    Outdent().Item("Third").
    Build()

func (*DocxTmpl) PreviewRender added in v0.1.1

func (d *DocxTmpl) PreviewRender(data any) (string, error)

PreviewRender renders the template with data but returns the text content instead of saving to a file. Useful for validation and previewing.

preview, err := doc.PreviewRender(data)

func (*DocxTmpl) ProtectionSummary added in v0.1.1

func (d *DocxTmpl) ProtectionSummary() string

ProtectionSummary returns a text summary of protection status.

summary := doc.ProtectionSummary()

func (*DocxTmpl) RegisterFuncMap added in v0.2.0

func (d *DocxTmpl) RegisterFuncMap(funcs template.FuncMap)

RegisterFuncMap registers all functions from a template.FuncMap. This is useful for adding external function libraries like Sprig.

doc.RegisterFuncMap(sprig.FuncMap())

func (*DocxTmpl) RegisterFunction

func (d *DocxTmpl) RegisterFunction(name string, fn any) error

Register a function which can then be used within your template

d.RegisterFunction("sayHello", func(text string) string {
	return "Hello " + text
})

func (*DocxTmpl) RejectAllChanges added in v0.1.1

func (d *DocxTmpl) RejectAllChanges()

RejectAllChanges rejects all tracked changes, removing insertions and restoring deleted text. Note: This modifies the processable files (headers, footers, etc.). Document body changes require re-parsing after save.

doc.RejectAllChanges()

func (*DocxTmpl) RemoveProtection added in v0.1.1

func (d *DocxTmpl) RemoveProtection() error

RemoveProtection removes document protection (without password). Note: This only works for documents without password protection.

err := doc.RemoveProtection()

func (*DocxTmpl) Render

func (d *DocxTmpl) Render(data any) error

Replace the placeholders in the document with passed in data. Data can be a struct or map

data := struct {
	FirstName     string
	LastName      string
	Gender        string
}{
	FirstName: "Tom",
	LastName:  "Watkins",
	Gender:    "Male",
}

err = doc.Render(data)

OR

data := map[string]any{
	"ProjectNumber": "B-00001",
	"Client":        "TW Software",
	"Status":        "New",
}

err = doc.Render(data)

func (*DocxTmpl) ReplaceText added in v0.1.1

func (d *DocxTmpl) ReplaceText(oldText, newText string)

ReplaceText replaces all occurrences of old text with new text in the document. This is a simple text replacement that works on the rendered document. For template-based replacement, use Render() instead.

doc.ReplaceText("COMPANY_NAME", "Acme Corp")

func (*DocxTmpl) ReplaceTextRegex added in v0.1.1

func (d *DocxTmpl) ReplaceTextRegex(pattern, replacement string)

ReplaceTextRegex replaces text matching the pattern with replacement. The replacement can include $1, $2, etc. for captured groups.

doc.ReplaceTextRegex(`\bfoo\b`, "bar")

func (*DocxTmpl) ReplaceWatermark

func (d *DocxTmpl) ReplaceWatermark(oldText, newText string)

ReplaceWatermark replaces a specific watermark text with a new value. This should be called before Render() if you want to change watermark text.

doc.ReplaceWatermark("DRAFT", "FINAL")
doc.Render(data)

func (*DocxTmpl) Save

func (d *DocxTmpl) Save(writer io.Writer) error

Save the document to a writer. This could be a new file.

f, err := os.Create(FILE_PATH)
if err != nil {
	panic(err)
}
err = doc.Save(f)
if err != nil {
	panic(err)
}
err = f.Close()
if err != nil {
	panic(err)
}

func (*DocxTmpl) SaveToFile

func (d *DocxTmpl) SaveToFile(filename string) error

Save the document directly to a file path. This is a convenience method that creates the file and calls Save().

err := doc.SaveToFile("output.docx")
if err != nil {
	panic(err)
}

func (*DocxTmpl) SearchWithContext added in v0.1.1

func (d *DocxTmpl) SearchWithContext(searchText string, contextLines int) []SearchResult

SearchWithContext searches for text and returns matches with context. contextLines specifies how many lines of context to include.

results := doc.SearchWithContext("important", 2)

func (*DocxTmpl) SetAuthor added in v0.1.1

func (d *DocxTmpl) SetAuthor(author string) *DocxTmpl

SetAuthor sets the document author (creator).

func (*DocxTmpl) SetCategory added in v0.1.1

func (d *DocxTmpl) SetCategory(category string) *DocxTmpl

SetCategory sets the document category.

func (*DocxTmpl) SetContentStatus added in v0.1.1

func (d *DocxTmpl) SetContentStatus(status string) *DocxTmpl

SetContentStatus sets the document status (e.g., "Draft", "Final", "Approved").

func (*DocxTmpl) SetDescription added in v0.1.1

func (d *DocxTmpl) SetDescription(description string) *DocxTmpl

SetDescription sets the document description/comments.

func (*DocxTmpl) SetKeywords added in v0.1.1

func (d *DocxTmpl) SetKeywords(keywords string) *DocxTmpl

SetKeywords sets the document keywords.

func (*DocxTmpl) SetMetadata added in v0.1.1

func (d *DocxTmpl) SetMetadata(meta *DocumentMetadata)

SetMetadata sets document metadata in core.xml. Only non-empty fields are updated.

doc.SetMetadata(&DocumentMetadata{
    Title:   "My Report",
    Creator: "John Doe",
})

func (*DocxTmpl) SetProperties added in v0.1.1

func (d *DocxTmpl) SetProperties(props *DocumentProperties)

SetProperties updates the document properties. The properties will be written when the document is saved.

func (*DocxTmpl) SetProtection added in v0.1.1

func (d *DocxTmpl) SetProtection(protType ProtectionType) error

SetProtection sets document protection. Note: This sets protection without a password. For password protection, use the Word application or a dedicated library.

err := doc.SetProtection(docxtpl.ProtectionReadOnly)

func (*DocxTmpl) SetReadOnly added in v0.1.1

func (d *DocxTmpl) SetReadOnly() error

SetReadOnly sets the document to read-only mode.

err := doc.SetReadOnly()

func (*DocxTmpl) SetSubject added in v0.1.1

func (d *DocxTmpl) SetSubject(subject string) *DocxTmpl

SetSubject sets the document subject.

func (*DocxTmpl) SetTitle added in v0.1.1

func (d *DocxTmpl) SetTitle(title string) *DocxTmpl

SetTitle sets the document title.

func (*DocxTmpl) SetXMLContent added in v0.1.1

func (d *DocxTmpl) SetXMLContent(filePath string, content string) error

SetXMLContent sets the content of a processable XML file. Only works for files in the processable files list (headers, footers, settings, etc.)

err := doc.SetXMLContent("word/settings.xml", newContent)

func (*DocxTmpl) SplitAt added in v0.1.1

func (d *DocxTmpl) SplitAt(rule SplitRule) []*DocxTmpl

SplitAt splits the document into multiple documents based on a rule. The rule function receives paragraph text, whether it's a heading, and heading level. Returns a slice of new DocxTmpl documents.

// Split at each Heading 1
docs := doc.SplitAt(func(text string, isHeading bool, level int) bool {
    return isHeading && level == 1
})

func (*DocxTmpl) SplitAtHeading added in v0.1.1

func (d *DocxTmpl) SplitAtHeading(level int) []*DocxTmpl

SplitAtHeading splits the document at each heading of the specified level. Level 0 splits at Title, level 1-9 splits at Heading1-Heading9.

chapters := doc.SplitAtHeading(1) // Split at each Heading 1

func (*DocxTmpl) SplitAtRegex added in v0.1.1

func (d *DocxTmpl) SplitAtRegex(pattern string) []*DocxTmpl

SplitAtRegex splits the document at paragraphs matching the regex pattern.

parts := doc.SplitAtRegex(`^Chapter \d+`) // Split at "Chapter 1", "Chapter 2", etc.

func (*DocxTmpl) SplitAtText added in v0.1.1

func (d *DocxTmpl) SplitAtText(text string) []*DocxTmpl

SplitAtText splits the document at paragraphs containing the specified text.

parts := doc.SplitAtText("---") // Split at paragraphs containing "---"

func (*DocxTmpl) ToHTML added in v0.1.1

func (d *DocxTmpl) ToHTML() string

ToHTML converts the document to basic HTML format.

html := doc.ToHTML()

func (*DocxTmpl) ToJSON added in v0.1.1

func (d *DocxTmpl) ToJSON() (string, error)

ToJSON returns the document structure as JSON.

jsonStr, err := doc.ToJSON()

func (*DocxTmpl) ToMarkdown added in v0.1.1

func (d *DocxTmpl) ToMarkdown() string

ToMarkdown converts the document to Markdown format. Supports headings, bold, italic, lists, tables, and links.

markdown := doc.ToMarkdown()

func (*DocxTmpl) ToStructured added in v0.1.1

func (d *DocxTmpl) ToStructured() *StructuredDocument

ToStructured converts the document to a structured representation. This is useful for AI/LLM consumption and document analysis.

structured := doc.ToStructured()
jsonBytes, _ := json.Marshal(structured)

func (*DocxTmpl) TrackedChangesSummary added in v0.1.1

func (d *DocxTmpl) TrackedChangesSummary() string

TrackedChangesSummary returns a text summary of all tracked changes.

summary := doc.TrackedChangesSummary()
fmt.Println(summary)

func (*DocxTmpl) UnpackToDirectory added in v0.1.1

func (d *DocxTmpl) UnpackToDirectory(dirPath string) error

UnpackToDirectory extracts the DOCX file to a directory. This allows direct access to all XML files for advanced manipulation.

err := doc.UnpackToDirectory("/tmp/unpacked")

func (*DocxTmpl) Validate added in v0.2.1

func (d *DocxTmpl) Validate() *ValidationResult

Validate checks the template for common errors without rendering. It returns a ValidationResult containing any errors found.

result := doc.Validate()
if result.HasErrors() {
    for _, err := range result.Errors {
        fmt.Println(err)
    }
}

func (*DocxTmpl) ValidateData added in v0.1.1

func (d *DocxTmpl) ValidateData(data any) []ValidationError

ValidateData validates that the provided data contains all required template fields. Returns a slice of validation errors, or empty slice if valid.

errors := doc.ValidateData(data)
if len(errors) > 0 {
    for _, err := range errors {
        fmt.Println(err)
    }
}

func (*DocxTmpl) ValidatePlaceholderSyntax added in v0.1.1

func (d *DocxTmpl) ValidatePlaceholderSyntax() []ValidationError

ValidatePlaceholderSyntax checks all placeholders for correct syntax. Returns errors for malformed placeholders.

errors := doc.ValidatePlaceholderSyntax()

type ErrorCode added in v0.2.1

type ErrorCode string

ErrorCode represents a specific error type for programmatic handling.

const (
	// Parse errors
	ErrCodeInvalidFile   ErrorCode = "INVALID_FILE"
	ErrCodeCorruptedDocx ErrorCode = "CORRUPTED_DOCX"
	ErrCodeFileNotFound  ErrorCode = "FILE_NOT_FOUND"
	ErrCodeReadError     ErrorCode = "READ_ERROR"

	// Template errors
	ErrCodeSyntaxError    ErrorCode = "SYNTAX_ERROR"
	ErrCodeUnclosedTag    ErrorCode = "UNCLOSED_TAG"
	ErrCodeUnmatchedEnd   ErrorCode = "UNMATCHED_END"
	ErrCodeUndefinedField ErrorCode = "UNDEFINED_FIELD"
	ErrCodeInvalidFunc    ErrorCode = "INVALID_FUNCTION"
	ErrCodeExecutionError ErrorCode = "EXECUTION_ERROR"

	// Render errors
	ErrCodeDataConversion ErrorCode = "DATA_CONVERSION"
	ErrCodeImageError     ErrorCode = "IMAGE_ERROR"
	ErrCodeMarshalError   ErrorCode = "MARSHAL_ERROR"

	// Save errors
	ErrCodeWriteError ErrorCode = "WRITE_ERROR"
	ErrCodeZipError   ErrorCode = "ZIP_ERROR"

	// Merge errors
	ErrCodeMergeError ErrorCode = "MERGE_ERROR"
)

type ErrorSummary added in v0.2.1

type ErrorSummary struct {
	Errors []*TemplateError
}

ErrorSummary provides a summary of multiple errors.

func (*ErrorSummary) Add added in v0.2.1

func (s *ErrorSummary) Add(err *TemplateError)

Add adds an error to the summary.

func (*ErrorSummary) ByCode added in v0.2.1

func (s *ErrorSummary) ByCode(code ErrorCode) []*TemplateError

ByCode returns all errors with a specific code.

func (*ErrorSummary) ByLocation added in v0.2.1

func (s *ErrorSummary) ByLocation(location string) []*TemplateError

ByLocation returns all errors from a specific location.

func (*ErrorSummary) Error added in v0.2.1

func (s *ErrorSummary) Error() string

Error implements the error interface.

func (*ErrorSummary) HasErrors added in v0.2.1

func (s *ErrorSummary) HasErrors() bool

HasErrors returns true if there are any errors.

func (*ErrorSummary) String added in v0.2.1

func (s *ErrorSummary) String() string

String returns a detailed multi-line description of all errors.

type FieldInfo added in v0.1.1

type FieldInfo struct {
	Name        string   // Field name (e.g., "Person.Name")
	Required    bool     // Whether the field is required
	Type        string   // Expected type (string, slice, etc.)
	Example     string   // Example value
	Occurrences int      // Number of times field appears
	Locations   []string // Where field appears (body, header, footer)
}

FieldInfo represents information about a template field

type FieldSchema added in v0.1.1

type FieldSchema struct {
	Type       string                 `json:"type"` // "string", "number", "boolean", "array", "object"
	Required   bool                   `json:"required"`
	Properties map[string]FieldSchema `json:"properties,omitempty"` // For nested objects
	Items      *FieldSchema           `json:"items,omitempty"`      // For arrays
}

FieldSchema represents a JSON schema-like field definition

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

Hyperlink wraps a Word hyperlink.

func (*Hyperlink) GetRaw added in v0.1.1

func (h *Hyperlink) GetRaw() *docx.Hyperlink

GetRaw returns the underlying go-docx hyperlink for advanced usage.

func (*Hyperlink) Then added in v0.1.1

func (h *Hyperlink) Then() *Paragraph

Then returns to the parent paragraph for continued building.

type HyperlinkInfo added in v0.1.1

type HyperlinkInfo struct {
	Text       string // Display text
	URL        string // Target URL
	Index      int    // Paragraph index
	IsInternal bool   // True if internal bookmark link
}

HyperlinkInfo contains information about a hyperlink in the document.

type ImageInfo added in v0.1.1

type ImageInfo struct {
	Name   string `json:"name"`
	Format string `json:"format"`
	Size   int    `json:"size"` // bytes
}

ImageInfo represents an embedded image

type IndentOptions added in v0.1.1

type IndentOptions struct {
	Left           int // Left indent in twips (1/20 of a point, 1440 = 1 inch)
	Right          int // Right indent in twips
	FirstLine      int // First line indent in twips (positive = indent, use Hanging for outdent)
	Hanging        int // Hanging indent in twips (first line outdent)
	LeftChars      int // Left indent in character units (100 = 1 character)
	FirstLineChars int // First line indent in character units
}

IndentOptions configures paragraph indentation

type InlineImage

type InlineImage struct {
	Ext string
	// contains filtered or unexported fields
}

func CreateInlineImage

func CreateInlineImage(filepath string) (*InlineImage, error)

Take a filenane for an image and return a pointer to an InlineImage struct. Images can be Jpegs (.jpg or .jpeg) or PNGs

img, err := CreateInlineImage("example_img.png")

func CreateInlineImageFromBytes added in v0.2.1

func CreateInlineImageFromBytes(data []byte, ext string) (*InlineImage, error)

CreateInlineImageFromBytes creates an InlineImage from raw bytes. You must specify the extension (.jpg, .jpeg, or .png).

img, err := CreateInlineImageFromBytes(imageData, ".png")

func CreateInlineImageFromURL added in v0.2.1

func CreateInlineImageFromURL(url string) (*InlineImage, error)

CreateInlineImageFromURL downloads an image from a URL and returns an InlineImage. Images can be Jpegs (.jpg or .jpeg) or PNGs. Timeout defaults to 30 seconds.

img, err := CreateInlineImageFromURL("https://example.com/image.png")

func CreateInlineImageFromURLWithTimeout added in v0.2.1

func CreateInlineImageFromURLWithTimeout(url string, timeout time.Duration) (*InlineImage, error)

CreateInlineImageFromURLWithTimeout downloads an image from a URL with a custom timeout.

img, err := CreateInlineImageFromURLWithTimeout("https://example.com/image.png", 10*time.Second)

func (*InlineImage) GetExifData

func (i *InlineImage) GetExifData() (map[string]imagemeta.TagInfo, error)

Return a map of EXIF data from the image.

func (*InlineImage) GetResolution

func (i *InlineImage) GetResolution() (wDpi int, hDpi int)

Get the resolution (DPI) of the image. It gets this from EXIF data and defaults to 72 if not found.

func (*InlineImage) GetSize

func (i *InlineImage) GetSize() (w int64, h int64, err error)

Get the size of the image in EMUs.

func (*InlineImage) Resize

func (i *InlineImage) Resize(width int, height int) error

Resize the image. Width and height should be pixel values.

type InlineImageError

type InlineImageError struct {
	Message string
}

func (*InlineImageError) Error

func (e *InlineImageError) Error() string
type InternalLink struct {
	Anchor string // Bookmark name this link points to
	Text   string // Display text
}

InternalLink represents an internal hyperlink (link to bookmark)

type Justification added in v0.1.1

type Justification string

Justification represents paragraph alignment

const (
	JustifyLeft       Justification = "left"
	JustifyCenter     Justification = "center"
	JustifyRight      Justification = "right"
	JustifyBoth       Justification = "both"       // Justified
	JustifyDistribute Justification = "distribute" // Distributed
)

type List added in v0.1.1

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

List wraps a collection of list paragraphs

func (*List) AddItem added in v0.1.1

func (l *List) AddItem(text string) *List

AddItem adds another item to the list at the same level.

func (*List) AddSubItem added in v0.1.1

func (l *List) AddSubItem(text string, level int) *List

AddSubItem adds a nested item to the list.

func (*List) Count added in v0.1.1

func (l *List) Count() int

Count returns the number of items in the list.

func (*List) GetParagraphs added in v0.1.1

func (l *List) GetParagraphs() []*Paragraph

GetParagraphs returns all paragraphs in the list.

type ListBuilder added in v0.1.1

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

ListBuilder provides a fluent interface for building complex lists

func (*ListBuilder) Build added in v0.1.1

func (lb *ListBuilder) Build() *List

Build creates the list and adds it to the document

func (*ListBuilder) Indent added in v0.1.1

func (lb *ListBuilder) Indent() *ListBuilder

Indent increases the indentation level for subsequent items

func (*ListBuilder) Item added in v0.1.1

func (lb *ListBuilder) Item(text string) *ListBuilder

Item adds an item at the current indentation level

func (*ListBuilder) Level added in v0.1.1

func (lb *ListBuilder) Level(level int) *ListBuilder

Level sets the indentation level directly

func (*ListBuilder) Outdent added in v0.1.1

func (lb *ListBuilder) Outdent() *ListBuilder

Outdent decreases the indentation level for subsequent items

type ListItem added in v0.1.1

type ListItem struct {
	Text     string     // Item text
	Level    int        // Nesting level (0-8)
	Children []ListItem // Nested items
}

ListItem represents an item in a list with optional nesting

type ListType added in v0.1.1

type ListType int

ListType represents the type of list

const (
	ListTypeBullet   ListType = iota // Bullet list (-, o, *)
	ListTypeNumbered                 // Numbered list (1, 2, 3)
	ListTypeLetter                   // Letter list (a, b, c)
	ListTypeRoman                    // Roman numeral list (i, ii, iii)
)

type Margins added in v0.1.1

type Margins struct {
	Top    float64
	Right  float64
	Bottom float64
	Left   float64
}

Margins represents page margins in inches

func DefaultMargins added in v0.1.1

func DefaultMargins() Margins

DefaultMargins returns the default Word margins (1 inch all around)

func NarrowMargins added in v0.1.1

func NarrowMargins() Margins

NarrowMargins returns narrow margins (0.5 inch all around)

func WideMargins added in v0.1.1

func WideMargins() Margins

WideMargins returns wide margins (1 inch top/bottom, 2 inch left/right)

type Media added in v0.1.1

type Media struct {
	Name string // Filename (e.g., "image1.png")
	Data []byte // File contents
}

Media represents an embedded media file in the document.

type Orientation added in v0.1.1

type Orientation string

Orientation represents page orientation

const (
	OrientationPortrait  Orientation = "portrait"
	OrientationLandscape Orientation = "landscape"
)

type OutlineItem added in v0.1.1

type OutlineItem struct {
	Level    int           // Heading level (0=Title, 1-9=Heading1-9)
	Text     string        // Heading text
	Index    int           // Paragraph index in document
	Children []OutlineItem // Nested headings
}

OutlineItem represents a heading in the document outline.

type PageSize added in v0.1.1

type PageSize int

PageSize represents standard page sizes

const (
	PageSizeA4 PageSize = iota
	PageSizeA3
	PageSizeLetter
	PageSizeLegal
)

type Paragraph added in v0.1.1

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

Paragraph wraps a Word paragraph with formatting methods. Methods can be chained for fluent API usage.

func (*Paragraph) AddAnchorImage added in v0.1.1

func (p *Paragraph) AddAnchorImage(imageData []byte) (*Run, error)

AddAnchorImage adds a floating/anchored image to the paragraph. The image can be positioned independently of text flow.

data, _ := os.ReadFile("logo.png")
para.AddAnchorImage(data)

func (*Paragraph) AddAnchorImageFromFile added in v0.1.1

func (p *Paragraph) AddAnchorImageFromFile(filepath string) (*Run, error)

AddAnchorImageFromFile adds a floating/anchored image from a file path.

para.AddAnchorImageFromFile("logo.png")

func (*Paragraph) AddAnchorShape added in v0.1.1

func (p *Paragraph) AddAnchorShape(opts ShapeOptions) *Run

AddAnchorShape adds a floating shape to the paragraph. Use ShapeOptions to configure the shape appearance.

para.AddAnchorShape(ShapeOptions{
    Width: 914400, Height: 914400, // 1 inch x 1 inch
    Preset: ShapeRectangle,
    LineColor: "000000",
})

func (*Paragraph) AddBreak added in v0.1.1

func (p *Paragraph) AddBreak() *Paragraph

AddBreak adds a line break within the paragraph.

func (*Paragraph) AddInlineImage added in v0.1.1

func (p *Paragraph) AddInlineImage(imageData []byte) (*Run, error)

AddInlineImage adds an inline image to the paragraph. Inline images flow with the text.

data, _ := os.ReadFile("icon.png")
para.AddInlineImage(data)

func (*Paragraph) AddInlineImageFromFile added in v0.1.1

func (p *Paragraph) AddInlineImageFromFile(filepath string) (*Run, error)

AddInlineImageFromFile adds an inline image from a file path.

para.AddInlineImageFromFile("icon.png")

func (*Paragraph) AddInlineShape added in v0.1.1

func (p *Paragraph) AddInlineShape(opts ShapeOptions) *Run

AddInlineShape adds an inline shape to the paragraph. Inline shapes flow with the text.

func (p *Paragraph) AddLink(text, url string) *Hyperlink

AddLink adds a hyperlink to the paragraph. Returns the Hyperlink for further customization.

para.AddLink("Click here", "https://example.com")

func (*Paragraph) AddPageBreak added in v0.1.1

func (p *Paragraph) AddPageBreak() *Paragraph

AddPageBreak adds a page break after this paragraph.

func (*Paragraph) AddTab added in v0.1.1

func (p *Paragraph) AddTab() *Paragraph

AddTab adds a tab character to the paragraph.

func (*Paragraph) AddTabStop added in v0.1.1

func (p *Paragraph) AddTabStop(position int, align, leader string) *Paragraph

AddTabStop adds a tab stop at the specified position. Align can be: "left", "center", "right", "decimal" Leader can be: "none", "dot", "hyphen", "underscore"

para.AddTabStop(4320, "left", "none")

func (*Paragraph) AddTabStops added in v0.1.1

func (p *Paragraph) AddTabStops(stops []TabStop) *Paragraph

AddTabStops adds multiple tab stops from a slice of TabStop.

para.AddTabStops([]TabStop{
    {Position: 1440, Align: "left"},
    {Position: 4320, Align: "center"},
    {Position: 7200, Align: "right"},
})

func (*Paragraph) AddText added in v0.1.1

func (p *Paragraph) AddText(text string) *Run

AddText adds more text to the paragraph and returns a Run for formatting.

para := doc.AddParagraph("Hello ")
para.AddText("World").Bold().Color("FF0000")

func (*Paragraph) Background added in v0.1.1

func (p *Paragraph) Background(hexColor string) *Paragraph

Background sets a solid background color for the text.

func (*Paragraph) Bold added in v0.1.1

func (p *Paragraph) Bold() *Paragraph

Bold applies bold formatting to all text in the paragraph.

func (*Paragraph) Bullet added in v0.1.1

func (p *Paragraph) Bullet() *Paragraph

Bullet makes this paragraph a bullet point.

func (*Paragraph) Center added in v0.1.1

func (p *Paragraph) Center() *Paragraph

Center centers the paragraph text.

func (*Paragraph) ClearTabStops added in v0.1.1

func (p *Paragraph) ClearTabStops() *Paragraph

ClearTabStops removes all tab stops from the paragraph.

func (*Paragraph) Color added in v0.1.1

func (p *Paragraph) Color(hexColor string) *Paragraph

Color sets the text color for all text in the paragraph. Use hex color code without # (e.g., "FF0000" for red).

func (*Paragraph) DropAllDrawings added in v0.1.1

func (p *Paragraph) DropAllDrawings() *Paragraph

DropAllDrawings removes all shapes, canvases, and groups from the paragraph.

func (*Paragraph) DropCanvas added in v0.1.1

func (p *Paragraph) DropCanvas() *Paragraph

DropCanvas removes all canvas elements from the paragraph.

func (*Paragraph) DropEmptyPictures added in v0.1.1

func (p *Paragraph) DropEmptyPictures() *Paragraph

DropEmptyPictures removes nil/empty picture references from the paragraph.

func (*Paragraph) DropGroups added in v0.1.1

func (p *Paragraph) DropGroups() *Paragraph

DropGroups removes all group elements from the paragraph.

func (*Paragraph) DropShapes added in v0.1.1

func (p *Paragraph) DropShapes() *Paragraph

DropShapes removes all shapes from the paragraph.

func (*Paragraph) Font added in v0.1.1

func (p *Paragraph) Font(fontName string) *Paragraph

Font sets the font family for the paragraph text.

func (*Paragraph) GetRaw added in v0.1.1

func (p *Paragraph) GetRaw() *docx.Paragraph

GetRaw returns the underlying go-docx paragraph for advanced usage.

func (*Paragraph) GetText added in v0.1.1

func (p *Paragraph) GetText() string

GetText returns the plain text content of the paragraph.

text := para.GetText()

func (*Paragraph) Highlight added in v0.1.1

func (p *Paragraph) Highlight(color string) *Paragraph

Highlight applies a highlight color to the paragraph text. Valid colors: yellow, green, cyan, magenta, blue, red, darkBlue, darkCyan, darkGreen, darkMagenta, darkRed, darkYellow, darkGray, lightGray, black

func (*Paragraph) Indent added in v0.1.1

func (p *Paragraph) Indent(opts IndentOptions) *Paragraph

Indent sets paragraph indentation options.

para.Indent(IndentOptions{Left: 720, FirstLine: 360})

func (*Paragraph) IndentFirstLine added in v0.1.1

func (p *Paragraph) IndentFirstLine(inches float64) *Paragraph

IndentFirstLine sets the first line indentation in inches.

para.IndentFirstLine(0.5)

func (*Paragraph) IndentHanging added in v0.1.1

func (p *Paragraph) IndentHanging(inches float64) *Paragraph

IndentHanging sets a hanging indent (outdent for first line) in inches.

para.IndentHanging(0.5)

func (*Paragraph) IndentLeft added in v0.1.1

func (p *Paragraph) IndentLeft(inches float64) *Paragraph

IndentLeft sets the left indentation in inches.

para.IndentLeft(0.5)

func (*Paragraph) IndentRight added in v0.1.1

func (p *Paragraph) IndentRight(inches float64) *Paragraph

IndentRight sets the right indentation in inches.

func (*Paragraph) Italic added in v0.1.1

func (p *Paragraph) Italic() *Paragraph

Italic applies italic formatting to all text in the paragraph.

func (*Paragraph) Justified added in v0.1.1

func (p *Paragraph) Justified() *Paragraph

Justified aligns text to both left and right margins.

func (*Paragraph) Justify added in v0.1.1

func (p *Paragraph) Justify(j Justification) *Paragraph

Justify sets the paragraph alignment.

para.Justify(docxtpl.JustifyCenter)

func (*Paragraph) KeepElements added in v0.1.1

func (p *Paragraph) KeepElements(names ...string) *Paragraph

KeepElements keeps only the specified element types in the paragraph. Valid names: "w:r" (runs), "w:hyperlink", "w:bookmarkStart", "w:bookmarkEnd"

para.KeepElements("w:r", "w:hyperlink")

func (*Paragraph) Left added in v0.1.1

func (p *Paragraph) Left() *Paragraph

Left aligns the paragraph text to the left (default).

func (*Paragraph) LineSpacing added in v0.1.1

func (p *Paragraph) LineSpacing(twips int) *Paragraph

LineSpacing sets the line spacing in twips. Use "single" (240), "1.5" (360), "double" (480), or a custom value.

para.LineSpacing(360) // 1.5 line spacing

func (*Paragraph) LineSpacingDouble added in v0.1.1

func (p *Paragraph) LineSpacingDouble() *Paragraph

LineSpacingDouble sets double line spacing.

func (*Paragraph) LineSpacingOneAndHalf added in v0.1.1

func (p *Paragraph) LineSpacingOneAndHalf() *Paragraph

LineSpacingOneAndHalf sets 1.5 line spacing.

func (*Paragraph) LineSpacingSingle added in v0.1.1

func (p *Paragraph) LineSpacingSingle() *Paragraph

LineSpacingSingle sets single line spacing.

func (*Paragraph) MergeAllRuns added in v0.1.1

func (p *Paragraph) MergeAllRuns() *Paragraph

MergeAllRuns merges all contiguous runs regardless of formatting.

func (*Paragraph) MergeRuns added in v0.1.1

func (p *Paragraph) MergeRuns() *Paragraph

MergeRuns merges contiguous runs with the same formatting into single runs.

para.MergeRuns()

func (*Paragraph) Numbered added in v0.1.1

func (p *Paragraph) Numbered() *Paragraph

Numbered makes this paragraph a numbered list item.

func (*Paragraph) Right added in v0.1.1

func (p *Paragraph) Right() *Paragraph

Right aligns the paragraph text to the right.

func (*Paragraph) Shade added in v0.1.1

func (p *Paragraph) Shade(pattern, color, fill string) *Paragraph

Shade applies background shading to the text. pattern: "clear", "solid", "horzStripe", "vertStripe", "diagStripe", etc. color: the pattern color (hex) fill: the background fill color (hex)

func (*Paragraph) Size added in v0.1.1

func (p *Paragraph) Size(halfPoints int) *Paragraph

Size sets the font size for all text in the paragraph. Size is in half-points (e.g., 24 = 12pt).

func (*Paragraph) SizePoints added in v0.1.1

func (p *Paragraph) SizePoints(points int) *Paragraph

SizePoints sets the font size in points (convenience method). e.g., SizePoints(12) sets 12pt font.

func (*Paragraph) Spacing added in v0.1.1

func (p *Paragraph) Spacing(opts SpacingOptions) *Paragraph

Spacing sets paragraph spacing options.

para.Spacing(SpacingOptions{Before: 240, After: 120, Line: 360})

func (*Paragraph) SpacingAfter added in v0.1.1

func (p *Paragraph) SpacingAfter(points int) *Paragraph

SpacingAfter sets the space after the paragraph in points.

para.SpacingAfter(6)

func (*Paragraph) SpacingBefore added in v0.1.1

func (p *Paragraph) SpacingBefore(points int) *Paragraph

SpacingBefore sets the space before the paragraph in points.

para.SpacingBefore(12)

func (*Paragraph) Strike added in v0.1.1

func (p *Paragraph) Strike() *Paragraph

Strike applies strikethrough formatting to the paragraph text.

func (*Paragraph) Style added in v0.1.1

func (p *Paragraph) Style(styleID string) *Paragraph

Style applies a paragraph style by name. Common styles: "Normal", "Heading1", "Heading2", "Title", "Subtitle", "Quote", "IntenseQuote", "ListParagraph", "ListBullet", "ListNumber"

para.Style("Heading1")

func (*Paragraph) Underline added in v0.1.1

func (p *Paragraph) Underline() *Paragraph

Underline applies underline formatting to all text in the paragraph.

type ProtectionInfo added in v0.1.1

type ProtectionInfo struct {
	IsProtected    bool           // Whether the document is protected
	Type           ProtectionType // Type of protection
	HasPassword    bool           // Whether a password is set
	EnforceMessage string         // Enforcement message if any
}

ProtectionInfo contains information about document protection

type ProtectionType added in v0.1.1

type ProtectionType string

ProtectionType represents the type of document protection

const (
	ProtectionNone           ProtectionType = "none"
	ProtectionReadOnly       ProtectionType = "readOnly"
	ProtectionComments       ProtectionType = "comments"       // Allow only comments
	ProtectionTrackedChanges ProtectionType = "trackedChanges" // Allow only tracked changes
	ProtectionForms          ProtectionType = "forms"          // Allow only form filling
)

type RestrictionInfo added in v0.1.1

type RestrictionInfo struct {
	CanEdit       bool // Can edit the document
	CanComment    bool // Can add comments
	CanTrack      bool // Can make tracked changes
	CanFillForms  bool // Can fill forms
	CanFormatText bool // Can format text
}

RestrictionInfo provides detailed restriction information

type Run added in v0.1.1

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

Run wraps a Word text run with formatting methods. A run is a contiguous piece of text with the same formatting. Methods can be chained for fluent API usage.

func (*Run) AddTab added in v0.1.1

func (r *Run) AddTab() *Run

AddTab adds a tab character after this run.

func (*Run) AllCaps added in v0.1.1

func (r *Run) AllCaps() *Run

AllCaps applies all capitals formatting.

func (*Run) Background added in v0.1.1

func (r *Run) Background(hexColor string) *Run

Background sets a solid background color for this run.

func (*Run) Bold added in v0.1.1

func (r *Run) Bold() *Run

Bold applies bold formatting to this run.

para.AddText("Bold text").Bold()

func (*Run) CharacterSpacing added in v0.1.1

func (r *Run) CharacterSpacing(twips int) *Run

CharacterSpacing sets the spacing between characters in twips. Positive values expand spacing, negative values condense. 20 twips = 1 point.

run.CharacterSpacing(40) // Expand by 2pt

func (*Run) Color added in v0.1.1

func (r *Run) Color(hexColor string) *Run

Color sets the text color for this run. Use hex color code without # (e.g., "FF0000" for red).

func (*Run) Condense added in v0.1.1

func (r *Run) Condense(points float64) *Run

Condense condenses character spacing by the specified points.

run.Condense(1) // Condense by 1pt

func (*Run) DoubleStrike added in v0.1.1

func (r *Run) DoubleStrike() *Run

DoubleStrike applies double strikethrough formatting.

func (*Run) Expand added in v0.1.1

func (r *Run) Expand(points float64) *Run

Expand expands character spacing by the specified points.

run.Expand(2) // Expand by 2pt

func (*Run) Font added in v0.1.1

func (r *Run) Font(fontName string) *Run

Font sets the font family for this run. fontName is applied to ASCII and high ANSI characters.

func (*Run) GetRaw added in v0.1.1

func (r *Run) GetRaw() *docx.Run

GetRaw returns the underlying go-docx run for advanced usage.

func (*Run) GetText added in v0.1.1

func (r *Run) GetText() string

GetText returns the plain text content of this run.

func (*Run) Highlight added in v0.1.1

func (r *Run) Highlight(color string) *Run

Highlight applies a highlight color to this run. Valid colors: yellow, green, cyan, magenta, blue, red, darkBlue, darkCyan, darkGreen, darkMagenta, darkRed, darkYellow, darkGray, lightGray, black

func (*Run) Italic added in v0.1.1

func (r *Run) Italic() *Run

Italic applies italic formatting to this run.

func (*Run) KeepElements added in v0.1.1

func (r *Run) KeepElements(names ...string) *Run

KeepElements keeps only specified element types in this run. Valid names depend on run content (e.g., "w:t" for text, "w:drawing" for drawings)

func (*Run) Kern added in v0.1.1

func (r *Run) Kern(halfPoints int) *Run

Kern sets the minimum font size for kerning in half-points. Kerning adjusts spacing between certain character pairs.

run.Kern(24) // Kern text 12pt and larger

func (*Run) Shade added in v0.1.1

func (r *Run) Shade(pattern, color, fill string) *Run

Shade applies background shading to this run. pattern: "clear", "solid", "horzStripe", "vertStripe", "diagStripe", etc. color: the pattern color (hex) fill: the background fill color (hex)

func (*Run) Size added in v0.1.1

func (r *Run) Size(halfPoints int) *Run

Size sets the font size for this run. Size is in half-points (e.g., 24 = 12pt).

func (*Run) SizePoints added in v0.1.1

func (r *Run) SizePoints(points int) *Run

SizePoints sets the font size in points (convenience method). e.g., SizePoints(12) sets 12pt font.

func (*Run) SmallCaps added in v0.1.1

func (r *Run) SmallCaps() *Run

SmallCaps applies small capitals formatting.

func (*Run) Strike added in v0.1.1

func (r *Run) Strike() *Run

Strike applies strikethrough formatting to this run.

func (*Run) Subscript added in v0.1.1

func (r *Run) Subscript() *Run

Subscript applies subscript formatting to this run.

para.AddText("H").Then().AddText("2").Subscript().Then().AddText("O") // H₂O

func (*Run) Superscript added in v0.1.1

func (r *Run) Superscript() *Run

Superscript applies superscript formatting to this run.

para.AddText("x").Then().AddText("2").Superscript() // x²

func (*Run) Then added in v0.1.1

func (r *Run) Then() *Paragraph

Then returns to the parent paragraph for continued building.

para.AddText("Bold").Bold().Then().AddText(" Normal")

func (*Run) Underline added in v0.1.1

func (r *Run) Underline(style ...string) *Run

Underline applies underline formatting to this run. Common values: "single", "double", "thick", "dotted", "dash", "wave"

type SearchResult added in v0.1.1

type SearchResult struct {
	Text       string // The matched text
	Line       int    // Line number (1-indexed)
	Paragraph  int    // Paragraph index (0-indexed)
	Context    string // Surrounding context
	MatchStart int    // Start position of match in context
}

SearchResult contains information about a text match.

type SectionBreakType added in v0.1.1

type SectionBreakType string

SectionBreakType represents the type of section break

const (
	SectionBreakNextPage   SectionBreakType = "nextPage"
	SectionBreakContinuous SectionBreakType = "continuous"
	SectionBreakEvenPage   SectionBreakType = "evenPage"
	SectionBreakOddPage    SectionBreakType = "oddPage"
)

type ShapeOptions added in v0.1.1

type ShapeOptions struct {
	Width     int64       // Width in EMUs (English Metric Units, 914400 = 1 inch)
	Height    int64       // Height in EMUs
	Preset    ShapePreset // Shape preset (rectangle, ellipse, etc.)
	Name      string      // Shape name
	LineColor string      // Outline color (hex without #)
	LineWidth int64       // Outline width in EMUs
	BWMode    string      // Black and white mode ("auto", "black", "white", etc.)
}

ShapeOptions configures a shape

type ShapePreset added in v0.1.1

type ShapePreset string

ShapePreset defines common shape presets

const (
	ShapeRectangle       ShapePreset = "rect"
	ShapeRoundedRect     ShapePreset = "roundRect"
	ShapeEllipse         ShapePreset = "ellipse"
	ShapeTriangle        ShapePreset = "triangle"
	ShapeDiamond         ShapePreset = "diamond"
	ShapePentagon        ShapePreset = "pentagon"
	ShapeHexagon         ShapePreset = "hexagon"
	ShapeArrowRight      ShapePreset = "rightArrow"
	ShapeArrowLeft       ShapePreset = "leftArrow"
	ShapeArrowUp         ShapePreset = "upArrow"
	ShapeArrowDown       ShapePreset = "downArrow"
	ShapeStar5           ShapePreset = "star5"
	ShapeStar6           ShapePreset = "star6"
	ShapeHeart           ShapePreset = "heart"
	ShapeLightningBolt   ShapePreset = "lightningBolt"
	ShapeSun             ShapePreset = "sun"
	ShapeMoon            ShapePreset = "moon"
	ShapeCloud           ShapePreset = "cloud"
	ShapeLine            ShapePreset = "line"
	ShapeStraightConnect ShapePreset = "straightConnector1"
)

type SpacingOptions added in v0.1.1

type SpacingOptions struct {
	Before      int    // Space before paragraph (in twips, 1/20 of a point)
	After       int    // Space after paragraph (in twips)
	Line        int    // Line spacing (in twips or percentage depending on LineRule)
	LineRule    string // "auto", "exact", "atLeast"
	BeforeLines int    // Space before in lines (1 = 100)
}

SpacingOptions configures paragraph spacing

type SplitRule added in v0.1.1

type SplitRule func(text string, isHeading bool, headingLevel int) bool

SplitRule defines a function that determines where to split a document. Return true to split before the paragraph that matches.

type StructuredDocument added in v0.1.1

type StructuredDocument struct {
	Metadata   DocumentMetadata      `json:"metadata"`
	Stats      DocumentStats         `json:"stats"`
	Outline    []OutlineItem         `json:"outline"`
	Paragraphs []StructuredParagraph `json:"paragraphs"`
	Tables     []StructuredTable     `json:"tables"`
	Images     []ImageInfo           `json:"images"`
	Links      []HyperlinkInfo       `json:"links"`
}

StructuredDocument represents the document in a structured format suitable for AI consumption

type StructuredParagraph added in v0.1.1

type StructuredParagraph struct {
	Index     int             `json:"index"`
	Text      string          `json:"text"`
	Style     string          `json:"style"`
	IsList    bool            `json:"is_list,omitempty"`
	ListLevel int             `json:"list_level,omitempty"`
	Alignment string          `json:"alignment,omitempty"`
	Runs      []StructuredRun `json:"runs,omitempty"`
}

StructuredParagraph represents a paragraph with its metadata

type StructuredRun added in v0.1.1

type StructuredRun struct {
	Text       string `json:"text"`
	Bold       bool   `json:"bold,omitempty"`
	Italic     bool   `json:"italic,omitempty"`
	Underline  bool   `json:"underline,omitempty"`
	Strike     bool   `json:"strike,omitempty"`
	Color      string `json:"color,omitempty"`
	FontSize   int    `json:"font_size,omitempty"`
	FontFamily string `json:"font_family,omitempty"`
	Highlight  string `json:"highlight,omitempty"`
}

StructuredRun represents a text run with formatting

type StructuredTable added in v0.1.1

type StructuredTable struct {
	Index   int        `json:"index"`
	Rows    int        `json:"rows"`
	Cols    int        `json:"cols"`
	Data    [][]string `json:"data"`
	Headers []string   `json:"headers,omitempty"`
}

StructuredTable represents a table with its data

type TabStop added in v0.1.1

type TabStop struct {
	Position int    // Position in twips (1440 = 1 inch)
	Align    string // "left", "center", "right", "decimal"
	Leader   string // "none", "dot", "hyphen", "underscore"
}

TabStop defines a tab stop position and alignment

type Table added in v0.1.1

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

Table wraps a Word table with formatting and manipulation methods.

func (*Table) AddColumn added in v0.1.1

func (t *Table) AddColumn() *Table

AddColumn adds a new column to the table.

table.AddColumn()

func (*Table) AddRow added in v0.1.1

func (t *Table) AddRow() *TableRow

AddRow adds a new empty row to the table. Returns the new TableRow for populating.

row := table.AddRow()
row.SetCell(0, "New cell")

func (*Table) AddRowWithData added in v0.1.1

func (t *Table) AddRowWithData(values ...string) *TableRow

AddRowWithData adds a new row with the given cell values.

table.AddRowWithData("Col1", "Col2", "Col3")

func (*Table) Cell added in v0.1.1

func (t *Table) Cell(row, col int) *TableCell

Cell returns the cell at the specified row and column (0-indexed). Returns nil if the indices are out of bounds.

func (*Table) Center added in v0.1.1

func (t *Table) Center() *Table

Center centers the table on the page.

func (*Table) ClearColumn added in v0.1.1

func (t *Table) ClearColumn(col int) *Table

ClearColumn clears all cell content in a column.

table.ClearColumn(0)

func (*Table) ClearRow added in v0.1.1

func (t *Table) ClearRow(rowIdx int) *Table

ClearRow clears all cell content in a row.

table.ClearRow(0)

func (*Table) Cols added in v0.1.1

func (t *Table) Cols() int

Cols returns the number of columns in the table.

func (*Table) DeleteColumn added in v0.1.1

func (t *Table) DeleteColumn(index int) *Table

DeleteColumn removes the column at the specified index.

table.DeleteColumn(2)

func (*Table) DeleteRow added in v0.1.1

func (t *Table) DeleteRow(index int) *Table

DeleteRow removes the row at the specified index.

table.DeleteRow(2)

func (*Table) FillColumn added in v0.1.1

func (t *Table) FillColumn(col int, value string) *Table

FillColumn fills all cells in a column with the same value.

table.FillColumn(0, "N/A")

func (*Table) FillRow added in v0.1.1

func (t *Table) FillRow(rowIdx int, value string) *Table

FillRow fills all cells in a row with the same value.

table.FillRow(0, "Header")

func (*Table) FindAllRows added in v0.1.1

func (t *Table) FindAllRows(col int, value string) []int

FindAllRows finds all rows where the specified column contains the value.

rows := table.FindAllRows(1, "Active")

func (*Table) FindRow added in v0.1.1

func (t *Table) FindRow(col int, value string) int

FindRow finds the first row where the specified column contains the value. Returns -1 if not found.

rowIdx := table.FindRow(0, "John")

func (*Table) GetColumn added in v0.1.1

func (t *Table) GetColumn(col int) []string

GetColumn returns all values in a column.

values := table.GetColumn(0)

func (*Table) GetRaw added in v0.1.1

func (t *Table) GetRaw() *docx.Table

GetRaw returns the underlying go-docx table for advanced usage.

func (*Table) GetRowData added in v0.1.1

func (t *Table) GetRowData(rowIdx int) []string

GetRowData returns all values in a row.

values := table.GetRowData(0)

func (*Table) InsertColumn added in v0.1.1

func (t *Table) InsertColumn(index int) *Table

InsertColumn inserts a new column at the specified index.

table.InsertColumn(1)

func (*Table) InsertRow added in v0.1.1

func (t *Table) InsertRow(index int) *TableRow

InsertRow inserts a new row at the specified index. Existing rows are shifted down.

table.InsertRow(1)

func (*Table) Justify added in v0.1.1

func (t *Table) Justify(alignment string) *Table

Justify sets the table alignment. Valid values: "left", "center", "right"

func (*Table) Row added in v0.1.1

func (t *Table) Row(index int) *TableRow

Row returns a TableRow wrapper for the specified row index.

func (*Table) Rows added in v0.1.1

func (t *Table) Rows() int

Rows returns the number of rows in the table.

func (*Table) SetAllColumnWidths added in v0.1.1

func (t *Table) SetAllColumnWidths(widths []int) *Table

SetAllColumnWidths sets widths for all columns.

table.SetAllColumnWidths([]int{2880, 1440, 1440})

func (*Table) SetBorderColors added in v0.1.1

func (t *Table) SetBorderColors(colors TableBorderColors) *Table

SetBorderColors sets border colors for all cells in the table. Note: For best results, use AddTableWithBorders when creating the table.

func (*Table) SetCell added in v0.1.1

func (t *Table) SetCell(row, col int, text string) *TableCell

SetCell sets the text content of a cell at the specified row and column. Returns the TableCell for further formatting.

table.SetCell(0, 0, "Header 1").Bold().Background("CCCCCC")

func (*Table) SetColumnWidth added in v0.1.1

func (t *Table) SetColumnWidth(col int, twips int) *Table

SetColumnWidth sets the width for a specific column in twips.

table.SetColumnWidth(0, 2880)

func (*Table) SetRowHeight added in v0.1.1

func (t *Table) SetRowHeight(rowIdx int, twips int) *Table

SetRowHeight sets the height for a specific row in twips.

table.SetRowHeight(0, 720)

func (*Table) SortByColumn added in v0.1.1

func (t *Table) SortByColumn(col int, ascending, skipHeader bool) *Table

SortByColumn sorts the table rows by the specified column. Set ascending to false for descending order. skipHeader skips the first row (treats it as a header).

table.SortByColumn(0, true, true)

func (*Table) ToCSV added in v0.1.1

func (t *Table) ToCSV() string

ToCSV returns the table data as CSV.

csvStr := table.ToCSV()

func (*Table) ToJSON added in v0.1.1

func (t *Table) ToJSON(headers bool) (string, error)

ToJSON returns the table data as JSON. If headers is true, the first row is used as keys.

jsonStr, err := table.ToJSON(true)

func (*Table) ToSlice added in v0.1.1

func (t *Table) ToSlice() [][]string

ToSlice returns the table data as a 2D string slice.

data := table.ToSlice()

type TableBorderColors added in v0.1.1

type TableBorderColors struct {
	Top     string // Top border color
	Left    string // Left border color
	Bottom  string // Bottom border color
	Right   string // Right border color
	InsideH string // Inside horizontal border color
	InsideV string // Inside vertical border color
}

TableBorderColors defines custom border colors for tables. Use hex color codes without # (e.g., "000000" for black).

type TableCell added in v0.1.1

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

TableCell wraps a Word table cell.

func (*TableCell) AddParagraph added in v0.1.1

func (c *TableCell) AddParagraph(text string) *Paragraph

AddParagraph adds a new paragraph to the cell and returns it.

func (*TableCell) Background added in v0.1.1

func (c *TableCell) Background(hexColor string) *TableCell

Background sets a solid background color for the cell.

func (*TableCell) Bold added in v0.1.1

func (c *TableCell) Bold() *TableCell

Bold applies bold formatting to the cell's text.

func (*TableCell) Borders added in v0.1.1

func (c *TableCell) Borders(color string, width int) *TableCell

Borders sets all borders for this cell. color is a hex color code without # (e.g., "000000" for black). width is the border width in eighths of a point.

cell.Borders("000000", 4) // Black border, 0.5pt width

func (*TableCell) Center added in v0.1.1

func (c *TableCell) Center() *TableCell

Center centers the text in the cell.

func (*TableCell) GetRaw added in v0.1.1

func (c *TableCell) GetRaw() *docx.WTableCell

GetRaw returns the underlying go-docx table cell for advanced usage.

func (*TableCell) MergeHorizontal added in v0.1.1

func (c *TableCell) MergeHorizontal(count int) *TableCell

MergeHorizontal merges this cell with the specified number of cells to the right. Uses GridSpan to span multiple columns.

table.Cell(0, 0).MergeHorizontal(2) // Merge with 2 cells to the right (3 total)

func (*TableCell) MergeVerticalContinue added in v0.1.1

func (c *TableCell) MergeVerticalContinue() *TableCell

MergeVerticalContinue marks this cell as a continuation of a vertical merge. The cell above must have MergeVerticalStart or MergeVerticalContinue.

func (*TableCell) MergeVerticalStart added in v0.1.1

func (c *TableCell) MergeVerticalStart() *TableCell

MergeVerticalStart marks this cell as the start of a vertical merge. Use with MergeVerticalContinue on cells below.

table.Cell(0, 0).MergeVerticalStart() // Start of vertical merge
table.Cell(1, 0).MergeVerticalContinue() // Continue merge

func (*TableCell) NoBorders added in v0.1.1

func (c *TableCell) NoBorders() *TableCell

NoBorders removes all borders from this cell.

func (*TableCell) SetText added in v0.1.1

func (c *TableCell) SetText(text string) *TableCell

SetText sets the text content of the cell. Clears any existing content and adds a new paragraph with the text.

func (*TableCell) Shade added in v0.1.1

func (c *TableCell) Shade(pattern, color, fill string) *TableCell

Shade applies background shading to the cell. pattern: "clear", "solid", etc. color: pattern color (hex) fill: background fill color (hex)

func (*TableCell) VAlign added in v0.1.1

func (c *TableCell) VAlign(align VerticalAlignment) *TableCell

VAlign sets the vertical alignment of the cell content.

cell.VAlign(docxtpl.VAlignCenter)

func (*TableCell) VAlignBottom added in v0.1.1

func (c *TableCell) VAlignBottom() *TableCell

VAlignBottom aligns cell content to the bottom.

func (*TableCell) VAlignCenter added in v0.1.1

func (c *TableCell) VAlignCenter() *TableCell

VAlignCenter vertically centers cell content.

func (*TableCell) VAlignTop added in v0.1.1

func (c *TableCell) VAlignTop() *TableCell

VAlignTop aligns cell content to the top.

func (*TableCell) Width added in v0.1.1

func (c *TableCell) Width(twips int) *TableCell

Width sets the cell width in twips (1/20 of a point). 1 inch = 1440 twips, 1 cm = 567 twips.

cell.Width(2880) // 2 inches

func (*TableCell) WidthCm added in v0.1.1

func (c *TableCell) WidthCm(cm float64) *TableCell

WidthCm sets the cell width in centimeters.

cell.WidthCm(3.5) // 3.5 cm

func (*TableCell) WidthInches added in v0.1.1

func (c *TableCell) WidthInches(inches float64) *TableCell

WidthInches sets the cell width in inches.

cell.WidthInches(1.5) // 1.5 inches

func (*TableCell) WidthPercent added in v0.1.1

func (c *TableCell) WidthPercent(percent int) *TableCell

WidthPercent sets the cell width as a percentage of table width.

cell.WidthPercent(25) // 25% of table width

type TableOfContentsEntry added in v0.1.1

type TableOfContentsEntry struct {
	Level    int    // Entry level (1, 2, 3, etc.)
	Text     string // Entry text
	Page     string // Page number (may be empty if not updated)
	Bookmark string // Bookmark reference
}

TableOfContentsEntry represents an entry in the table of contents

type TableRow added in v0.1.1

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

TableRow wraps a Word table row.

func (*TableRow) Cell added in v0.1.1

func (r *TableRow) Cell(col int) *TableCell

Cell returns the cell at the specified column in this row.

func (*TableRow) GetRaw added in v0.1.1

func (r *TableRow) GetRaw() *docx.WTableRow

GetRaw returns the underlying go-docx table row for advanced usage.

func (*TableRow) Justify added in v0.1.1

func (r *TableRow) Justify(alignment string) *TableRow

Justify sets the alignment for all cells in this row.

func (*TableRow) SetCell added in v0.1.1

func (r *TableRow) SetCell(col int, text string) *TableCell

SetCell sets the text content of a cell in this row.

type TemplateError added in v0.2.1

type TemplateError struct {
	// Code is a programmatic error code for categorization.
	Code ErrorCode

	// Message is a human-readable error description.
	Message string

	// Location describes where the error occurred (e.g., "document body", "header1").
	Location string

	// Placeholder is the template tag that caused the error, if applicable.
	Placeholder string

	// LineNumber is the approximate line in the template, if available.
	LineNumber int

	// Cause is the underlying error that caused this error.
	Cause error

	// Suggestions provides possible fixes for the error.
	Suggestions []string
}

TemplateError is an enhanced error type that provides detailed context about where and why an error occurred during template processing.

func ErrFileParse added in v0.2.1

func ErrFileParse(filename string, cause error) *TemplateError

ErrFileParse creates a file parsing error.

func ErrImageLoad added in v0.2.1

func ErrImageLoad(path string, cause error) *TemplateError

ErrImageLoad creates an image loading error.

func ErrInvalidFunc added in v0.2.1

func ErrInvalidFunc(funcName string) *TemplateError

ErrInvalidFunc creates an invalid function error.

func ErrSyntax added in v0.2.1

func ErrSyntax(message string) *TemplateError

ErrSyntax creates a syntax error.

func ErrUnclosedTag added in v0.2.1

func ErrUnclosedTag(location string) *TemplateError

ErrUnclosedTag creates an unclosed tag error.

func ErrUndefinedField added in v0.2.1

func ErrUndefinedField(field string, location string) *TemplateError

ErrUndefinedField creates an undefined field error.

func ErrUnmatchedEnd added in v0.2.1

func ErrUnmatchedEnd(tag string, location string) *TemplateError

ErrUnmatchedEnd creates an unmatched end error.

func IsTemplateError added in v0.2.1

func IsTemplateError(err error) (*TemplateError, bool)

IsTemplateError checks if an error is a TemplateError and returns it.

func NewTemplateError added in v0.2.1

func NewTemplateError(code ErrorCode, message string) *TemplateError

NewTemplateError creates a new TemplateError.

func (*TemplateError) Error added in v0.2.1

func (e *TemplateError) Error() string

Error implements the error interface.

func (*TemplateError) String added in v0.2.1

func (e *TemplateError) String() string

String returns a detailed multi-line error description.

func (*TemplateError) Unwrap added in v0.2.1

func (e *TemplateError) Unwrap() error

Unwrap returns the underlying error for errors.Is and errors.As support.

func (*TemplateError) WithCause added in v0.2.1

func (e *TemplateError) WithCause(cause error) *TemplateError

WithCause returns a copy of the error with the cause set.

func (*TemplateError) WithLocation added in v0.2.1

func (e *TemplateError) WithLocation(location string) *TemplateError

WithLocation returns a copy of the error with the location set.

func (*TemplateError) WithPlaceholder added in v0.2.1

func (e *TemplateError) WithPlaceholder(placeholder string) *TemplateError

WithPlaceholder returns a copy of the error with the placeholder set.

func (*TemplateError) WithSuggestions added in v0.2.1

func (e *TemplateError) WithSuggestions(suggestions ...string) *TemplateError

WithSuggestions returns a copy of the error with suggestions added.

type TrackedChange added in v0.1.1

type TrackedChange struct {
	ID       int               // Change ID
	Type     TrackedChangeType // insertion or deletion
	Author   string            // Author who made the change
	Date     time.Time         // When the change was made
	Text     string            // The changed text
	Location string            // Location description (paragraph index, etc.)
}

TrackedChange represents a tracked change in the document

type TrackedChangeType added in v0.1.1

type TrackedChangeType string

TrackedChangeType represents the type of tracked change

const (
	ChangeTypeInsertion TrackedChangeType = "insertion"
	ChangeTypeDeletion  TrackedChangeType = "deletion"
)

type TrackedChangesConfig added in v0.1.1

type TrackedChangesConfig struct {
	Author   string // Default author name
	Initials string // Default author initials
}

TrackedChangesConfig holds configuration for tracked changes

func DefaultTrackedChangesConfig added in v0.1.1

func DefaultTrackedChangesConfig() TrackedChangesConfig

DefaultTrackedChangesConfig returns default configuration

type UnpackedDocument added in v0.1.1

type UnpackedDocument struct {
	Files map[string][]byte // All files in the archive
}

UnpackedDocument represents an unpacked DOCX document

type ValidationError added in v0.1.1

type ValidationError struct {
	Field       string // Field name that caused the error
	Message     string // Error description
	Placeholder string // Original placeholder text
}

ValidationError represents a template validation error

func (ValidationError) Error added in v0.1.1

func (e ValidationError) Error() string

type ValidationErrorType added in v0.2.1

type ValidationErrorType string

ValidationErrorType represents the type of validation error.

const (
	ErrorUnclosedTag     ValidationErrorType = "UNCLOSED_TAG"
	ErrorUnmatchedEnd    ValidationErrorType = "UNMATCHED_END"
	ErrorSyntaxError     ValidationErrorType = "SYNTAX_ERROR"
	ErrorUndefinedField  ValidationErrorType = "UNDEFINED_FIELD"
	ErrorInvalidFunction ValidationErrorType = "INVALID_FUNCTION"
)

type ValidationResult added in v0.2.1

type ValidationResult struct {
	Valid  bool
	Errors []ValidationError
}

ValidationResult contains the results of template validation.

func (*ValidationResult) Error added in v0.2.1

func (r *ValidationResult) Error() string

Error returns a combined error message for all validation errors.

func (*ValidationResult) HasErrors added in v0.2.1

func (r *ValidationResult) HasErrors() bool

HasErrors returns true if there are any validation errors.

type VerticalAlignment added in v0.1.1

type VerticalAlignment string

VerticalAlignment represents vertical alignment in table cells.

const (
	VAlignTop    VerticalAlignment = "top"
	VAlignCenter VerticalAlignment = "center"
	VAlignBottom VerticalAlignment = "bottom"
)

type XMLFile added in v0.1.1

type XMLFile struct {
	Path    string // File path within the archive (e.g., "word/document.xml")
	Content string // XML content
}

XMLFile represents an XML file from the DOCX archive

Directories

Path Synopsis
cmd
test_template command
Example demonstrates basic usage of go-docxgen
Example demonstrates basic usage of go-docxgen
internal
docx
Package docx is one of the most functional libraries to read and write .docx (a.k.a.
Package docx is one of the most functional libraries to read and write .docx (a.k.a.
docx/cmd/main command
Package main is a function demo
Package main is a function demo

Jump to

Keyboard shortcuts

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