Skip to content

Releases: mmonterroca/docxgo

v2.3.0 — Template / Mail Merge engine

28 Feb 02:42
b548d88

Choose a tag to compare

Release Notes - v2.3.0

Release Date: February 2026

Summary

v2.3.0 introduces the Template / Mail Merge engine — a new pkg/template/ package for document template processing. This release adds placeholder detection, data merging, batch document generation, custom delimiter support, and full MERGEFIELD compatibility with real Microsoft Word templates.

New Features

Template / Mail Merge Engine (pkg/template/)

A complete template processing package with zero external dependencies:

  • MergeTemplate() — Replace {{placeholder}} tokens with data values while preserving all formatting
  • FindPlaceholders() / PlaceholderNames() — Detect all placeholders across body, tables, headers, and footers
  • ValidateTemplate() — Check for missing or unused data keys before merging
  • ConsolidateRuns() — Merge adjacent runs with identical formatting to heal split placeholders
  • Custom Delimiters — Support for ${key}, «key», or any custom open/close delimiter pair
  • Strict Mode — Optional error reporting for missing keys during merge
  • Batch Merge — Generate multiple documents from a single template with different data sets

MERGEFIELD Support

Full compatibility with Microsoft Word's native mail merge fields:

  • Reads Word MERGEFIELD instructions from .docx templates
  • Correctly handles Word's two-run MERGEFIELD pattern (field instruction + display text)
  • Supports «guillemet» delimiters used by Word's mail merge UI
  • Tested with real production Word templates

Paragraph Mutation APIs

  • Paragraph.ClearRuns() — Remove all runs from a paragraph
  • Paragraph.RemoveRun(index) — Remove a specific run by index
  • Paragraph.InsertRunAt(index) — Insert a new run at a specific position

Run Content Inspection

  • Run.Fields() — Access field instructions in a run
  • Run.Breaks() — Access break elements in a run
  • Run.Image() — Access embedded image in a run
  • Run.ClearFields() — Clear field instructions from a run

New Examples

  • Example 14: Mail merge invoice template with batch generation (programmatic)
  • Example 15: External Word template with real MERGEFIELDs and «» delimiters

Bug Fixes

  • Phantom Header/Footer References — Fixed walkParagraphs() calling section.Header() which auto-creates headers/footers on sections that don't have them, causing "Word found unreadable content" errors. Now uses read-only HeadersAll()/FootersAll() methods.
  • MERGEFIELD Text Duplication — Fixed issue where MERGEFIELD display text was duplicated after merge because the field instruction in the preceding run continued to emit the original placeholder. Now clears fields from the preceding run when replacing MERGEFIELD text.

Installation

go get github.com/mmonterroca/docxgo/v2@v2.3.0

Usage Examples

Basic Template Merge

import (
    docx "github.com/mmonterroca/docxgo/v2"
    "github.com/mmonterroca/docxgo/v2/pkg/template"
)

doc := docx.NewDocument()
para, _ := doc.AddParagraph()
run, _ := para.AddRun()
run.SetText("Hello {{name}}, welcome to {{company}}!")

data := template.MergeData{
    "name":    "John",
    "company": "Acme Corp",
}

err := template.MergeTemplate(doc, data)
// MergeTemplate modifies the document in place
doc.SaveAs("output.docx")

External Word Template with MERGEFIELDs

doc, _ := docx.OpenDocument("template.docx")

opts := template.MergeOptions{
    OpenDelimiter:  "«",
    CloseDelimiter: "»",
}

data := template.MergeData{
    "Contact_FullName": "Jane Doe",
    "Account_Name":     "Acme Corp",
}

err := template.MergeTemplate(doc, data, opts)
// MergeTemplate modifies the document in place
doc.SaveAs("merged_output.docx")

Batch Merge

records := []template.MergeData{
    {"name": "John Smith", "amount": "$1,500.00"},
    {"name": "Alice Johnson", "amount": "$2,300.00"},
}

for i, data := range records {
    doc, _ := docx.OpenDocument("invoice_template.docx")
    template.MergeTemplate(doc, data)
    doc.SaveAs(fmt.Sprintf("invoice_%d.docx", i+1))
}

Files Added

  • pkg/template/doc.go — Package documentation
  • pkg/template/merge.go — Core merge logic
  • pkg/template/merge_test.go — Merge tests
  • pkg/template/placeholder.go — Placeholder detection
  • pkg/template/placeholder_test.go — Placeholder tests
  • pkg/template/consolidate.go — Run consolidation
  • pkg/template/consolidate_test.go — Consolidation tests
  • pkg/template/format.go — Run formatting comparison helper
  • pkg/template/options.go — MergeData, MergeOptions, ValidationError types
  • pkg/template/walk.go — Document traversal
  • pkg/template/integration_test.go — Integration tests
  • examples/14_mail_merge/main.go — Programmatic template example
  • examples/15_external_template/main.go — External Word template example

Files Modified

  • domain/paragraph.go — Added ClearRuns(), RemoveRun(), InsertRunAt()
  • domain/run.go — Added Fields(), Breaks(), Image(), ClearFields()
  • internal/core/paragraph.go — Implemented paragraph mutation methods
  • internal/core/run.go — Implemented run content inspection and ClearFields()

Test Coverage

  • 41 new tests across the pkg/template/ package
  • All existing tests continue to pass
  • Tested with real Microsoft Word templates containing MERGEFIELDs

Acknowledgements

This release represents the biggest feature addition since the v2.0.0 rewrite, adding a complete template engine while maintaining the library's zero-dependency philosophy.

v2.2.2

27 Feb 06:04
5019370

Choose a tag to compare

Release Notes - v2.2.2

Release Date: February 2026

Summary

This release fixes a critical issue where tables using built-in styles (e.g., TableGrid, PlainTable1) rendered without visible borders in Microsoft Word. It also includes a comprehensive documentation overhaul to bring all docs up to date, and restores the themes example.

Bug Fixes

Table Style Borders Not Rendering (#15)

Tables with applied styles like TableGrid appeared without any borders in Word because the style definitions in styles.xml were missing w:tblPr / w:tblBorders elements.

Root Cause: Table styles were registered in the style manager but had no border data attached. The serializer had no logic to emit w:tblPr for table-type styles.

Fix:

  • Added TableStyleDef interface to domain/style.go with TableBorders(), SetTableBorders(), HasTableBorders(), and CellMargins() methods
  • Added TableLevelBorders struct to domain/table.go with InsideH and InsideV fields for inner grid borders
  • Updated tableStyle in internal/manager/table_style.go to implement TableStyleDef with border and cell margin storage
  • Built-in styles TableGrid and PlainTable1 now ship with all-around + inside single borders (0.5pt)
  • Added serializeTableStyleProperties() to the document serializer, emitting proper w:tblPr > w:tblBorders XML
  • Added TableStyleProperties, TableCellMargins, TableCellMargin, and TableLevelBorders XML structs

Grid Column Width Calculation

  • serializeGrid() now derives column widths from the first row's cell widths instead of emitting w:w="0" for every column
  • Handles cell span (gridSpan) by distributing width evenly across spanned columns
  • Falls back to omitting widths (Word auto-calculates) when no explicit widths are set

Improvements

Examples Updated

  • 01_basic and 02_intermediate: Added .Style(domain.TableStyleGrid) to table creation so tables render with visible borders out of the box
  • 13_themes: Restored with updated v2 API — generates 7 themed documents (Corporate, Startup, Modern, Fintech, Academic, TechPresentation, TechDarkMode)

Documentation Overhaul (#14)

Comprehensive update across all documentation files to reflect the current state of the project:

  • README.md: Updated version info, example count (13), architecture tree, features section, roadmap with actual release history, copyright year
  • CHANGELOG.md: Added all missing version entries (v2.0.0-beta through v2.2.1 — previously only had v2.2.0)
  • docs/IMPLEMENTATION_STATUS.md: Complete rewrite — accurate release history table, removed outdated roadmap/recommendations, fixed known limitations (document reading works since v2.0.0), added mail merge as top planned feature
  • docs/README.md: Updated example count to 13, added missing examples to index
  • examples/README.md: Added 13_themes section, removed reference to nonexistent basic/ directory
  • docs/V2_API_GUIDE.md: Updated version from v2.0.0-beta to v2.2.1
  • docs/V2_DESIGN.md: Updated status from "v2.0.0-beta Ready" to "v2.2.1 Stable"

Installation

go get github.com/mmonterroca/docxgo/v2@v2.2.2

Usage Example

package main

import (
    docx "github.com/mmonterroca/docxgo/v2"
    "github.com/mmonterroca/docxgo/v2/domain"
)

func main() {
    builder := docx.NewDocumentBuilder(
        docx.WithTitle("Invoice"),
    )

    builder.AddParagraph().Text("Product List").Style(domain.StyleHeading1).End()

    // Tables now render with visible borders when using TableStyleGrid
    builder.AddTable(2, 3).
        Style(domain.TableStyleGrid).
        Row(0).Cell(0).Text("Product").Bold().End().
        Row(0).Cell(1).Text("Qty").Bold().End().
        Row(0).Cell(2).Text("Price").Bold().End().
        Row(1).Cell(0).Text("Widget").End().
        Row(1).Cell(1).Text("10").End().
        Row(1).Cell(2).Text("$9.99").End()

    doc, _ := builder.Build()
    doc.SaveAs("invoice.docx")
}

Files Changed

Code Changes

  • domain/style.go — Added TableStyleDef interface
  • domain/table.go — Added TableLevelBorders struct, clarified TableBorders doc comment
  • internal/manager/style.go — Built-in table styles now carry border definitions
  • internal/manager/table_style.go — Implements TableStyleDef (borders + cell margins)
  • internal/serializer/serializer.go — New serializeTableStyleProperties(), serializeStyleBorder(), borderLineStyleToString() functions; improved serializeGrid() with width derivation
  • internal/xml/style.go — Added TableStyleProperties, TableCellMargins, TableCellMargin structs
  • internal/xml/table.go — Added TableLevelBorders struct, Space attr on Border, Borders field on TableProperties

Example Changes

  • examples/01_basic/main.go — Added Style(domain.TableStyleGrid) to table
  • examples/02_intermediate/main.go — Added Style(domain.TableStyleGrid) to tables
  • examples/13_themes/main.go — Restored with full v2 API (355 lines)

Documentation Changes

  • CHANGELOG.md — Complete version history (v2.0.0-beta through v2.2.2)
  • README.md — Version, features, roadmap, examples updated
  • docs/IMPLEMENTATION_STATUS.md — Full rewrite (722 → 376 lines)
  • docs/README.md — Example count and index updated
  • docs/V2_API_GUIDE.md — Version header updated
  • docs/V2_DESIGN.md — Status header updated
  • examples/README.md — Added 13_themes, removed stale references

Acknowledgements

v2.2.1 - DOCX Validation Fix

23 Jan 04:14
0b9f7e2

Choose a tag to compare

Release Notes - v2.2.1

Release Date: January 2026

Bug Fixes

This release fixes critical DOCX validation errors that prevented documents from opening in Microsoft Word after round-trip operations (read → modify → save).

Fixed

  • Hyperlink RelationshipID Preservation (#6)

    • When reading and re-saving documents with hyperlinks, the library was generating new relationship IDs instead of preserving the originals
    • This caused Word to fail with "relationship not found" errors
    • Now correctly preserves original rId references during round-trip
  • Drawing Position Serialization

    • Fixed wp:align empty value error for floating images
    • Images with posOffset=0 were incorrectly serialized with empty <wp:align> elements
    • Added UseOffsetX/UseOffsetY flags to ImagePosition to distinguish between "offset = 0" and "no offset set"
  • Internal Hyperlink Anchors

    • Added support for anchor-based internal hyperlinks (bookmarks, TOC links)
    • Serializer now correctly handles both anchor property and URLs starting with #
  • Custom Styles Preservation

    • Documents with custom styles (modified Heading1, custom BodyCopy, etc.) are now preserved correctly during round-trip
    • All 55+ custom styles from templates are maintained

New Features

Troubleshooting Documentation

Added comprehensive troubleshooting guide for DOCX validation errors:

  • docs/TROUBLESHOOTING_DOCX_VALIDATION.md
  • Includes diagnostic workflow, common errors, and solutions

Installation

go get github.com/mmonterroca/docxgo/v2@v2.2.1

Usage Example

// Read existing document with custom styles
doc, err := docx.OpenDocument("template.docx")
if err != nil {
    log.Fatal(err)
}

// Modify content - styles are preserved
para := doc.AddParagraph()
para.AddRun().SetText("New content")

// Save - document opens correctly in Word
if err := doc.SaveAs("output.docx"); err != nil {
    log.Fatal(err)
}

Known Limitations

When loading an existing document and adding new images or hyperlinks (not modifying existing ones), the new relationships may not be written correctly. This is tracked in #8.

For the primary use case of reading a template, modifying text, and saving, this version works correctly.

Acknowledgements

Thanks to @krishnadubagunta for reporting the issue with detailed examples that helped identify the root cause.

Files Changed

  • domain/image.go - Added UseOffsetX/UseOffsetY flags
  • internal/core/run.go - Preserve existing relationshipID
  • internal/core/document.go - Store preserved parts for round-trip
  • internal/reader/reconstruct.go - Preserve original parts and set UseOffset flags
  • internal/serializer/serializer.go - Handle anchor hyperlinks, use preserved relationshipID
  • internal/writer/zip.go - Write preserved parts during round-trip
  • internal/xml/drawing_helper.go - Use offset flags in serialization
  • internal/xml/paragraph.go - Add Anchor/History to Hyperlink struct

Full Changelog

See PR #7 for complete details.

v2.2.0 – Table Cell Border Property Serialization & Validation

06 Jan 03:30

Choose a tag to compare

v2.2.0 – Table Cell Border Property Serialization & Validation

This release ensures table cell borders are serialized with explicit properties per side:

  • Style: "single"
  • Width (Sz): 4
  • Color: "FF0000" (hex for ColorRed)

Acknowledgements

v2.1.1 - Theme System + Go Module Path Fix

05 Nov 00:07

Choose a tag to compare

Release Notes - v2.1.1

Release Date: January 2025

Critical Bug Fix

This is a patch release that fixes a critical Go module compatibility issue in v2.1.0.

Fixed

  • Go Module Path: Added required /v2 suffix to module declaration in go.mod
    • Previous: module github.com/mmonterroca/docxgo
    • Fixed: module github.com/mmonterroca/docxgo/v2
    • This is required by Go's semantic versioning for v2+ major versions

Impact

Version v2.1.0 could not be imported correctly due to the missing /v2 suffix. Users attempting to run:

go get github.com/mmonterroca/docxgo/v2@v2.1.0

Would encounter module path mismatch errors. This release resolves that issue.

Installation

go get github.com/mmonterroca/docxgo/v2@v2.1.1

Usage

All imports now use the /v2 path:

import (
    docx "github.com/mmonterroca/docxgo/v2"
    "github.com/mmonterroca/docxgo/v2/domain"
    "github.com/mmonterroca/docxgo/v2/themes"
)

What's in v2.1.x

This release includes all features from v2.1.0:

Theme System

A comprehensive theming system with 6 pre-built themes:

  • DefaultTheme: Professional balanced design
  • ModernLight: Clean, spacious contemporary look
  • TechPresentation: Tech-focused with strong visual hierarchy
  • TechDarkMode: Dark background with bright accents
  • AcademicFormal: Traditional academic style
  • MinimalistClean: Ultra-minimal design

See RELEASE_NOTES_v2.1.0.md for complete feature details.

Notes

  • This release contains the same features as v2.1.0
  • Only the module path declaration has been fixed
  • All tests passing
  • No API changes

Upgrading from v2.1.0

If you were using v2.1.0 (which was broken), simply update your dependencies:

go get github.com/mmonterroca/docxgo/v2@v2.1.1

No code changes required - just update the version in your go.mod.

Upgrading from v2.0.x

The theme system is fully backward compatible. Existing code continues to work without changes. To use themes:

import "github.com/mmonterroca/docxgo/v2/themes"

theme := themes.ModernLight()
doc := docx.NewDocument(docx.WithTheme(theme))

Full Changelog: See CHANGELOG.md for complete version history.

v2.0.1 - Go Module Path Fix

05 Nov 00:07

Choose a tag to compare

Release Notes - v2.0.1

Release Date: January 2025

Critical Bug Fix

This is a patch release that fixes a critical Go module compatibility issue in v2.0.0.

Fixed

  • Go Module Path: Added required /v2 suffix to module declaration in go.mod
    • Previous: module github.com/mmonterroca/docxgo
    • Fixed: module github.com/mmonterroca/docxgo/v2
    • This is required by Go's semantic versioning for v2+ major versions

Impact

Version v2.0.0 could not be imported correctly due to the missing /v2 suffix. Users attempting to run:

go get github.com/mmonterroca/docxgo/v2@v2.0.0

Would encounter module path mismatch errors. This release resolves that issue.

Installation

go get github.com/mmonterroca/docxgo/v2@v2.0.1

Usage

All imports now use the /v2 path:

import (
    docx "github.com/mmonterroca/docxgo/v2"
    "github.com/mmonterroca/docxgo/v2/domain"
)

Notes

  • This release contains the same features as v2.0.0
  • Only the module path declaration has been fixed
  • All tests passing
  • No API changes

Upgrading from v2.0.0

If you were using v2.0.0 (which was broken), simply update your dependencies:

go get github.com/mmonterroca/docxgo/v2@v2.0.1

No code changes required - just update the version in your go.mod.


Full Changelog: See CHANGELOG.md for complete version history.

v2.1.0 - Theme System

01 Nov 00:34

Choose a tag to compare

Release Notes - v2.1.0

🎨 go-docx v2.1.0 - Themes & Advanced Styling

Release Date: October 31, 2025

We're excited to announce v2.1.0, bringing powerful theme support and advanced styling capabilities to go-docx!


🆕 What's New

🎨 Theme System

Complete theme infrastructure for consistent document styling:

  • Pre-built Themes - 6 professional themes ready to use
  • Theme Colors - Comprehensive color palettes (Primary, Secondary, Accent, Background, Text, etc.)
  • Theme Fonts - Font families for body, headings, and monospace
  • Theme Spacing - Configurable spacing for paragraphs, headings, and sections
  • Custom Themes - Clone and customize existing themes or create from scratch
  • Theme Application - Apply themes globally to documents with one method call

Available Themes:

Theme Description Best For
DefaultTheme Classic professional look Business documents, reports
ModernLight Clean, contemporary design Marketing materials, proposals
TechPresentation Tech-focused with blue accents Technical documentation, specs
TechDarkMode Dark theme for technical docs Developer documentation, coding guides
AcademicFormal Traditional academic styling Research papers, academic reports
MinimalistClean Minimal, distraction-free Focus documents, minimalist designs

Example: Using Themes

package main

import (
    "log"
    docx "github.com/mmonterroca/docxgo"
    "github.com/mmonterroca/docxgo/domain"
    "github.com/mmonterroca/docxgo/themes"
)

func main() {
    // Create document with theme
    doc := docx.NewDocument()
    themes.TechPresentation.ApplyTo(doc)
    
    // Get theme colors and fonts
    colors := themes.TechPresentation.Colors()
    fonts := themes.TechPresentation.Fonts()
    
    // Use theme settings
    title, _ := doc.AddParagraph()
    title.SetStyle(domain.StyleIDHeading1)
    titleRun, _ := title.AddRun()
    titleRun.AddText("Technical Architecture Document")
    
    body, _ := doc.AddParagraph()
    bodyRun, _ := body.AddRun()
    bodyRun.AddText("This document uses the Tech Presentation theme")
    bodyRun.SetFont(domain.Font{Name: fonts.Body})
    bodyRun.SetColor(colors.Text)
    
    if err := doc.SaveAs("themed.docx"); err != nil {
        log.Fatal(err)
    }
}

Example: Custom Theme

// Clone and customize existing theme
customTheme := themes.ModernLight.Clone()
customColors := themes.ThemeColors{
    Primary:    domain.Color{R: 200, G: 50, B: 50},  // Custom red
    Secondary:  domain.Color{R: 50, G: 50, B: 200},  // Custom blue
    Background: domain.Color{R: 255, G: 255, B: 255},
    Text:       domain.Color{R: 33, G: 33, B: 33},
    // ... other colors
}
customTheme = customTheme.WithColors(customColors)
customTheme.ApplyTo(doc)

📐 Advanced Examples

Example 13: Technical Architecture Documents

New comprehensive example demonstrating:

  • Theme application (Light & Dark modes)
  • PlantUML diagram integration
  • Code blocks with syntax highlighting
  • Professional tables with tech styling
  • Architecture decision records
  • Multiple sections with consistent branding

See examples/13_themes/04_tech_architecture/ for complete implementation.

Features:

  • Generates both light and dark mode versions
  • Integrates with PlantUML server for UML diagrams (Class, Sequence, Component)
  • Styled code blocks with language indicators
  • Technology comparison tables
  • Cover page with metadata
  • Headers and footers with theme colors

🔧 Improvements

Style Management

  • Enhanced built-in style library (40+ styles)
  • Improved style inheritance and customization
  • Better style serialization and persistence

Error Handling

  • More descriptive error messages for theme operations
  • Validation of theme color values
  • Clear feedback on theme application failures

Documentation

  • Complete theme system documentation
  • New example showcasing all theme capabilities
  • Updated API documentation with theme methods

📦 Installation

go get github.com/mmonterroca/docxgo@v2.1.0

🚀 Migration from v2.0.0

v2.1.0 is fully backward compatible with v2.0.0. No breaking changes.

New APIs Added

// Theme package
import "github.com/mmonterroca/docxgo/themes"

// Pre-built themes
themes.DefaultTheme
themes.ModernLight
themes.TechPresentation
themes.TechDarkMode
themes.AcademicFormal
themes.MinimalistClean

// Theme application
theme.ApplyTo(doc)

// Theme properties
colors := theme.Colors()
fonts := theme.Fonts()
spacing := theme.Spacing()

// Customization
customTheme := theme.Clone()
customTheme = theme.WithColors(newColors)
customTheme = theme.WithFonts(newFonts)
customTheme = theme.WithSpacing(newSpacing)

🐛 Bug Fixes

  • Fixed style preservation when applying themes
  • Corrected font inheritance in themed documents
  • Improved color serialization in OOXML
  • Fixed spacing inconsistencies in themed headings

📊 Examples

All examples from v2.0.0 continue to work, plus:

Example Description Key Features
13_themes/04_tech_architecture Technical documentation Themes, PlantUML, code blocks, tables

Running the New Example

cd examples/13_themes/04_tech_architecture
go run main.go

Generates:

  • tech_architecture_light.docx - Light mode technical document
  • tech_architecture_dark.docx - Dark mode technical document

🔗 Compatibility

  • Go Version: 1.23+
  • OOXML: Office Open XML (ISO/IEC 29500)
  • Microsoft Word: 2007+ (Windows/Mac)
  • LibreOffice: 6.0+ (all platforms)
  • Google Docs: Full compatibility
  • Operating Systems: Linux, macOS, Windows

📚 Documentation

New Documentation

Updated Documentation


🗺️ Roadmap

v2.2.0 (Q1 2026) - Enhanced Reading

  • Complete Phase 10 (Document Reading to 100%)
  • Read headers/footers from existing documents
  • Read images and complex tables
  • Comments and change tracking

v2.3.0 (Q2 2026) - Advanced Content

  • Custom XML parts
  • Advanced drawing shapes
  • Enhanced image manipulation
  • Content controls

See docs/IMPLEMENTATION_STATUS.md for detailed roadmap.


🙏 Credits

v2.1.0 Theme System: @mmonterroca

Contributors: See CONTRIBUTORS file


📄 License

MIT License - See LICENSE file for details.


🎉 Thank You!

Thank you for using go-docx v2.1.0! We're excited to see the beautiful themed documents you create.

If you find this library useful, please:

  • ⭐ Star the repository on GitHub
  • 📣 Share with your colleagues
  • 🐛 Report issues you encounter
  • 💡 Suggest features you'd like to see

Happy theming! 🎨

v2.0.0 - Production Stable Release

29 Oct 20:51

Choose a tag to compare

Release Notes - v2.0.0 (Stable)

🎉 go-docx v2.0.0 - Production Ready Release

Release Date: October 29, 2025

We're excited to announce v2.0.0 stable, the production-ready release of go-docx! This version includes all features from the beta release plus major new capabilities for reading and modifying existing documents.

🆕 What's New Since Beta

🚀 Phase 10: Document Reading (NEW!)

The biggest addition to v2.0.0 is full support for reading and modifying existing .docx files:

  • Open existing documents - docx.OpenDocument("file.docx")
  • Read document structure - Access paragraphs, runs, tables, and styles
  • Modify existing content - Edit text, change formatting, update table cells
  • Preserve document styles - Maintains Title, Subtitle, Headings, Quote, Normal styles
  • Add new content - Insert new paragraphs, runs, and sections into existing documents
  • Round-trip capability - Create → Save → Open → Modify → Save workflow

Example: Read and Modify Documents

package main

import (
    "log"
    docx "github.com/mmonterroca/docxgo"
)

func main() {
    // Open existing document
    doc, err := docx.OpenDocument("template.docx")
    if err != nil {
        log.Fatal(err)
    }
    
    // Read and modify existing content
    paragraphs := doc.Paragraphs()
    for _, para := range paragraphs {
        runs := para.Runs()
        for _, run := range runs {
            if run.Text() == "PLACEHOLDER" {
                run.SetText("Updated Value")
                run.SetBold(true)
                run.SetColor(docx.Blue)
            }
        }
    }
    
    // Add new content
    newPara, _ := doc.AddParagraph()
    newRun, _ := newPara.AddRun()
    newRun.SetText("This paragraph was added by the reader")
    
    // Save modified document
    if err := doc.SaveAs("modified.docx"); err != nil {
        log.Fatal(err)
    }
}

See examples/12_read_and_modify/ for complete examples.

🐛 Critical Bug Fixes

  • Fixed style preservation - Paragraph styles (Title, Subtitle, Heading1-9, Quote, Normal, ListParagraph) are now correctly preserved when reading and modifying documents
  • Fixed README API examples - Corrected all Quick Start examples to show accurate API signatures and usage patterns
  • Enhanced example 12 - Now demonstrates both editing existing content AND adding new content

📚 Documentation Improvements

  • Updated README.md - Fixed incorrect API examples, separated Simple API vs Builder API clearly
  • Added Option 3 - New Quick Start section showing document reading/modification workflow
  • Updated implementation status - Phase 10 now marked as "60% complete - core features working"
  • Corrected example count - All documentation now references 11 working examples (was 9)

✨ Complete Feature List

Document Structure

  • Document Management - Create, open, read, modify, and save .docx files
  • Section Support - Multiple sections with independent page settings
  • Headers & Footers - Per-section headers/footers with first-page and odd/even variants
  • Page Layout - Configurable page sizes, orientations, margins, and columns
  • Fields - TOC, page numbers, hyperlinks, dates, and custom fields

Content Creation

  • Paragraphs - Full formatting with alignment, indentation, spacing, and styles
  • Text Runs - Bold, italic, underline, colors, fonts, sizes, highlights
  • Advanced Tables - Cell merging (colspan/rowspan), vertical alignment, shading, borders, 8 built-in styles
  • Images - Inline and floating images (9 formats: PNG, JPEG, GIF, BMP, TIFF, SVG, WEBP, ICO, EMF)
  • Styles - 40+ built-in Word styles (Normal, Heading1-9, Title, Subtitle, Quote, etc.)

Architecture

  • Domain-Driven Design - Clean separation of concerns (domain, internal, pkg)
  • Error Handling - Comprehensive error types with context and validation
  • Type Safety - Strong typing throughout, no interface{}
  • Thread Safety - Concurrent access supported with RWMutex
  • Memory Efficient - Streaming ZIP writer, optimized serialization

Developer Experience

  • Two APIs - Simple API (direct interfaces) and Builder API (fluent, chainable)
  • 11 Working Examples - Comprehensive examples covering all major features
  • Excellent Error Handling - Rated EXCELLENT in Phase 11 review
  • 50.7% Test Coverage - Comprehensive unit tests (improvement plan ready → 95%)
  • Zero Linter Warnings - golangci-lint with 30+ linters

📦 Installation

Using go get

go get github.com/mmonterroca/docxgo@v2.0.0

Import in your code

import (
    docx "github.com/mmonterroca/docxgo"
    "github.com/mmonterroca/docxgo/domain"
)

🚀 Quick Start

Option 1: Simple API (Direct Domain Interfaces)

package main

import (
    "log"
    docx "github.com/mmonterroca/docxgo"
)

func main() {
    // Create document
    doc := docx.NewDocument()
    
    // Add paragraph with formatted text
    para, _ := doc.AddParagraph()
    run, _ := para.AddRun()
    run.SetText("Hello, World!")
    run.SetBold(true)
    run.SetColor(docx.Red)
    
    // Save document
    if err := doc.SaveAs("simple.docx"); err != nil {
        log.Fatal(err)
    }
}

Option 2: Builder API (Fluent, Chainable - Recommended)

package main

import (
    "log"
    docx "github.com/mmonterroca/docxgo"
    "github.com/mmonterroca/docxgo/domain"
)

func main() {
    // Create builder with options
    builder := docx.NewDocumentBuilder(
        docx.WithTitle("My Report"),
        docx.WithAuthor("John Doe"),
        docx.WithDefaultFont("Calibri"),
        docx.WithDefaultFontSize(22), // 11pt in half-points
        docx.WithPageSize(docx.A4),
        docx.WithMargins(docx.NormalMargins),
    )
    
    // Add content using fluent API
    builder.AddParagraph().
        Text("Project Report").
        Bold().
        FontSize(16).
        Color(docx.Blue).
        Alignment(domain.AlignmentCenter).
        End()
    
    builder.AddParagraph().
        Text("This is bold text").Bold().
        Text(" and this is ").
        Text("colored text").Color(docx.Red).FontSize(14).
        End()
    
    // Build and save
    doc, err := builder.Build()
    if err != nil {
        log.Fatal(err)
    }
    
    if err := doc.SaveAs("report.docx"); err != nil {
        log.Fatal(err)
    }
}

Option 3: Read and Modify Existing Documents 🆕

package main

import (
    "log"
    docx "github.com/mmonterroca/docxgo"
)

func main() {
    // Open existing document
    doc, err := docx.OpenDocument("template.docx")
    if err != nil {
        log.Fatal(err)
    }
    
    // Modify existing content
    paragraphs := doc.Paragraphs()
    for _, para := range paragraphs {
        runs := para.Runs()
        for _, run := range runs {
            if run.Text() == "PLACEHOLDER" {
                run.SetText("Updated Value")
                run.SetBold(true)
            }
        }
    }
    
    // Add new content
    newPara, _ := doc.AddParagraph()
    newRun, _ := newPara.AddRun()
    newRun.SetText("Added by the reader")
    
    // Save modified document
    if err := doc.SaveAs("modified.docx"); err != nil {
        log.Fatal(err)
    }
}

📖 Examples

See examples/ directory for 11 comprehensive examples:

Example Description Key Features
01_basic Simple document creation Document, paragraph, run basics
02_intermediate Formatted content Font styles, colors, alignment
03_toc Table of Contents TOC generation, headings, bookmarks
04_fields Dynamic fields Page numbers, dates, hyperlinks
05_styles Paragraph styles Built-in Word styles (40+ styles)
06_sections Multi-section documents Headers, footers, page setup
07_advanced Complex layouts Multiple sections, page breaks
08_images Image insertion 9 formats, inline/floating positioning
09_advanced_tables Table features Cell merging, nested tables, 8 styles
11_multi_section Section management Different layouts per section
12_read_and_modify 🆕 Document reading Open, read, modify, save workflow

Running Examples

cd examples/01_basic
go run main.go

# Or run all examples at once
cd examples
bash run_all_examples.sh

All examples generate valid .docx files that open correctly in Microsoft Word, LibreOffice, and Google Docs.


⚠️ Breaking Changes from v1.x

This is a major version update with complete API redesign. v1.x code will not work with v2.0.0.

Key Differences

v1.x v2.0.0
Concrete types Interface-based design
Silent failures Explicit error returns
Global state Dependency injection
No validation Full input validation
Limited features Comprehensive OOXML support
No error context Rich error context

Migration Resources


🔗 Compatibility

  • Go Version: 1.23+
  • OOXML: Office Open XML (ISO/IEC 29500)
  • Microsoft Word: 2007+ (Windows/Mac)
  • LibreOffice: 6.0+ (all platforms)
  • Google Docs: Full compatibility
  • Operating Systems: Linux, macOS, Windows

📊 Test Coverage & Quality

  • ✅ **50.7% Test...
Read more

v2.0.0-beta - Complete Rewrite

29 Oct 04:59

Choose a tag to compare

Pre-release

Release Notes - v2.0.0-beta

🎉 Major Rewrite: go-docx v2

This is a complete rewrite of go-docx with improved architecture, comprehensive error handling, and full OOXML compliance.

⚠️ Breaking Changes

This is a major version update (v1.x → v2.x) with breaking API changes. Existing code using v1.x will need to be updated.

Migration Guide: See docs/V2_API_GUIDE.md and MIGRATION.md

✨ New Features

Document Structure

  • Section Management: Full support for multiple sections with independent page settings
  • Headers & Footers: Per-section headers/footers with first-page and odd/even variants
  • Page Layout: Configurable page sizes, orientations, margins, and columns
  • Fields Support: TOC, page numbers, hyperlinks, dates, and custom fields

Content Creation

  • Advanced Tables: Cell merging (colspan/rowspan), vertical alignment, shading, borders
  • Images: Inline and floating images with precise positioning
  • Styles: Built-in Word styles (Normal, Heading1-9, Title, etc.) with custom style support
  • Rich Text: Bold, italic, underline, colors, fonts, sizes, highlights

Architecture

  • Domain-Driven Design: Clean separation of domain, serialization, and infrastructure
  • Error Handling: Comprehensive error types with context and validation
  • Type Safety: Strong typing throughout with proper interfaces
  • Memory Efficient: Streaming ZIP writer, optimized serialization

🐛 Bug Fixes

  • Fixed character encoding issues in XML serialization
  • Corrected relationship ID management for images and hyperlinks
  • Resolved section break serialization order
  • Fixed table cell border rendering
  • Corrected bookmark generation for TOC functionality

📚 Documentation

  • Complete API documentation with examples
  • 11 working examples covering all major features
  • Migration guide from v1.x
  • Architecture documentation
  • Error handling patterns

🔧 Developer Experience

  • CI/CD: GitHub Actions with golangci-lint v2.5.0, tests, and examples validation
  • Code Quality: Strict linting for production code, lenient for examples
  • Testing: Comprehensive unit tests with >80% coverage
  • Examples: All examples include README and validate against Word

📦 Installation

go get github.com/mmonterroca/docxgo@v2.0.0-beta

🚀 Quick Start

package main

import (
    "github.com/mmonterroca/docxgo"
    "github.com/mmonterroca/docxgo/domain"
)

func main() {
    doc := docx.NewDocument()
    
    para, _ := doc.AddParagraph()
    run, _ := para.AddRun()
    run.SetText("Hello, World!")
    run.SetBold(true)
    run.SetFontSize(14) // points
    
    doc.SaveAs("hello.docx")
}

📖 Examples

See examples/ directory:

  • 01_basic - Simple document creation
  • 02_intermediate - Paragraphs, runs, formatting
  • 03_toc - Table of Contents
  • 04_fields - Page numbers, dates, hyperlinks
  • 05_styles - Built-in and custom styles
  • 06_sections - Multi-section documents with headers/footers
  • 07_advanced - Complex layouts
  • 08_images - Image insertion and positioning
  • 09_advanced_tables - Table features (merging, styling)
  • 11_multi_section - Multiple sections with different layouts

🔗 Compatibility

  • Go Version: 1.23+
  • OOXML: Office Open XML (ISO/IEC 29500)
  • Word Compatibility: Microsoft Word 2007+, LibreOffice, Google Docs

🙏 Credits

Based on the original fumiama/go-docx library.
Completely rewritten with new architecture and features by @mmonterroca.

📄 License

MIT License - See LICENSE file for details.

🐛 Known Issues

  • TOC requires manual "Update Field" in Word (F9) - inherent OOXML limitation
  • Complex table borders may require fine-tuning
  • Some advanced Word features not yet implemented (see roadmap)

🗺️ Roadmap

See docs/IMPLEMENTATION_STATUS.md for planned features.


Full Changelog: v1.0.0...v2.0.0-beta