godocx

package module
v1.8.3 Latest Latest
Warning

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

Go to latest
Published: Mar 2, 2026 License: MIT Imports: 19 Imported by: 0

README

DOCX Updater

Go Version

A powerful Go library for programmatically manipulating Microsoft Word (DOCX) documents. Update charts, insert tables, add paragraphs, generate captions, and more—all with a clean, idiomatic Go API.

Features

🎯 Document Content

  • Paragraphs: Styled text with headings (H1–H9), alignment, lists, and anchor positioning
  • Tables: Formatted tables with custom styles, borders, row heights, and cell merging
  • Images: Add images with automatic proportional sizing and flexible positioning
  • Hyperlinks & Bookmarks: External URLs, internal links, and bookmark management
  • Lists: Bullet and numbered lists with nesting support

📊 Charts

  • Chart Updates: Modify existing chart data with automatic Excel workbook synchronization
  • Chart Insertion: Create bar, column, line, pie, area, and scatter charts from scratch
  • Scatter Charts: Full XValues support for true scatter/XY data
  • Multi-Chart Workflows: Insert multiple charts programmatically
  • Read Chart Data: Extract existing chart categories and series

📝 Document Structure

  • Table of Contents: Generate automatic TOC using Word field codes, with update-on-open support
  • Page & Section Breaks: Control document flow with page and section breaks
  • Page Layout: Configure page sizes, orientation, and margins per section
  • Headers & Footers: Professional headers and footers with page numbering
  • Page Numbers: Control starting page number and format (decimal, roman, letters)

Styles & Formatting

  • Custom Styles: Create paragraph and character styles with full formatting control
  • Text Watermarks: Add diagonal or horizontal text watermarks via VML shapes
  • Auto-Captions: Generate auto-numbered captions using Word's SEQ fields

📎 Collaboration & Review

  • Comments: Add and read document comments with author and initials
  • Track Changes: Insert text with revision tracking (insertions and deletions)
  • Footnotes & Endnotes: Add scholarly footnotes and endnotes with reference markers

🔧 Operations

  • Text Find & Replace: Search and replace with regex support
  • Read Operations: Extract text from paragraphs, tables, headers, and footers
  • Delete Operations: Remove paragraphs, tables, images, and charts by index
  • Update Operations: Modify existing table cells
  • Count Operations: Get counts of paragraphs, tables, images, and charts
  • Document Properties: Full CRUD for core, app, and custom metadata (title, author, status, template, statistics, custom key-value pairs)

🛠️ Advanced

  • Blank Document Creation: Create documents from scratch with NewBlank() — no template file needed
  • Template Upload: Load templates from raw bytes with NewFromBytes() — ideal for web uploads and API payloads
  • io.Reader/io.Writer support: In-memory document manipulation without disk I/O
  • XML-based chart parsing using Go's encoding/xml
  • Automatic Excel formula range adjustment
  • Full OpenXML relationship and content type management
  • Structured error types for better error handling
  • Golden file tests for XML output verification

Installation

go get github.com/falcomza/go-docx

Quick Start

package main

import (
    "log"
    godocx "github.com/falcomza/go-docx"
)

func main() {
    // Choose one constructor:
    u, err := godocx.New("template.docx")       // From existing file
    // u, err := godocx.NewBlank()               // From scratch (no template)
    // u, err := godocx.NewFromBytes(data)       // From raw bytes (upload/API)
    // u, err := godocx.NewFromReader(reader)    // From io.Reader
    if err != nil {
        log.Fatal(err)
    }
    defer u.Cleanup()

    // Update a chart
    chartData := godocx.ChartData{
        Categories: []string{"Q1", "Q2", "Q3", "Q4"},
        Series: []godocx.SeriesData{
            {Name: "Revenue", Values: []float64{100, 150, 120, 180}},
            {Name: "Costs", Values: []float64{80, 90, 85, 95}},
        },
    }
    u.UpdateChart(1, chartData)

    // Add a table
    u.InsertTable(godocx.TableOptions{
        Columns: []godocx.ColumnDefinition{
            {Title: "Product"},
            {Title: "Sales"},
            {Title: "Growth"},
        },
        Rows: [][]string{
            {"Product A", "$1.2M", "+15%"},
            {"Product B", "$980K", "+8%"},
        },
        TableStyle: godocx.TableStyleGridAccent1,
        Position:   godocx.PositionEnd,
        HeaderBold: true,
    })

    // Save result
    if err := u.Save("output.docx"); err != nil {
        log.Fatal(err)
    }
}

Usage Examples

Updating Chart Data
u, _ := godocx.New("template.docx")
defer u.Cleanup()

data := godocx.ChartData{
    Categories: []string{"Jan", "Feb", "Mar", "Apr"},
    Series: []godocx.SeriesData{
        {Name: "Sales", Values: []float64{250, 300, 275, 350}},
    },
}

u.UpdateChart(1, data) // Update first chart (1-based index)
u.Save("updated.docx")
Inserting Charts

Create charts from scratch, including scatter charts with custom X values:

u, _ := godocx.New("document.docx")
defer u.Cleanup()

// Column chart
u.InsertChart(godocx.ChartOptions{
    Title:      "Quarterly Revenue",
    ChartKind:  godocx.ChartKindColumn,
    Position:   godocx.PositionEnd,
    Categories: []string{"Q1", "Q2", "Q3", "Q4"},
    Series: []godocx.SeriesOptions{
        {Name: "2025", Values: []float64{100, 120, 110, 130}},
        {Name: "2026", Values: []float64{110, 130, 125, 145}},
    },
})

// Scatter chart with custom X values
u.InsertChart(godocx.ChartOptions{
    Title:     "Correlation Analysis",
    ChartKind: godocx.ChartKindScatter,
    Position:  godocx.PositionEnd,
    ScatterChartOptions: &godocx.ScatterChartOptions{
        ScatterStyle: "smoothMarker",
    },
    Categories: []string{"Point 1", "Point 2", "Point 3"},
    Series: []godocx.SeriesOptions{
        {
            Name:    "Dataset A",
            Values:  []float64{10, 25, 40},
            XValues: []float64{1.5, 3.0, 4.5}, // Custom X values
        },
    },
})

u.Save("with_charts.docx")

Supported chart types: ChartKindColumn (vertical bars), ChartKindBar (horizontal bars), ChartKindLine, ChartKindPie, ChartKindArea, ChartKindScatter

Note: ChartKindColumn and ChartKindBar are distinct constants — Column renders vertically (the default bar chart orientation) while Bar renders horizontally. Both emit <c:barChart> XML with the appropriate barDir attribute.

Note: ChartData / SeriesData are used when updating existing charts (UpdateChart), while ChartOptions / SeriesOptions are used when inserting new charts (InsertChart).

Creating Tables
u, _ := godocx.New("document.docx")
defer u.Cleanup()

u.InsertTable(godocx.TableOptions{
    Columns: []godocx.ColumnDefinition{
        {Title: "Product", Width: 2000, Bold: true},
        {Title: "Q1", Width: 1200},
        {Title: "Q2", Width: 1200},
    },
    Rows: [][]string{
        {"Product A", "$120K", "$135K"},
        {"Product B", "$98K", "$105K"},
    },
    TableStyle: godocx.TableStyleGridAccent1,
    Position:   godocx.PositionEnd,
    HeaderBold: true,
    RowHeight:  280,
})

// Update an existing cell
u.UpdateTableCell(1, 2, 3, "$140K") // table 1, row 2, col 3

// Merge cells horizontally (columns 1-3 in row 1)
u.MergeTableCellsHorizontal(1, 1, 1, 3)

// Merge cells vertically (rows 1-3 in column 1)
u.MergeTableCellsVertical(1, 1, 3, 1)

u.Save("with_table.docx")
Adding Paragraphs
u, _ := godocx.New("document.docx")
defer u.Cleanup()

u.AddHeading(1, "Executive Summary", godocx.PositionEnd)
u.AddHeading(2, "Background", godocx.PositionEnd)
u.AddHeading(3, "Scope", godocx.PositionEnd)
u.AddHeading(4, "Methodology – Data Collection", godocx.PositionEnd) // H1–H9 supported

u.AddText("This quarter showed strong growth.", godocx.PositionEnd)

u.InsertParagraph(godocx.ParagraphOptions{
    Text:      "Important: Review required",
    Bold:      true,
    Italic:    true,
    Alignment: godocx.ParagraphAlignCenter,
    Position:  godocx.PositionEnd,
})

// Anchor-based positioning (works across split Word runs)
u.InsertParagraph(godocx.ParagraphOptions{
    Text:     "Follow-up details",
    Position: godocx.PositionAfterText,
    Anchor:   "Executive Summary",
})

// Newlines and tabs are emitted as <w:br/> and <w:tab/>
u.InsertParagraph(godocx.ParagraphOptions{
    Text:     "Line 1\nLine 2\tTabbed",
    Position: godocx.PositionEnd,
})

u.Save("with_paragraphs.docx")
Table of Contents

Generate an automatic Table of Contents using Word field codes:

u, _ := godocx.New("document.docx")
defer u.Cleanup()

// Insert TOC at the beginning
u.InsertTOC(godocx.TOCOptions{
    Title:         "Table of Contents",
    OutlineLevels: "1-3",
    Position:      godocx.PositionBeginning,
})

// Add headings (these will appear in the TOC)
u.AddHeading(1, "Chapter 1: Introduction", godocx.PositionEnd)
u.AddText("Introduction content...", godocx.PositionEnd)
u.AddHeading(2, "1.1 Background", godocx.PositionEnd)
u.AddText("Background content...", godocx.PositionEnd)

// Mark TOC for update (Word recalculates on open)
u.UpdateTOC()

// Read existing TOC entries
entries, _ := u.GetTOCEntries()
for _, entry := range entries {
    fmt.Printf("Level %d: %s\n", entry.Level, entry.Text)
}

u.Save("with_toc.docx")
Custom Styles

Create and apply custom paragraph and character styles:

u, _ := godocx.New("document.docx")
defer u.Cleanup()

u.AddStyles([]godocx.StyleDefinition{
    {
        ID:         "DocTitle",
        Name:       "Document Title",
        Type:       godocx.StyleTypeParagraph,
        BasedOn:    "Normal",
        FontFamily: "Calibri",
        FontSize:   56, // half-points (56 = 28pt)
        Color:      "1F4E79",
        Bold:       true,
        Alignment:  godocx.ParagraphAlignCenter,
        SpaceAfter: 240,
    },
    {
        ID:     "Highlight",
        Name:   "Strong Emphasis",
        Type:   godocx.StyleTypeCharacter,
        Bold:   true,
        Italic: true,
        Color:  "C00000",
    },
})

// Use the custom style
u.InsertParagraph(godocx.ParagraphOptions{
    Text:     "My Document Title",
    Style:    "DocTitle",
    Position: godocx.PositionBeginning,
})

u.Save("with_styles.docx")
Watermarks

Add text watermarks to documents:

u, _ := godocx.New("document.docx")
defer u.Cleanup()

u.SetTextWatermark(godocx.WatermarkOptions{
    Text:       "CONFIDENTIAL",
    FontFamily: "Calibri",
    Color:      "C0C0C0",
    Opacity:    0.3,
    Diagonal:   true, // 315-degree rotation
})

u.Save("watermarked.docx")
Page Numbers

Control page numbering format and starting number:

u, _ := godocx.New("document.docx")
defer u.Cleanup()

u.SetPageNumber(godocx.PageNumberOptions{
    Start:  1,
    Format: godocx.PageNumDecimal, // also: PageNumUpperRoman, PageNumLowerRoman, etc.
})

u.Save("with_page_numbers.docx")
Footnotes and Endnotes
u, _ := godocx.New("document.docx")
defer u.Cleanup()

u.AddText("The experiment showed significant results.", godocx.PositionEnd)

// Insert footnote at anchor text
u.InsertFootnote(godocx.FootnoteOptions{
    Text:   "Based on data collected in Q3 2026.",
    Anchor: "significant results",
})

// Insert endnote at anchor text
u.InsertEndnote(godocx.EndnoteOptions{
    Text:   "See full methodology in Appendix A.",
    Anchor: "experiment",
})

u.Save("with_notes.docx")
Comments

Add and read document comments:

u, _ := godocx.New("document.docx")
defer u.Cleanup()

u.AddText("Revenue grew 15% this quarter.", godocx.PositionEnd)

u.InsertComment(godocx.CommentOptions{
    Text:     "Please verify this figure with accounting.",
    Author:   "Jane Reviewer",
    Initials: "JR",
    Anchor:   "grew 15%",
})

// Read existing comments
comments, _ := u.GetComments()
for _, c := range comments {
    fmt.Printf("%s: %s\n", c.Author, c.Text)
}

u.Save("with_comments.docx")
Track Changes

Insert and delete text with revision tracking:

u, _ := godocx.New("document.docx")
defer u.Cleanup()

// Insert tracked text (green underline in Word)
u.InsertTrackedText(godocx.TrackedInsertOptions{
    Text:     "This paragraph was added during review.",
    Author:   "Jane Reviewer",
    Date:     time.Now(),
    Position: godocx.PositionEnd,
    Bold:     true,
})

// Mark existing text as deleted (red strikethrough in Word)
u.DeleteTrackedText(godocx.TrackedDeleteOptions{
    Anchor: "paragraph to be removed",
    Author: "Jane Reviewer",
    Date:   time.Now(),
})

u.Save("with_tracked_changes.docx")
Delete Operations

Remove content from documents:

u, _ := godocx.New("document.docx")
defer u.Cleanup()

// Delete paragraphs containing specific text
count, _ := u.DeleteParagraphs("draft", godocx.DeleteOptions{MatchCase: false})
fmt.Printf("Deleted %d paragraphs\n", count)

// Delete by index (1-based)
u.DeleteTable(2)  // Remove 2nd table
u.DeleteImage(1)  // Remove 1st image
u.DeleteChart(1)  // Remove 1st chart

// Count operations
tableCount, _ := u.GetTableCount()
paraCount, _ := u.GetParagraphCount()
imageCount, _ := u.GetImageCount()
chartCount, _ := u.GetChartCount()

u.Save("cleaned.docx")
io.Reader / io.Writer Support

Work with documents in memory without disk I/O:

import (
    "bytes"
    "os"
    godocx "github.com/falcomza/go-docx"
)

// Open from io.Reader (e.g., HTTP upload, S3 object, etc.)
file, _ := os.Open("template.docx")
defer file.Close()

u, _ := godocx.NewFromReader(file)
defer u.Cleanup()

u.AddText("Added via io.Reader", godocx.PositionEnd)

// Save to io.Writer (e.g., HTTP response, S3 upload, etc.)
var buf bytes.Buffer
u.SaveToWriter(&buf)

// buf.Bytes() contains the complete DOCX file
os.WriteFile("output.docx", buf.Bytes(), 0o644)
Inserting Images
u, _ := godocx.New("document.docx")
defer u.Cleanup()

// Width only — height calculated proportionally
u.InsertImage(godocx.ImageOptions{
    Path:     "images/logo.png",
    Width:    400,
    AltText:  "Company Logo",
    Position: godocx.PositionEnd,
})

// With auto-numbered caption
u.InsertImage(godocx.ImageOptions{
    Path:     "images/chart.png",
    Width:    500,
    Position: godocx.PositionEnd,
    Caption: &godocx.CaptionOptions{
        Type:        godocx.CaptionFigure,
        Description: "Q1 Sales Performance",
        AutoNumber:  true,
    },
})

u.Save("with_images.docx")

Proportional sizing: Specify only Width (height auto-calculated), only Height (width auto-calculated), both (used as-is), or neither (actual image dimensions). Supported formats: PNG, JPEG, GIF, BMP, TIFF.

Page and Section Breaks
u, _ := godocx.New("document.docx")
defer u.Cleanup()

u.InsertPageBreak(godocx.BreakOptions{
    Position: godocx.PositionEnd,
})

u.InsertSectionBreak(godocx.BreakOptions{
    Position:    godocx.PositionEnd,
    SectionType: godocx.SectionBreakNextPage,
    PageLayout:  godocx.PageLayoutA3Landscape(),
})

u.Save("with_breaks.docx")

Section break types: SectionBreakNextPage, SectionBreakContinuous, SectionBreakEvenPage, SectionBreakOddPage

Layout helpers: PageLayoutLetterPortrait(), PageLayoutLetterLandscape(), PageLayoutA4Portrait(), PageLayoutA4Landscape(), PageLayoutA3Portrait(), PageLayoutA3Landscape(), PageLayoutLegalPortrait()

u, _ := godocx.New("document.docx")
defer u.Cleanup()

// External hyperlink
u.InsertHyperlink("Visit GitHub", "https://github.com/falcomza/go-docx", godocx.HyperlinkOptions{
    Position:  godocx.PositionEnd,
    Color:     "0563C1",
    Underline: true,
    Tooltip:   "Open repository",
})

// Create bookmark with heading text
u.CreateBookmarkWithText("summary", "Executive Summary", godocx.BookmarkOptions{
    Position: godocx.PositionEnd,
    Style:    godocx.StyleHeading1,
})

// Internal link to bookmark
u.InsertInternalLink("Go to Summary", "summary", godocx.HyperlinkOptions{
    Position:  godocx.PositionBeginning,
    Color:     "0563C1",
    Underline: true,
})

u.Save("with_links.docx")
Headers and Footers
u, _ := godocx.New("document.docx")
defer u.Cleanup()

u.SetHeader(godocx.HeaderFooterContent{
    LeftText:   "Company Name",
    CenterText: "Confidential Report",
    RightText:  "Feb 2026",
}, godocx.DefaultHeaderOptions())

u.SetFooter(godocx.HeaderFooterContent{
    CenterText:       "Page ",
    PageNumber:       true,
    PageNumberFormat: "X of Y",
}, godocx.DefaultFooterOptions())

u.Save("with_headers_footers.docx")
Text Find & Replace
u, _ := godocx.New("document.docx")
defer u.Cleanup()

opts := godocx.DefaultReplaceOptions()
count, _ := u.ReplaceText("{{name}}", "John Doe", opts)

// Regex replacement
pattern := regexp.MustCompile(`\d{3}-\d{3}-\d{4}`)
count, _ = u.ReplaceTextRegex(pattern, "[REDACTED]", opts)

u.Save("replaced.docx")
Read Operations
u, _ := godocx.New("document.docx")
defer u.Cleanup()

text, _ := u.GetText()                // All document text
paragraphs, _ := u.GetParagraphText()  // Text by paragraphs
tables, _ := u.GetTableText()          // Text from tables

// Find text with context
opts := godocx.DefaultFindOptions()
matches, _ := u.FindText("TODO:", opts)
for _, m := range matches {
    fmt.Printf("Paragraph %d: %s\n", m.Paragraph, m.Text)
}
Creating Documents from Scratch

Create a blank document without any template file:

u, _ := godocx.NewBlank()
defer u.Cleanup()

u.AddHeading(1, "Report Title", godocx.PositionEnd)
u.AddText("Created entirely from scratch.", godocx.PositionEnd)
u.Save("from_scratch.docx")

Load a template from raw bytes (e.g., HTTP upload or database):

data, _ := io.ReadAll(uploadedFile)
u, _ := godocx.NewFromBytes(data)
defer u.Cleanup()

u.AddText("Added to uploaded template.", godocx.PositionEnd)
u.Save("from_upload.docx")
Document Properties

Set and read core, application, and custom properties — matching Word's File → Info → Properties dialog:

u, _ := godocx.NewBlank()
defer u.Cleanup()

// Core properties (Summary tab)
u.SetCoreProperties(godocx.CoreProperties{
    Title:         "Q4 Report",
    Creator:       "Finance Dept",
    Subject:       "Quarterly Financials",
    Keywords:      "finance, quarterly, report",
    ContentStatus: "Draft", // "Draft", "Final", "Reviewed", etc.
})

// Application properties (Statistics tab + template assignment)
u.SetAppProperties(godocx.AppProperties{
    Company:              "ACME Corp",
    Manager:              "Jane Smith",
    Template:             "Corporate_Report.dotm",
    HyperlinkBase:        "https://docs.acme.com",
    Pages:                25,
    Words:                7500,
    Characters:           42000,
    CharactersWithSpaces: 49500,
    Lines:                350,
    Paragraphs:           80,
    TotalTime:            120,
})

// Custom properties (Custom tab) — typed values
u.SetCustomProperties([]godocx.CustomProperty{
    {Name: "Department", Value: "Engineering"},
    {Name: "ProjectCode", Value: "PRJ-2026"},
    {Name: "Budget", Value: 150000.50},
    {Name: "Approved", Value: true},
    {Name: "Deadline", Value: time.Date(2026, 12, 31, 0, 0, 0, 0, time.UTC)},
})

// Read properties back
coreProps, _ := u.GetCoreProperties()
fmt.Println(coreProps.Title, coreProps.ContentStatus)

appProps, _ := u.GetAppProperties()
fmt.Println(appProps.Company, appProps.Template, appProps.Pages)

customProps, _ := u.GetCustomProperties()
for _, p := range customProps {
    fmt.Printf("%s = %v\n", p.Name, p.Value)
}

u.Save("with_properties.docx")
Lists
u, _ := godocx.New("document.docx")
defer u.Cleanup()

u.AddBulletList([]string{
    "First item",
    "Second item",
    "Third item",
}, 0, godocx.PositionEnd)

u.AddNumberedList([]string{
    "Step 1: Planning",
    "Step 2: Development",
    "Step 3: Testing",
}, 0, godocx.PositionEnd)

u.Save("with_lists.docx")

API Overview

Core Operations
Method Description
New(filepath string) Open DOCX file from disk
NewBlank() Create blank document from scratch (no template needed)
NewFromBytes(data []byte) Create from raw bytes (upload/API/database)
NewFromReader(r io.Reader) Open DOCX from any io.Reader
Save(outputPath string) Save document to disk
SaveToWriter(w io.Writer) Save document to any io.Writer
Cleanup() Clean up temporary files
Paragraph Operations
Method Description
InsertParagraph(opts ParagraphOptions) Insert styled paragraph
InsertParagraphs(paragraphs []ParagraphOptions) Insert multiple paragraphs
AddHeading(level, text, position) Insert heading at level 1–9 (matches Word's built-in Heading 1 – Heading 9 styles)
AddText(text, position) Insert normal text
AddBulletItem(text, level, position) Insert bullet item
AddBulletList(items, level, position) Insert bullet list
AddNumberedItem(text, level, position) Insert numbered item
AddNumberedList(items, level, position) Insert numbered list
Table Operations
Method Description
InsertTable(opts TableOptions) Insert formatted table
UpdateTableCell(table, row, col, value) Modify existing cell
MergeTableCellsHorizontal(table, row, startCol, endCol) Merge cells across columns
MergeTableCellsVertical(table, startRow, endRow, col) Merge cells across rows
Chart Operations
Method Description
InsertChart(opts ChartOptions) Create new chart
UpdateChart(index, data) Update existing chart data
GetChartCount() Count charts in document
GetChartData(chartIndex) Read chart categories and series
Table of Contents
Method Description
InsertTOC(opts TOCOptions) Insert TOC field
UpdateTOC() Mark TOC for recalculation on open
GetTOCEntries() Parse existing TOC entries
Styles
Method Description
AddStyle(def StyleDefinition) Add single custom style
AddStyles(defs []StyleDefinition) Add multiple custom styles
Comments
Method Description
InsertComment(opts CommentOptions) Add comment at anchor text
GetComments() Read all document comments
Track Changes
Method Description
InsertTrackedText(opts TrackedInsertOptions) Insert text with revision tracking
DeleteTrackedText(opts TrackedDeleteOptions) Mark text as tracked deletion
Footnotes & Endnotes
Method Description
InsertFootnote(opts FootnoteOptions) Add footnote at anchor text
InsertEndnote(opts EndnoteOptions) Add endnote at anchor text
Image Operations
Method Description
InsertImage(opts ImageOptions) Insert image with proportional sizing
Method Description
InsertHyperlink(text, url, opts) Insert external hyperlink
InsertInternalLink(text, bookmark, opts) Insert internal link
CreateBookmark(name, opts) Create empty bookmark
CreateBookmarkWithText(name, text, opts) Create bookmark with content
WrapTextInBookmark(name, anchorText) Wrap existing text in bookmark
Text Operations
Method Description
ReplaceText(old, new, opts) Replace text occurrences
ReplaceTextRegex(pattern, replacement, opts) Replace using regex
GetText() Extract all document text
GetParagraphText() Extract text by paragraphs
GetTableText() Extract text from tables
FindText(pattern, opts) Find text with context
Delete Operations
Method Description
DeleteParagraphs(text, opts) Delete paragraphs matching text
DeleteTable(index) Delete table by index
DeleteImage(index) Delete image by index
DeleteChart(index) Delete chart by index
Count Operations
Method Description
GetTableCount() Count tables in document
GetParagraphCount() Count paragraphs
GetImageCount() Count images
GetChartCount() Count charts
Page Layout & Formatting
Method Description
SetPageNumber(opts PageNumberOptions) Set page number start and format
SetTextWatermark(opts WatermarkOptions) Add text watermark
SetPageLayout(opts PageLayoutOptions) Set page size and orientation
InsertPageBreak(opts BreakOptions) Insert page break
InsertSectionBreak(opts BreakOptions) Insert section break
Method Description
SetHeader(content, opts) Create/update header
SetFooter(content, opts) Create/update footer
Properties Operations
Method Description
SetCoreProperties(props) Set core metadata (Title, Author, ContentStatus, etc.)
GetCoreProperties() Read core metadata
SetAppProperties(props) Set app metadata (Company, Template, statistics, etc.)
GetAppProperties() Read app metadata
SetCustomProperties(properties) Set custom key-value metadata
GetCustomProperties() Read custom key-value metadata with preserved types
Caption Operations
Method Description
AddCaption(opts CaptionOptions) Insert auto-numbered caption

Project Structure

.
├── chart_updater.go     # Main Updater API, New/Save/io.Reader/io.Writer
├── chart.go             # Chart insertion (column, bar, line, pie, area, scatter)
├── chart_xml.go         # XML manipulation for charts
├── chart_read.go        # Read existing chart data
├── chart_extended.go    # Extended chart types and options
├── excel_handler.go     # Embedded workbook updates
├── table.go             # Table insertion with styles
├── table_update.go      # Update existing table cells
├── merge.go             # Table cell merging (horizontal/vertical)
├── paragraph.go         # Paragraph and text insertion
├── image.go             # Image insertion with proportional sizing
├── toc.go               # Table of Contents generation
├── styles.go            # Custom style definitions
├── watermark.go         # Text watermarks via VML
├── pagenumber.go        # Page number control
├── footnote.go          # Footnotes and endnotes
├── comment.go           # Document comments
├── trackchanges.go      # Revision tracking (insertions/deletions)
├── delete.go            # Delete operations and count queries
├── bookmark.go          # Bookmark management
├── hyperlink.go         # Hyperlinks (external and internal)
├── headerfooter.go      # Headers and footers
├── breaks.go            # Page and section breaks
├── caption.go           # Auto-numbered captions
├── list.go              # Bullet and numbered lists
├── read.go              # Text extraction and search
├── replace.go           # Find and replace operations
├── properties.go        # Document properties
├── helpers.go           # Shared utility functions
├── utils.go             # ZIP and file utilities
├── types.go             # Shared type definitions
├── constants.go         # Constants and enums
├── errors.go            # Structured error types
├── doc.go               # Package-level documentation
├── *_test.go            # Unit and golden file tests
├── examples/            # Example programs
└── LICENSE              # MIT License

Examples

Check the /examples directory for complete working examples:

  • example_all_features.go - Comprehensive demo of every feature
  • example_toc_watermark.go - TOC, watermarks, page numbers, styles, footnotes
  • example_chart_insert.go - Creating charts from scratch
  • example_extended_chart.go - Extended chart options
  • example_bookmarks.go - Bookmark creation and internal navigation
  • example_table.go - Table creation with styling
  • example_table_widths.go - Table column width control
  • example_table_row_heights.go - Table row height control
  • example_table_named_styles.go - Named table styles
  • example_table_orientation.go - Table with page orientation
  • example_paragraph.go - Text and heading insertion
  • example_image.go - Image insertion with proportional sizing
  • example_breaks.go - Page and section breaks
  • example_captions.go - Auto-numbered captions
  • example_lists.go - Bullet and numbered lists
  • example_page_layout.go - Page layout configuration
  • example_properties.go - Document properties
  • example_blank_and_properties.go - Blank document creation and full properties CRUD
  • example_multi_subsystem.go - Combined operations
  • example_with_template.go - Template-based generation
  • example_conditional_cell_colors.go - Conditional cell formatting

Run any example:

go run examples/example_all_features.go template.docx output.docx

Testing

# Run all tests
go test ./...

# Run with verbose output
go test -v ./...

# Run specific test
go test -run TestInsertTable ./...

# Generate coverage report
go test -cover ./...

# Run golden file tests only
go test -run TestGolden ./...

The test suite includes:

  • Unit tests for all public and internal functions
  • Golden file tests that verify XML output against expected strings
  • Validation tests for error handling and edge cases

Requirements

  • Go 1.26 or later
  • No external dependencies (uses only standard library)

How It Works

DOCX files are ZIP archives containing XML files. This library:

  1. Extracts the DOCX archive to a temporary directory
  2. Parses and modifies XML files using Go's encoding/xml and string manipulation
  3. Updates relationships (_rels/*.rels) and content types ([Content_Types].xml)
  4. Manages embedded Excel workbooks for chart data
  5. Re-packages everything into a new DOCX file

Reliability details:

  • All in-place XML writes use an atomic write-then-rename strategy so a crash mid-write never leaves a corrupt file visible to readers
  • The ZIP extractor enforces a 256 MiB per-file cap to guard against zip-bomb payloads
  • XML escaping and unescaping use the stdlib encoding/xml codec throughout (no html package dependency)

Roadmap

  • Chart updates and insertion (column, bar, line, pie, area, scatter)
  • Table insertion with cell merging
  • Paragraph and text insertion with formatting
  • Image insertion with proportional sizing
  • Header/footer manipulation
  • Table of Contents generation
  • Custom styles API
  • Watermarks
  • Page number control
  • Footnotes and endnotes
  • Comments
  • Track changes (insertions and deletions)
  • Delete operations
  • io.Reader/io.Writer support
  • Blank document creation (NewBlank, NewFromBytes)
  • Full properties CRUD (core, app, custom — get and set)
  • Expanded app properties (template, statistics, hyperlink base)
  • Golden file tests
  • Content controls (structured document tags)
  • Digital signatures
  • Performance optimizations for large documents
  • context.Context support for cancellation/timeouts

Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes:

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Write tests for your changes
  4. Commit your changes (git commit -m 'Add amazing feature')
  5. Push to the branch (git push origin feature/amazing-feature)
  6. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

  • Built with Go's standard library
  • Follows OpenXML specifications for DOCX manipulation
  • Inspired by the need for programmatic Word document generation in Go

Support

  • 📫 Report issues on GitHub Issues
  • ⭐ Star this repo if you find it useful
  • 🔧 Contributions and feedback are always welcome

Made with ❤️ by falcomza

Documentation

Overview

Package godocx provides a programmatic API for creating and modifying Microsoft Word (DOCX) documents without requiring Microsoft Office.

Quick Start

u, err := godocx.New("template.docx")
if err != nil {
    log.Fatal(err)
}
defer u.Cleanup()

u.UpdateChart(1, godocx.ChartData{
    Categories: []string{"Q1", "Q2", "Q3", "Q4"},
    Series: []godocx.SeriesData{
        {Name: "Revenue", Values: []float64{100, 150, 120, 180}},
    },
})

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

Architecture

go-docx extracts the DOCX ZIP archive to a temporary directory, manipulates the underlying OpenXML files directly, and repackages on Updater.Save. Call Updater.Cleanup (typically via defer) to remove the temporary directory when done.

Creating Documents

There are four ways to create or open a document:

  • New — opens an existing DOCX file from disk
  • NewBlank — creates a new empty document from scratch (no template needed)
  • NewFromBytes — creates a document from raw bytes (e.g., uploaded template data)
  • NewFromReader — creates a document from an io.Reader

Inserting Content

All Insert* and Add* methods accept an InsertPosition:

Document Properties

Properties correspond to the Info panel and Advanced Properties dialog in Microsoft Word.

The [AppProperties.Template] field assigns a template name (e.g., "Normal.dotm").

Chart Workflow

Use Updater.UpdateChart to replace data in an existing chart template. Use Updater.InsertChart to create a new chart from scratch. Use Updater.GetChartData to read current chart categories and series.

Index

Constants

View Source
const (
	// ChartAnchorIDBase is the base value for anchor IDs in chart drawings
	ChartAnchorIDBase = 0x30000000

	// ChartEditIDBase is the base value for edit IDs in chart drawings
	ChartEditIDBase = 0x0D000000

	// ChartIDIncrement is the increment per chart to ensure ID uniqueness
	ChartIDIncrement = 0x1000
)

OpenXML constants for chart drawings

View Source
const (
	// ImageAnchorIDBase is the base value for anchor IDs in image drawings
	ImageAnchorIDBase = 0x50000000

	// ImageEditIDBase is the base value for edit IDs in image drawings
	ImageEditIDBase = 0x0E000000

	// ImageIDIncrement is the increment per image to ensure ID uniqueness
	ImageIDIncrement = 0x1000

	// EMUsPerInch is the number of English Metric Units (EMUs) per inch
	// 1 inch = 914400 EMUs (used for image sizing in OpenXML)
	EMUsPerInch = 914400

	// DefaultImageDPI is the default DPI for image dimensions
	DefaultImageDPI = 96
)

OpenXML constants for image drawings

View Source
const (
	RelationshipsNS  = "http://schemas.openxmlformats.org/package/2006/relationships"
	OfficeDocumentNS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
	DrawingMLNS      = "http://schemas.openxmlformats.org/drawingml/2006/main"
	ChartNS          = "http://schemas.openxmlformats.org/drawingml/2006/chart"
	SpreadsheetMLNS  = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
)

OpenXML namespace URIs

View Source
const (
	ChartContentType = "application/vnd.openxmlformats-officedocument.drawingml.chart+xml"
	ImageJPEGType    = "image/jpeg"
	ImagePNGType     = "image/png"
	ImageGIFType     = "image/gif"
	ImageBMPType     = "image/bmp"
	ImageTIFFType    = "image/tiff"
)

OpenXML content types

View Source
const (
	BulletListNumID   = 1 // Numbering ID for bullet lists
	NumberedListNumID = 2 // Numbering ID for numbered lists
)

List numbering IDs

View Source
const (
	// US Letter: 8.5" × 11"
	PageWidthLetter  = 12240
	PageHeightLetter = 15840

	// US Legal: 8.5" × 14"
	PageWidthLegal  = 12240
	PageHeightLegal = 20160

	// A4: 210mm × 297mm (8.27" × 11.69")
	PageWidthA4  = 11906
	PageHeightA4 = 16838

	// A3: 297mm × 420mm (11.69" × 16.54")
	PageWidthA3  = 16838
	PageHeightA3 = 23811

	// Tabloid/Ledger: 11" × 17"
	PageWidthTabloid  = 15840
	PageHeightTabloid = 24480

	// Default margin: 1 inch
	MarginDefault = 1440

	// Narrow margin: 0.5 inch
	MarginNarrow = 720

	// Wide margin: 1.5 inch
	MarginWide = 2160

	// Default header/footer margin: 0.5 inch
	MarginHeaderFooterDefault = 720
)

Page size constants in twips (1/1440 inch)

View Source
const FontSizeHalfPointsFactor = 2

FontSizeHalfPointsFactor is the multiplier to convert a font size expressed in typographic points to the half-point units required by the Open XML w:sz and w:szCs attributes (ECMA-376 Part 1 §17.3.2.38).

Variables

This section is empty.

Functions

func FormatCaptionText

func FormatCaptionText(opts CaptionOptions) string

FormatCaptionText formats a caption text for display (without XML) Useful for previewing what the caption will look like

func NewChartNotFoundError

func NewChartNotFoundError(index int) error

NewChartNotFoundError creates an error for when a chart is not found

func NewFileNotFoundError

func NewFileNotFoundError(path string) error

NewFileNotFoundError creates an error for missing files

func NewHeaderFooterError

func NewHeaderFooterError(reason string, err error) error

NewHeaderFooterError creates an error for header/footer operations

func NewHyperlinkError

func NewHyperlinkError(reason string, err error) error

NewHyperlinkError creates an error for hyperlink creation failures

func NewImageFormatError

func NewImageFormatError(format string) error

NewImageFormatError creates an error for unsupported image formats

func NewImageNotFoundError

func NewImageNotFoundError(path string) error

NewImageNotFoundError creates an error for when an image file is not found

func NewInvalidChartDataError

func NewInvalidChartDataError(reason string) error

NewInvalidChartDataError creates an error for invalid chart data

func NewInvalidFileError

func NewInvalidFileError(reason string, err error) error

NewInvalidFileError creates an error for invalid DOCX files

func NewInvalidRegexError

func NewInvalidRegexError(pattern string, err error) error

NewInvalidRegexError creates an error for invalid regex patterns

func NewInvalidURLError

func NewInvalidURLError(url string) error

NewInvalidURLError creates an error for invalid URLs

func NewRelationshipError

func NewRelationshipError(reason string, err error) error

NewRelationshipError creates an error for relationship issues

func NewTextNotFoundError

func NewTextNotFoundError(text string) error

NewTextNotFoundError creates an error for when text is not found in document

func NewValidationError

func NewValidationError(field, reason string) error

NewValidationError creates an error for validation failures

func NewXMLParseError

func NewXMLParseError(file string, err error) error

NewXMLParseError creates an error for XML parsing failures

func NewXMLWriteError

func NewXMLWriteError(file string, err error) error

NewXMLWriteError creates an error for XML writing failures

func ValidateCaptionOptions

func ValidateCaptionOptions(opts *CaptionOptions) error

ValidateCaptionOptions validates caption options

Types

type AppProperties

type AppProperties struct {
	// Company name
	Company string

	// Manager name
	Manager string

	// Application name (typically Microsoft Word)
	Application string

	// AppVersion (e.g., "16.0000")
	AppVersion string

	// Template name (e.g., "Normal.dotm")
	Template string

	// HyperlinkBase is the base URL for relative hyperlinks in the document
	HyperlinkBase string

	// TotalTime is the total editing time in minutes
	TotalTime int

	// Pages is the page count
	Pages int

	// Words is the word count
	Words int

	// Characters is the character count (without spaces)
	Characters int

	// CharactersWithSpaces is the character count including spaces
	CharactersWithSpaces int

	// Lines is the line count
	Lines int

	// Paragraphs is the paragraph count
	Paragraphs int

	// DocSecurity defines the document security level (0=none, 1=password protected,
	// 2=read-only recommended, 4=read-only enforced, 8=locked for annotations)
	DocSecurity int
}

AppProperties represents application-specific document properties

type Axis

type Axis struct {
	Title *AxisTitle `xml:"title,omitempty"`
}

Axis represents a chart axis.

type AxisOptions

type AxisOptions struct {
	// Basic properties
	Title        string // Axis title
	TitleOverlay bool   // Title overlays chart area (default: false)

	// Scale properties
	Min       *float64 // Minimum value (nil for auto)
	Max       *float64 // Maximum value (nil for auto)
	MajorUnit *float64 // Major unit interval (nil for auto)
	MinorUnit *float64 // Minor unit interval (nil for auto)

	// Display properties
	Visible  bool         // Show axis (default: true)
	Position AxisPosition // Axis position

	// Tick marks
	MajorTickMark TickMark // Major tick mark style (default: out)
	MinorTickMark TickMark // Minor tick mark style (default: none)

	// Tick labels
	TickLabelPos TickLabelPosition // Tick label position (default: nextTo)

	// Number format
	NumberFormat string // Number format code (e.g., "0.00", "#,##0")

	// Gridlines
	MajorGridlines bool // Show major gridlines (default: true for value axis)
	MinorGridlines bool // Show minor gridlines (default: false)

	// Crossing
	CrossesAt *float64 // Where axis crosses (nil for auto)
}

AxisOptions defines comprehensive axis customization

type AxisPosition

type AxisPosition string

AxisPosition defines axis position

const (
	AxisPositionBottom AxisPosition = "b" // Bottom
	AxisPositionLeft   AxisPosition = "l" // Left
	AxisPositionRight  AxisPosition = "r" // Right
	AxisPositionTop    AxisPosition = "t" // Top
)

type AxisTitle

type AxisTitle struct {
	Tx struct {
		Rich *struct {
			P struct {
				R struct {
					T string `xml:"t"`
				} `xml:"r"`
			} `xml:"p"`
		} `xml:"rich,omitempty"`
	} `xml:"tx"`
}

AxisTitle represents an axis title.

type BarChartOptions

type BarChartOptions struct {
	Direction  BarDirection // Bar direction (default: col for column)
	Grouping   BarGrouping  // Grouping type (default: clustered)
	GapWidth   int          // Gap between bar groups (0-500, default: 150)
	Overlap    int          // Overlap of bars (-100 to 100, default: 0)
	VaryColors bool         // Vary colors by point (default: false)
}

BarChartOptions defines options specific to bar/column charts

type BarDirection

type BarDirection string

BarDirection defines bar orientation

const (
	BarDirectionColumn BarDirection = "col" // Vertical bars (column chart)
	BarDirectionBar    BarDirection = "bar" // Horizontal bars (bar chart)
)

type BarGrouping

type BarGrouping string

BarGrouping defines how bars are grouped

const (
	BarGroupingClustered      BarGrouping = "clustered"      // Clustered (default)
	BarGroupingStacked        BarGrouping = "stacked"        // Stacked
	BarGroupingPercentStacked BarGrouping = "percentStacked" // 100% stacked
	BarGroupingStandard       BarGrouping = "standard"       // Standard
)

type BookmarkOptions

type BookmarkOptions struct {
	// Position where to insert the bookmark
	Position InsertPosition

	// Anchor text for position-based insertion (for PositionAfterText/PositionBeforeText)
	Anchor string

	// Style to apply to the bookmarked text paragraph
	Style ParagraphStyle

	// Whether the bookmark should be invisible (default: true)
	// Word bookmarks are typically invisible markers
	Hidden bool
}

BookmarkOptions defines options for bookmark creation

func DefaultBookmarkOptions

func DefaultBookmarkOptions() BookmarkOptions

DefaultBookmarkOptions returns bookmark options with sensible defaults

type BorderStyle

type BorderStyle string

BorderStyle defines table border style

const (
	BorderSingle BorderStyle = "single"
	BorderDouble BorderStyle = "double"
	BorderDashed BorderStyle = "dashed"
	BorderDotted BorderStyle = "dotted"
	BorderNone   BorderStyle = "none"
)

type BreakOptions

type BreakOptions struct {
	// Position where to insert the break
	Position InsertPosition

	// Anchor text for position-based insertion (for PositionAfterText/PositionBeforeText)
	Anchor string

	// Type of section break (only used for section breaks)
	SectionType SectionBreakType

	// Page layout settings for the section (optional)
	PageLayout *PageLayoutOptions
}

BreakOptions defines options for inserting breaks

type CaptionOptions

type CaptionOptions struct {
	// Type of caption (Figure or Table)
	Type CaptionType

	// Position relative to object (before/after)
	Position CaptionPosition

	// Description text after the number (e.g., "Figure 1: <description>")
	Description string

	// Style to use (default: "Caption" which is standard in Word)
	// Can be overridden with custom styles like "Heading 1", "Normal", etc.
	Style string

	// Whether to include automatic numbering using SEQ fields
	// When true, uses Word's built-in field codes for auto-numbering
	AutoNumber bool

	// Alignment options
	Alignment CellAlignment

	// Optional: Manual number override (when AutoNumber is false)
	ManualNumber int
}

CaptionOptions defines options for caption creation

func DefaultCaptionOptions

func DefaultCaptionOptions(captionType CaptionType) CaptionOptions

DefaultCaptionOptions returns caption options with sensible defaults

type CaptionPosition

type CaptionPosition string

CaptionPosition defines where the caption appears relative to the object

const (
	CaptionBefore CaptionPosition = "before" // Caption appears before the object
	CaptionAfter  CaptionPosition = "after"  // Caption appears after the object (default for most)
)

type CaptionType

type CaptionType string

CaptionType defines the type of caption (Figure or Table)

const (
	CaptionFigure CaptionType = "Figure"
	CaptionTable  CaptionType = "Table"
)

type CellAlignment

type CellAlignment string

CellAlignment defines cell content alignment

const (
	CellAlignLeft   CellAlignment = "start"
	CellAlignCenter CellAlignment = "center"
	CellAlignRight  CellAlignment = "end"
)

type CellStyle

type CellStyle struct {
	Bold       bool
	Italic     bool
	FontSize   int    // Font size in half-points (e.g., 20 = 10pt)
	FontColor  string // Hex color (e.g., "000000")
	Background string // Hex color for cell background
}

CellStyle defines styling for table cells

type Chart

type Chart struct {
	Title    *ChartTitle `xml:"title,omitempty"`
	PlotArea PlotArea    `xml:"plotArea"`
}

Chart represents the chart element containing plot area.

type ChartData

type ChartData struct {
	Categories []string
	Series     []SeriesData
	// Optional titles
	ChartTitle        string // Main chart title
	CategoryAxisTitle string // X-axis title
	ValueAxisTitle    string // Y-axis title
}

ChartData defines chart categories and series values.

type ChartKind

type ChartKind string

ChartKind defines the type of chart

const (
	// ChartKindColumn creates a column chart (vertical bars, <c:barDir val="col"/>).
	ChartKindColumn ChartKind = "column"
	// ChartKindBar creates a bar chart (horizontal bars, <c:barDir val="bar"/>).
	// Although both column and bar charts emit a <c:barChart> element in OpenXML,
	// they are kept as distinct constants so callers do not need to set
	// BarChartOptions.Direction manually.
	ChartKindBar     ChartKind = "bar"
	ChartKindLine    ChartKind = "lineChart"    // Line chart
	ChartKindPie     ChartKind = "pieChart"     // Pie chart
	ChartKindArea    ChartKind = "areaChart"    // Area chart
	ChartKindScatter ChartKind = "scatterChart" // Scatter chart (XY chart)
)

type ChartOptions

type ChartOptions struct {
	// Position where to insert the chart
	Position InsertPosition
	Anchor   string // Text anchor for relative positioning

	// Chart type (default: Column)
	ChartKind ChartKind

	// Chart titles
	Title             string // Main chart title
	TitleOverlay      bool   // Overlays the title on the chart area
	CategoryAxisTitle string // X-axis title (horizontal axis) — backward compat, prefer CategoryAxis.Title
	ValueAxisTitle    string // Y-axis title (vertical axis) — backward compat, prefer ValueAxis.Title

	// Data
	Categories []string        // Category labels (X-axis)
	Series     []SeriesOptions // Data series with names and values
	// Deprecated: Use Legend.Show instead.
	ShowLegend bool // Show legend — backward compat, prefer Legend.Show
	// Deprecated: Use Legend.Position instead.
	LegendPosition string // Legend position — backward compat, prefer Legend.Position

	// Chart dimensions (default: spans between margins)
	Width  int // Width in EMUs (English Metric Units), 0 for default (6099523 = ~6.5")
	Height int // Height in EMUs, 0 for default (3340467 = ~3.5")

	// Caption options (nil for no caption)
	Caption *CaptionOptions

	// Extended axis customization (nil = auto defaults)
	CategoryAxis *AxisOptions
	ValueAxis    *AxisOptions

	// Legend customization (nil = derives from ShowLegend/LegendPosition)
	Legend *LegendOptions

	// Default data labels for all series (nil = no labels)
	DataLabels *DataLabelOptions

	// Chart-level rendering properties (nil = library defaults)
	Properties *ChartProperties

	// Bar/column-specific options (nil = clustered column defaults)
	BarChartOptions *BarChartOptions

	// Scatter chart-specific options (nil = marker defaults)
	ScatterChartOptions *ScatterChartOptions
}

ChartOptions defines comprehensive options for chart creation

type ChartProperties

type ChartProperties struct {
	// Appearance
	Style          ChartStyle // Chart style (0-48, 0=none, default: 2)
	RoundedCorners bool       // Use rounded corners (default: false)

	// Behavior
	Date1904 bool   // Use 1904 date system (Mac compatibility) (default: false)
	Language string // Language code (e.g., "en-US", "en-GB") (default: "en-US")

	// Display options
	PlotVisibleOnly       bool   // Plot only visible cells (default: true)
	DisplayBlanksAs       string // How to display blank cells: "gap", "zero", "span" (default: "gap")
	ShowDataLabelsOverMax bool   // Show data labels even if over max (default: false)
}

ChartProperties defines chart-level properties

type ChartSpace

type ChartSpace struct {
	XMLName      xml.Name `xml:"chartSpace"`
	Chart        Chart    `xml:"chart"`
	ExternalData struct {
		RID string `xml:"http://schemas.openxmlformats.org/officeDocument/2006/relationships id,attr"`
	} `xml:"externalData"`
}

ChartSpace represents the root element of a chart XML document.

type ChartStyle

type ChartStyle int

ChartStyle represents predefined chart styles (1-48 in Office)

const (
	ChartStyleNone       ChartStyle = 0  // No specific style
	ChartStyle1          ChartStyle = 1  // Style 1
	ChartStyle2          ChartStyle = 2  // Style 2 (default in many templates)
	ChartStyle3          ChartStyle = 3  // Style 3
	ChartStyleColorful   ChartStyle = 10 // Colorful style
	ChartStyleMonochrome ChartStyle = 42 // Monochrome style
)

type ChartTitle

type ChartTitle struct {
	Tx struct {
		Rich *struct {
			P struct {
				R struct {
					T string `xml:"t"`
				} `xml:"r"`
			} `xml:"p"`
		} `xml:"rich,omitempty"`
		StrRef *struct {
			F string `xml:"f"`
		} `xml:"strRef,omitempty"`
	} `xml:"tx"`
}

ChartTitle represents the chart title element.

type ChartType

type ChartType struct {
	Series []Series `xml:"ser"`
}

ChartType represents a chart with series data.

type ColumnDefinition

type ColumnDefinition struct {
	Title     string        // Column header title
	Width     int           // Optional: width in twips, 0 for auto
	Alignment CellAlignment // Optional: alignment for this column
	Bold      bool          // Make header bold
}

ColumnDefinition defines properties for a table column

type Comment

type Comment struct {
	ID       int
	Author   string
	Initials string
	Date     string
	Text     string
}

Comment represents an existing comment in the document

type CommentOptions

type CommentOptions struct {
	// Text is the comment content
	Text string

	// Author is the comment author name
	Author string

	// Initials is the author's initials (derived from Author if empty)
	Initials string

	// Anchor is the text in the document to attach the comment to.
	// The comment range will span the paragraph containing this text.
	Anchor string
}

CommentOptions defines options for inserting a comment

type CoreProperties

type CoreProperties struct {
	// Title of the document
	Title string

	// Subject of the document
	Subject string

	// Creator/Author of the document
	Creator string

	// Keywords for the document (comma-separated or slice)
	Keywords string

	// Description/Comments
	Description string

	// Category of the document
	Category string

	// ContentStatus indicates the document status (e.g., "Draft", "Final", "Reviewed")
	ContentStatus string

	// Created date (if empty, uses current time)
	Created time.Time

	// Modified date (if empty, uses current time)
	Modified time.Time

	// LastModifiedBy user name
	LastModifiedBy string

	// Revision number (version)
	Revision string
}

CoreProperties represents core document properties

type CustomProperty

type CustomProperty struct {
	// Name of the property
	Name string

	// Value of the property (string, int, float64, bool, or time.Time)
	Value any

	// Type is inferred from Value, but can be explicitly set
	// Valid types: "lpwstr" (string), "i4" (int), "r8" (float), "bool", "date"
	Type string
}

CustomProperty represents a custom document property

type DataLabelOptions

type DataLabelOptions struct {
	ShowValue        bool              // Show values on data points (default: false)
	ShowCategoryName bool              // Show category names (default: false)
	ShowSeriesName   bool              // Show series names (default: false)
	ShowPercent      bool              // Show percentage (for pie charts) (default: false)
	ShowLegendKey    bool              // Show legend key (default: false)
	Position         DataLabelPosition // Label position (default: bestFit)
	ShowLeaderLines  bool              // Show leader lines for pie charts (default: true)
}

DataLabelOptions defines options for data labels on chart elements

type DataLabelPosition

type DataLabelPosition string

DataLabelPosition defines where data labels appear

const (
	DataLabelCenter     DataLabelPosition = "ctr"     // Center of data point
	DataLabelInsideEnd  DataLabelPosition = "inEnd"   // Inside end
	DataLabelInsideBase DataLabelPosition = "inBase"  // Inside base
	DataLabelOutsideEnd DataLabelPosition = "outEnd"  // Outside end
	DataLabelBestFit    DataLabelPosition = "bestFit" // Best fit (auto)
)

type DeleteOptions

type DeleteOptions struct {
	// MatchCase determines if search is case-sensitive
	MatchCase bool

	// WholeWord only matches whole words
	WholeWord bool
}

DeleteOptions defines options for content deletion

func DefaultDeleteOptions

func DefaultDeleteOptions() DeleteOptions

DefaultDeleteOptions returns delete options with sensible defaults

type DocxError

type DocxError struct {
	Code    ErrorCode
	Message string
	Err     error
	Context map[string]any
}

DocxError provides structured error information

func (*DocxError) Error

func (e *DocxError) Error() string

Error implements the error interface

func (*DocxError) Unwrap

func (e *DocxError) Unwrap() error

Unwrap returns the wrapped error

func (*DocxError) WithContext

func (e *DocxError) WithContext(key string, value any) *DocxError

WithContext adds context to the error

type EndnoteOptions

type EndnoteOptions struct {
	// Text is the endnote content
	Text string

	// Anchor is the text in the document after which the endnote reference is placed
	Anchor string
}

EndnoteOptions defines options for inserting an endnote

type ErrorCode

type ErrorCode string

ErrorCode represents specific error conditions

const (
	// File-related errors
	ErrCodeInvalidFile      ErrorCode = "INVALID_FILE"
	ErrCodeFileNotFound     ErrorCode = "FILE_NOT_FOUND"
	ErrCodeFileCorrupted    ErrorCode = "FILE_CORRUPTED"
	ErrCodeFileTooLarge     ErrorCode = "FILE_TOO_LARGE"
	ErrCodePermissionDenied ErrorCode = "PERMISSION_DENIED"

	// Chart-related errors
	ErrCodeChartNotFound    ErrorCode = "CHART_NOT_FOUND"
	ErrCodeInvalidChartData ErrorCode = "INVALID_CHART_DATA"
	ErrCodeChartCreation    ErrorCode = "CHART_CREATION"

	// Table-related errors
	ErrCodeInvalidTableData ErrorCode = "INVALID_TABLE_DATA"
	ErrCodeTableCreation    ErrorCode = "TABLE_CREATION"

	// Image-related errors
	ErrCodeImageNotFound ErrorCode = "IMAGE_NOT_FOUND"
	ErrCodeImageFormat   ErrorCode = "IMAGE_FORMAT"
	ErrCodeImageTooLarge ErrorCode = "IMAGE_TOO_LARGE"

	// Text-related errors
	ErrCodeTextNotFound   ErrorCode = "TEXT_NOT_FOUND"
	ErrCodeInvalidRegex   ErrorCode = "INVALID_REGEX"
	ErrCodeReplaceFailure ErrorCode = "REPLACE_FAILURE"

	// XML-related errors
	ErrCodeXMLParse   ErrorCode = "XML_PARSE"
	ErrCodeXMLWrite   ErrorCode = "XML_WRITE"
	ErrCodeInvalidXML ErrorCode = "INVALID_XML"

	// Relationship errors
	ErrCodeRelationship ErrorCode = "RELATIONSHIP"
	ErrCodeRelNotFound  ErrorCode = "RELATIONSHIP_NOT_FOUND"

	// Content type errors
	ErrCodeContentType ErrorCode = "CONTENT_TYPE"

	// Validation errors
	ErrCodeValidation      ErrorCode = "VALIDATION"
	ErrCodeMissingRequired ErrorCode = "MISSING_REQUIRED"
	ErrCodeInvalidValue    ErrorCode = "INVALID_VALUE"

	// Document structure errors
	ErrCodeNoDocument       ErrorCode = "NO_DOCUMENT"
	ErrCodeNoBody           ErrorCode = "NO_BODY"
	ErrCodeInvalidStructure ErrorCode = "INVALID_STRUCTURE"

	// Hyperlink errors
	ErrCodeHyperlinkCreation ErrorCode = "HYPERLINK_CREATION"
	ErrCodeInvalidURL        ErrorCode = "INVALID_URL"

	// Header/Footer errors
	ErrCodeHeaderFooter ErrorCode = "HEADER_FOOTER"
)

type FindOptions

type FindOptions struct {
	// MatchCase determines if search is case-sensitive
	MatchCase bool

	// WholeWord only matches whole words
	WholeWord bool

	// UseRegex treats the search string as a regular expression
	UseRegex bool

	// MaxResults limits the number of results (0 for unlimited)
	MaxResults int

	// InParagraphs enables search in paragraphs
	InParagraphs bool

	// InTables enables search in tables
	InTables bool

	// InHeaders enables search in headers
	InHeaders bool

	// InFooters enables search in footers
	InFooters bool
}

FindOptions defines options for text search

func DefaultFindOptions

func DefaultFindOptions() FindOptions

DefaultFindOptions returns find options with sensible defaults

type FooterOptions

type FooterOptions struct {
	// Type of footer (first, even, default)
	Type FooterType

	// DifferentFirst enables different footer on first page
	DifferentFirst bool

	// DifferentOddEven enables different footers for odd/even pages
	DifferentOddEven bool
}

FooterOptions defines options for footer creation

func DefaultFooterOptions

func DefaultFooterOptions() FooterOptions

DefaultFooterOptions returns footer options with sensible defaults

type FooterType

type FooterType string

FooterType defines the type of footer

const (
	// FooterFirst is the footer for the first page
	FooterFirst FooterType = "first"
	// FooterEven is the footer for even pages
	FooterEven FooterType = "even"
	// FooterDefault is the default footer (odd pages)
	FooterDefault FooterType = "default"
)

type FootnoteOptions

type FootnoteOptions struct {
	// Text is the footnote content
	Text string

	// Anchor is the text in the document after which the footnote reference is placed
	Anchor string
}

FootnoteOptions defines options for inserting a footnote

type HeaderFooterContent

type HeaderFooterContent struct {
	// LeftText is left-aligned text
	LeftText string

	// CenterText is center-aligned text
	CenterText string

	// RightText is right-aligned text
	RightText string

	// PageNumber includes page number field
	PageNumber bool

	// PageNumberFormat defines the page number format (e.g., "Page X of Y")
	PageNumberFormat string

	// Date includes current date field
	Date bool

	// DateFormat defines date format
	DateFormat string
}

HeaderFooterContent defines the content structure for headers/footers

type HeaderOptions

type HeaderOptions struct {
	// Type of header (first, even, default)
	Type HeaderType

	// DifferentFirst enables different header on first page
	DifferentFirst bool

	// DifferentOddEven enables different headers for odd/even pages
	DifferentOddEven bool
}

HeaderOptions defines options for header creation

func DefaultHeaderOptions

func DefaultHeaderOptions() HeaderOptions

DefaultHeaderOptions returns header options with sensible defaults

type HeaderType

type HeaderType string

HeaderType defines the type of header

const (
	// HeaderFirst is the header for the first page
	HeaderFirst HeaderType = "first"
	// HeaderEven is the header for even pages
	HeaderEven HeaderType = "even"
	// HeaderDefault is the default header (odd pages)
	HeaderDefault HeaderType = "default"
)

type HyperlinkOptions

type HyperlinkOptions struct {
	// Position where to insert the hyperlink
	Position InsertPosition

	// Anchor text for position-based insertion (for PositionAfterText/PositionBeforeText)
	Anchor string

	// Tooltip text shown on hover
	Tooltip string

	// Style to apply to the hyperlink paragraph (if creating new paragraph)
	Style ParagraphStyle

	// Color for hyperlink text (hex color, e.g., "0563C1")
	Color string

	// Underline the hyperlink text
	Underline bool

	// ScreenTip for accessibility
	ScreenTip string
}

HyperlinkOptions defines options for hyperlink insertion

func DefaultHyperlinkOptions

func DefaultHyperlinkOptions() HyperlinkOptions

DefaultHyperlinkOptions returns hyperlink options with sensible defaults

type ImageDimensions

type ImageDimensions struct {
	Width  int
	Height int
}

ImageDimensions stores image width and height in pixels

type ImageOptions

type ImageOptions struct {
	// Path to the image file (required)
	Path string

	// Width in pixels (optional - if only width is set, height is calculated proportionally)
	Width int

	// Height in pixels (optional - if only height is set, width is calculated proportionally)
	Height int

	// Alternative text for accessibility (optional)
	AltText string

	// Position where to insert the image
	Position InsertPosition

	// Anchor text for position-based insertion (for PositionAfterText/PositionBeforeText)
	Anchor string

	// Caption options (nil for no caption)
	Caption *CaptionOptions
}

ImageOptions defines options for image insertion

type InsertPosition

type InsertPosition int

InsertPosition defines where to insert the paragraph

const (
	// PositionBeginning inserts at the start of the document body
	PositionBeginning InsertPosition = iota
	// PositionEnd inserts at the end of the document body
	PositionEnd
	// PositionAfterText inserts after the first occurrence of specified text
	PositionAfterText
	// PositionBeforeText inserts before the first occurrence of specified text
	PositionBeforeText
)

type LegendOptions

type LegendOptions struct {
	Show     bool   // Show legend (default: true)
	Position string // Position: "r" (right), "l" (left), "t" (top), "b" (bottom), "tr" (top right)
	Overlay  bool   // Legend overlays chart (default: false)
}

LegendOptions defines legend customization

type ListType

type ListType string

ListType defines the type of list

const (
	ListTypeBullet   ListType = "bullet"   // Bullet list (•)
	ListTypeNumbered ListType = "numbered" // Numbered list (1, 2, 3...)
)

type NumCache

type NumCache struct {
	PtCount int     `xml:"ptCount>val,attr"`
	Pts     []NumPt `xml:"pt"`
}

NumCache contains cached numeric values.

type NumPt

type NumPt struct {
	Idx int     `xml:"idx,attr"`
	V   float64 `xml:"v"`
}

NumPt represents a numeric point in the cache.

type PageLayoutOptions

type PageLayoutOptions struct {
	// Page dimensions in twips (1/1440 inch)
	// Use predefined page sizes or custom values
	PageWidth  int // Width in twips (e.g., 12240 for 8.5")
	PageHeight int // Height in twips (e.g., 15840 for 11")

	// Page orientation
	Orientation PageOrientation

	// Margins in twips (1/1440 inch)
	MarginTop    int // Top margin
	MarginRight  int // Right margin
	MarginBottom int // Bottom margin
	MarginLeft   int // Left margin
	MarginHeader int // Header distance from edge
	MarginFooter int // Footer distance from edge
	MarginGutter int // Gutter margin for binding
}

PageLayoutOptions defines page layout settings for a section

func PageLayoutA3Landscape

func PageLayoutA3Landscape() *PageLayoutOptions

PageLayoutA3Landscape creates an A3 landscape layout with default margins

func PageLayoutA3Portrait

func PageLayoutA3Portrait() *PageLayoutOptions

PageLayoutA3Portrait creates an A3 portrait layout with default margins

func PageLayoutA4Landscape

func PageLayoutA4Landscape() *PageLayoutOptions

PageLayoutA4Landscape creates an A4 landscape layout with default margins

func PageLayoutA4Portrait

func PageLayoutA4Portrait() *PageLayoutOptions

PageLayoutA4Portrait creates an A4 portrait layout with default margins

func PageLayoutLegalPortrait

func PageLayoutLegalPortrait() *PageLayoutOptions

PageLayoutLegalPortrait creates a US Legal portrait layout with 1" margins

func PageLayoutLetterLandscape

func PageLayoutLetterLandscape() *PageLayoutOptions

PageLayoutLetterLandscape creates a US Letter landscape layout with 1" margins

func PageLayoutLetterPortrait

func PageLayoutLetterPortrait() *PageLayoutOptions

PageLayoutLetterPortrait creates a US Letter portrait layout with 1" margins

type PageNumberFormat

type PageNumberFormat string

PageNumberFormat defines the format for page numbers

const (
	// PageNumDecimal uses 1, 2, 3, ... (default)
	PageNumDecimal PageNumberFormat = "decimal"
	// PageNumUpperRoman uses I, II, III, IV, ...
	PageNumUpperRoman PageNumberFormat = "upperRoman"
	// PageNumLowerRoman uses i, ii, iii, iv, ...
	PageNumLowerRoman PageNumberFormat = "lowerRoman"
	// PageNumUpperLetter uses A, B, C, ...
	PageNumUpperLetter PageNumberFormat = "upperLetter"
	// PageNumLowerLetter uses a, b, c, ...
	PageNumLowerLetter PageNumberFormat = "lowerLetter"
)

type PageNumberOptions

type PageNumberOptions struct {
	// Start is the starting page number (default: 1)
	Start int

	// Format defines the page number format (default: decimal)
	Format PageNumberFormat
}

PageNumberOptions defines options for page numbering

type PageOrientation

type PageOrientation string

PageOrientation defines page orientation

const (
	// OrientationPortrait sets page to portrait mode (taller than wide)
	OrientationPortrait PageOrientation = "portrait"
	// OrientationLandscape sets page to landscape mode (wider than tall)
	OrientationLandscape PageOrientation = "landscape"
)

type ParagraphAlignment

type ParagraphAlignment string

ParagraphAlignment defines paragraph text alignment.

const (
	ParagraphAlignLeft    ParagraphAlignment = "left"
	ParagraphAlignCenter  ParagraphAlignment = "center"
	ParagraphAlignRight   ParagraphAlignment = "right"
	ParagraphAlignJustify ParagraphAlignment = "both"
)

type ParagraphOptions

type ParagraphOptions struct {
	// Text is used when Runs is empty — the whole paragraph gets a single run with
	// the Bold/Italic/Underline flags below applied uniformly.
	Text      string         // The text content of the paragraph
	Style     ParagraphStyle // The style to apply (default: Normal)
	Alignment ParagraphAlignment
	Position  InsertPosition // Where to insert the paragraph
	Anchor    string         // Text to anchor the insertion (for PositionAfterText/PositionBeforeText)

	// Single-run formatting flags — only used when Runs is empty.
	Bold      bool // Make text bold
	Italic    bool // Make text italic
	Underline bool // Underline text

	// Runs allows building a multi-run paragraph where each run can have independent
	// character formatting. When Runs is non-empty, Text/Bold/Italic/Underline above
	// are ignored.
	Runs []RunOptions

	// List properties (alternative to Style-based lists)
	ListType  ListType // Type of list (bullet or numbered)
	ListLevel int      // Indentation level (0-8, default 0)

	// Pagination control
	KeepNext  bool // Keep this paragraph on the same page as the next (prevents orphaned headings)
	KeepLines bool // Keep all lines of this paragraph together on the same page
}

ParagraphOptions defines options for paragraph insertion

type ParagraphStyle

type ParagraphStyle string

ParagraphStyle defines common paragraph styles

const (
	StyleNormal     ParagraphStyle = "Normal"
	StyleHeading1   ParagraphStyle = "Heading1"
	StyleHeading2   ParagraphStyle = "Heading2"
	StyleHeading3   ParagraphStyle = "Heading3"
	StyleHeading4   ParagraphStyle = "Heading4"
	StyleHeading5   ParagraphStyle = "Heading5"
	StyleHeading6   ParagraphStyle = "Heading6"
	StyleHeading7   ParagraphStyle = "Heading7"
	StyleHeading8   ParagraphStyle = "Heading8"
	StyleHeading9   ParagraphStyle = "Heading9"
	StyleTitle      ParagraphStyle = "Title"
	StyleSubtitle   ParagraphStyle = "Subtitle"
	StyleQuote      ParagraphStyle = "Quote"
	StyleIntense    ParagraphStyle = "IntenseQuote"
	StyleListNumber ParagraphStyle = "ListNumber"
	StyleListBullet ParagraphStyle = "ListBullet"
)

type PlotArea

type PlotArea struct {
	BarChart     *ChartType `xml:"barChart,omitempty"`
	LineChart    *ChartType `xml:"lineChart,omitempty"`
	ScatterChart *ChartType `xml:"scatterChart,omitempty"`
	PieChart     *ChartType `xml:"pieChart,omitempty"`
	CatAx        []Axis     `xml:"catAx,omitempty"`
	ValAx        []Axis     `xml:"valAx,omitempty"`
}

PlotArea contains the chart type and series.

type ReplaceOptions

type ReplaceOptions struct {
	// MatchCase determines if replacement is case-sensitive
	MatchCase bool

	// WholeWord only replaces whole word matches
	WholeWord bool

	// InParagraphs enables replacement in paragraph text
	InParagraphs bool

	// InTables enables replacement in table cells
	InTables bool

	// InHeaders enables replacement in headers
	InHeaders bool

	// InFooters enables replacement in footers
	InFooters bool

	// MaxReplacements limits the number of replacements (0 for unlimited)
	MaxReplacements int
}

ReplaceOptions defines options for text replacement

func DefaultReplaceOptions

func DefaultReplaceOptions() ReplaceOptions

DefaultReplaceOptions returns replace options with sensible defaults

type RowHeightRule

type RowHeightRule string

RowHeightRule defines how row height is interpreted

const (
	RowHeightAuto    RowHeightRule = "auto"    // Auto height based on content (default)
	RowHeightAtLeast RowHeightRule = "atLeast" // Minimum height, can grow
	RowHeightExact   RowHeightRule = "exact"   // Fixed height, no growth
)

type RunOptions added in v1.8.1

type RunOptions struct {
	// Text is the content of this run. Newlines (\n) become <w:br/> and tabs (\t) become <w:tab/>.
	Text string

	// Character formatting
	Bold          bool
	Italic        bool
	Underline     bool // Single underline
	Strikethrough bool // Strikethrough text
	Superscript   bool // Raise text above baseline
	Subscript     bool // Lower text below baseline

	// Color is a 6-digit hex RGB value without '#', e.g. "FF0000" for red.
	Color string

	// Highlight is a named highlight color: "yellow", "green", "cyan", "magenta",
	// "blue", "red", "darkBlue", "darkCyan", "darkGreen", "darkMagenta",
	// "darkRed", "darkYellow", "darkGray", "lightGray", "black".
	Highlight string

	// FontSize is the font size in points (e.g. 12.0). Zero means inherit.
	FontSize float64

	// FontName sets the ASCII/Unicode font (e.g. "Arial", "Times New Roman").
	FontName string

	// URL sets an inline hyperlink on this run. When non-empty the run is emitted
	// as a <w:hyperlink> element. Hyperlinks are always underlined; Color defaults
	// to "0563C1" (Word's standard blue) but can be overridden by setting Color.
	URL string
}

RunOptions defines formatting and content for a single text run within a paragraph. A run is the smallest unit of text in OpenXML that can carry its own character formatting. Use multiple RunOptions in ParagraphOptions.Runs to mix bold, italic, colored, and differently-sized text within the same paragraph.

type ScatterChartOptions

type ScatterChartOptions struct {
	// ScatterStyle defines the scatter chart style
	// "line" - scatter chart with straight lines
	// "lineMarker" - scatter chart with markers and straight lines
	// "marker" - scatter chart with markers only (default)
	// "smooth" - scatter chart with smooth lines
	// "smoothMarker" - scatter chart with markers and smooth lines
	ScatterStyle string

	// VaryColors - whether to vary colors by point
	VaryColors bool
}

ScatterChartOptions defines options specific to scatter charts

type SectionBreakType

type SectionBreakType string

SectionBreakType defines the type of section break

const (
	// SectionBreakNextPage starts the new section on the next page
	SectionBreakNextPage SectionBreakType = "nextPage"
	// SectionBreakContinuous starts the new section on the same page
	SectionBreakContinuous SectionBreakType = "continuous"
	// SectionBreakEvenPage starts the new section on the next even page
	SectionBreakEvenPage SectionBreakType = "evenPage"
	// SectionBreakOddPage starts the new section on the next odd page
	SectionBreakOddPage SectionBreakType = "oddPage"
)

type Series

type Series struct {
	Tx  SeriesText `xml:"tx"`
	Cat *SeriesRef `xml:"cat,omitempty"`
	Val *SeriesRef `xml:"val,omitempty"`
	// For scatter charts
	XVal *SeriesRef `xml:"xVal,omitempty"`
	YVal *SeriesRef `xml:"yVal,omitempty"`
}

Series represents a data series in a chart.

type SeriesData

type SeriesData struct {
	Name   string
	Values []float64
	Color  string // Hex color code (e.g., "FF0000" for red) - optional
}

SeriesData defines one chart series.

type SeriesOptions

type SeriesOptions struct {
	Name             string            // Series name
	Values           []float64         // Data values (Y-axis for scatter, values for other charts)
	XValues          []float64         // X values for scatter charts (if nil, uses category indices)
	Color            string            // Hex color (e.g., "FF0000")
	InvertIfNegative bool              // Use different color for negative values (default: false)
	Smooth           bool              // Smooth lines (for line charts) (default: false)
	ShowMarkers      bool              // Show markers (for line charts) (default: false)
	DataLabels       *DataLabelOptions // Data labels for this series (nil for default)
}

SeriesOptions defines per-series customization

type SeriesRef

type SeriesRef struct {
	F        string    `xml:"f,omitempty"`
	StrCache *StrCache `xml:"strCache,omitempty"`
	NumCache *NumCache `xml:"numCache,omitempty"`
}

SeriesRef represents a reference to chart data.

type SeriesText

type SeriesText struct {
	V   string     `xml:"v,omitempty"`
	Ref *SeriesRef `xml:"strRef,omitempty"`
}

SeriesText contains the series name.

type StrCache

type StrCache struct {
	PtCount int     `xml:"ptCount>val,attr"`
	Pts     []StrPt `xml:"pt"`
}

StrCache contains cached string values.

type StrPt

type StrPt struct {
	Idx int    `xml:"idx,attr"`
	V   string `xml:"v"`
}

StrPt represents a string point in the cache.

type StyleDefinition

type StyleDefinition struct {
	// ID is the style ID used for referencing (e.g., "CustomHeading")
	ID string

	// Name is the display name shown in Word's style gallery
	Name string

	// Type is the style type (paragraph or character)
	Type StyleType

	// BasedOn is the parent style ID (e.g., "Normal", "Heading1")
	BasedOn string

	// NextStyle is the style applied to the next paragraph (paragraph styles only)
	NextStyle string

	// Font settings
	FontFamily string // e.g., "Arial", "Times New Roman"
	FontSize   int    // Font size in half-points (e.g., 24 = 12pt)
	Color      string // Hex color code without '#' (e.g., "FF0000")

	// Text formatting
	Bold          bool
	Italic        bool
	Underline     bool
	Strikethrough bool
	AllCaps       bool
	SmallCaps     bool

	// Paragraph formatting (paragraph styles only)
	Alignment    ParagraphAlignment
	SpaceBefore  int // Space before paragraph in twips
	SpaceAfter   int // Space after paragraph in twips
	LineSpacing  int // Line spacing in 240ths of a line (e.g., 240 = single, 480 = double)
	IndentLeft   int // Left indent in twips
	IndentRight  int // Right indent in twips
	IndentFirst  int // First line indent in twips
	KeepNext     bool
	KeepLines    bool
	PageBreakBef bool

	// Outline level (0-8, paragraph styles only, used for TOC)
	OutlineLevel int
}

StyleDefinition defines a custom style to add to the document

type StyleType

type StyleType string

StyleType defines the type of style

const (
	// StyleTypeParagraph is a paragraph style (affects entire paragraph)
	StyleTypeParagraph StyleType = "paragraph"
	// StyleTypeCharacter is a character style (affects inline text runs)
	StyleTypeCharacter StyleType = "character"
)

type TOCEntry

type TOCEntry struct {
	Level int    // Heading level (1-9)
	Text  string // Entry text
	Page  int    // Page number (if available)
}

TOCEntry represents an entry in the Table of Contents

type TOCOptions

type TOCOptions struct {
	// Title for the TOC (default: "Table of Contents")
	Title string

	// Outline levels to include (default: "1-3")
	// Example: "1-3" includes Heading1, Heading2, Heading3
	OutlineLevels string

	// Position where to insert the TOC
	Position InsertPosition

	// Anchor text for position-based insertion
	Anchor string
}

TOCOptions defines options for Table of Contents

func DefaultTOCOptions

func DefaultTOCOptions() TOCOptions

DefaultTOCOptions returns default TOC options

type TableAlignment

type TableAlignment string

TableAlignment defines table alignment

const (
	AlignLeft   TableAlignment = "left"
	AlignCenter TableAlignment = "center"
	AlignRight  TableAlignment = "right"
)

type TableOptions

type TableOptions struct {
	// Position where to insert the table
	Position InsertPosition
	Anchor   string // Text anchor for relative positioning

	// Column definitions
	Columns      []ColumnDefinition // Column titles and properties
	ColumnWidths []int              // Optional: column widths in twips (1/1440 inch), nil for auto

	// Data rows (excluding header)
	Rows [][]string // Each inner slice is a row of cell data

	// ProportionalColumnWidths enables content-based proportional sizing
	// When true, column widths are calculated based on the length of content
	// (headers + longest cell) in each column. Wider content gets wider columns.
	// If false (default), all columns get equal width.
	// Ignored if ColumnWidths is explicitly specified.
	ProportionalColumnWidths bool

	// AvailableWidth specifies the usable page width in twips (page width - left margin - right margin)
	// Used for auto-calculating column widths in percentage mode
	// If 0 (default), uses standard Letter page width calculation: 12240 - 1440 - 1440 = 9360
	// Automatically computed if not set
	AvailableWidth int

	// Header styling
	HeaderStyle      CellStyle     // Style for header row
	HeaderStyleName  string        // Named Word style for header paragraphs (e.g., "Heading 1")
	RepeatHeader     bool          // Repeat header row on each page
	HeaderBackground string        // Hex color for header background (e.g., "4472C4")
	HeaderBold       bool          // Make header text bold
	HeaderAlignment  CellAlignment // Header text alignment

	// Row styling
	RowStyle          CellStyle         // Style for data rows
	RowStyleName      string            // Named Word style for data row paragraphs (e.g., "Normal")
	AlternateRowColor string            // Hex color for alternate rows (e.g., "F2F2F2")
	RowAlignment      CellAlignment     // Default cell alignment for data rows
	VerticalAlign     VerticalAlignment // Vertical alignment in cells

	// Row height
	HeaderRowHeight  int           // Header row height in twips, 0 for auto
	HeaderHeightRule RowHeightRule // Header height rule (auto, atLeast, exact)
	RowHeight        int           // Data row height in twips, 0 for auto
	RowHeightRule    RowHeightRule // Data row height rule (auto, atLeast, exact)

	// Table properties
	TableAlignment TableAlignment // Table alignment on page
	TableWidthType TableWidthType // Width type: auto, percentage, or fixed (default: percentage)
	TableWidth     int            // Width value: 0 for auto, 5000 for 100% (pct mode), or twips (dxa mode)
	TableStyle     TableStyle     // Predefined table style

	// Border properties
	BorderStyle BorderStyle // Border style

	// Caption options (nil for no caption)
	Caption     *CaptionOptions
	BorderSize  int    // Border width in eighths of a point (default: 4 = 0.5pt)
	BorderColor string // Hex color for borders (default: "000000")

	// Cell properties
	CellPadding int  // Cell padding in twips (default: 108 = 0.075")
	AutoFit     bool // Auto-fit content (default: false for fixed widths)

	// Conditional cell styling based on content
	// Map keys are matched case-insensitively against cell text
	// Matching cells will have their style overridden by the map value
	// Non-empty conditional values take precedence over row-level styling
	ConditionalStyles map[string]CellStyle
}

TableOptions defines comprehensive options for table creation

type TableStyle

type TableStyle string

TableStyle defines table styling options

const (
	TableStyleGrid         TableStyle = "TableGrid"
	TableStyleGridAccent1  TableStyle = "LightShading-Accent1"
	TableStyleGridAccent2  TableStyle = "MediumShading1-Accent1"
	TableStylePlain        TableStyle = "TableNormal"
	TableStyleColorful     TableStyle = "ColorfulGrid-Accent1"
	TableStyleProfessional TableStyle = "LightGrid-Accent1"
)

type TableWidthType

type TableWidthType string

TableWidthType defines how table width is specified

const (
	TableWidthAuto       TableWidthType = "auto" // Auto-fit to content
	TableWidthPercentage TableWidthType = "pct"  // Percentage of available width (5000 = 100%)
	TableWidthFixed      TableWidthType = "dxa"  // Fixed width in twips
)

type TextMatch

type TextMatch struct {
	Text      string // The matched text
	Paragraph int    // Paragraph index (0-based)
	Position  int    // Character position in document
	Before    string // Context before match (up to 50 chars)
	After     string // Context after match (up to 50 chars)
}

TextMatch represents a text match with context

type TickLabelPosition

type TickLabelPosition string

TickLabelPosition defines tick label position

const (
	TickLabelHigh   TickLabelPosition = "high"   // High
	TickLabelLow    TickLabelPosition = "low"    // Low
	TickLabelNextTo TickLabelPosition = "nextTo" // Next to axis (default)
	TickLabelNone   TickLabelPosition = "none"   // No labels
)

type TickMark

type TickMark string

TickMark defines tick mark type

const (
	TickMarkCross TickMark = "cross" // Cross
	TickMarkIn    TickMark = "in"    // Inside
	TickMarkNone  TickMark = "none"  // None
	TickMarkOut   TickMark = "out"   // Outside (default)
)

type TrackedDeleteOptions

type TrackedDeleteOptions struct {
	// Anchor is the text in the document to mark as deleted (required).
	// The entire paragraph containing this text will be marked.
	Anchor string

	// Author of the deletion revision (default: "Author")
	Author string

	// Date of the deletion revision (default: current time)
	Date time.Time
}

TrackedDeleteOptions defines options for marking existing text as deleted.

type TrackedInsertOptions

type TrackedInsertOptions struct {
	// Text to insert (required)
	Text string

	// Author of the revision (default: "Author")
	Author string

	// Date of the revision (default: current time)
	Date time.Time

	// Position where to insert the tracked text
	Position InsertPosition

	// Anchor text for position-based insertion
	Anchor string

	// Style for the inserted paragraph (default: Normal)
	Style ParagraphStyle

	// Text formatting
	Bold      bool
	Italic    bool
	Underline bool
}

TrackedInsertOptions defines options for inserting text with revision tracking.

type Updater

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

Updater manages a DOCX document for programmatic reading and writing.

An Updater is not safe for concurrent use by multiple goroutines. All operations read and write files in a shared temporary directory; callers must serialise access externally if they need to issue operations from multiple goroutines.

func New

func New(docxPath string) (*Updater, error)

New opens a DOCX file and prepares it for editing.

func NewBlank added in v1.8.1

func NewBlank() (*Updater, error)

NewBlank creates a new blank DOCX document from scratch without requiring a template. The document contains a minimal valid OpenXML structure ready for content insertion.

func NewFromBytes added in v1.8.1

func NewFromBytes(data []byte) (*Updater, error)

NewFromBytes creates an Updater from raw DOCX bytes (e.g., uploaded template data). This is useful when the template is received from a web upload, API payload, or database rather than a file on disk.

func NewFromReader

func NewFromReader(r io.Reader) (*Updater, error)

NewFromReader opens a DOCX from an io.Reader and prepares it for editing. The reader content is buffered to a temporary file which is cleaned up by Cleanup().

func (*Updater) AddBulletItem

func (u *Updater) AddBulletItem(text string, level int, position InsertPosition) error

AddBulletItem adds a bullet list item at the specified level (0-8)

func (*Updater) AddBulletList

func (u *Updater) AddBulletList(items []string, level int, position InsertPosition) error

AddBulletList adds multiple bullet list items in batch

func (*Updater) AddHeading

func (u *Updater) AddHeading(level int, text string, position InsertPosition) error

AddHeading is a convenience function to add a heading paragraph at the specified level (1–9), matching Word's built-in Heading 1 – Heading 9 styles.

func (*Updater) AddNumberedItem

func (u *Updater) AddNumberedItem(text string, level int, position InsertPosition) error

AddNumberedItem adds a numbered list item at the specified level (0-8)

func (*Updater) AddNumberedList

func (u *Updater) AddNumberedList(items []string, level int, position InsertPosition) error

AddNumberedList adds multiple numbered list items in batch

func (*Updater) AddStyle

func (u *Updater) AddStyle(def StyleDefinition) error

AddStyle adds a custom style definition to the document. The style can then be used with InsertParagraph by setting ParagraphOptions.Style to the style ID.

func (*Updater) AddStyles

func (u *Updater) AddStyles(defs []StyleDefinition) error

AddStyles adds multiple custom style definitions in batch.

func (*Updater) AddText

func (u *Updater) AddText(text string, position InsertPosition) error

AddText is a convenience function to add normal text paragraph

func (*Updater) Cleanup

func (u *Updater) Cleanup() error

Cleanup removes temporary workspace.

func (*Updater) CreateBookmark

func (u *Updater) CreateBookmark(name string, opts BookmarkOptions) error

CreateBookmark creates a bookmark at a specific location with optional text If text is provided, the bookmark wraps the text; otherwise it's an empty bookmark marker

func (*Updater) CreateBookmarkWithText

func (u *Updater) CreateBookmarkWithText(name, text string, opts BookmarkOptions) error

CreateBookmarkWithText creates a bookmark that wraps specific text content

func (*Updater) DeleteChart

func (u *Updater) DeleteChart(chartIndex int) error

DeleteChart removes a chart by index (1-based).

func (*Updater) DeleteImage

func (u *Updater) DeleteImage(imageIndex int) error

DeleteImage removes an image by index (1-based). Note: This removes the image from the document but does not delete the media file.

func (*Updater) DeleteParagraphs

func (u *Updater) DeleteParagraphs(text string, opts DeleteOptions) (int, error)

DeleteParagraphs removes paragraphs matching the specified text. Returns the number of paragraphs deleted.

func (*Updater) DeleteTable

func (u *Updater) DeleteTable(tableIndex int) error

DeleteTable removes a table by index (1-based).

func (*Updater) DeleteTrackedText

func (u *Updater) DeleteTrackedText(opts TrackedDeleteOptions) error

DeleteTrackedText marks the paragraph containing the anchor text as a tracked deletion. The text appears as struck-through red text in Word and can be accepted or rejected by the reviewer.

func (*Updater) FindText

func (u *Updater) FindText(pattern string, opts FindOptions) ([]TextMatch, error)

FindText finds all occurrences of text in the document

func (*Updater) GetAppProperties added in v1.8.1

func (u *Updater) GetAppProperties() (*AppProperties, error)

GetAppProperties retrieves application-specific document properties

func (*Updater) GetChartCount

func (u *Updater) GetChartCount() (int, error)

GetChartCount returns the number of charts embedded in the document. Returns 0 if the document contains no charts.

func (*Updater) GetChartData

func (u *Updater) GetChartData(chartIndex int) (ChartData, error)

GetChartData reads the categories, series names, and values from chart N (1-based).

func (*Updater) GetComments

func (u *Updater) GetComments() ([]Comment, error)

GetComments reads all comments from the document. Returns nil if the document has no comments.

func (*Updater) GetCoreProperties

func (u *Updater) GetCoreProperties() (*CoreProperties, error)

GetCoreProperties retrieves core document properties

func (*Updater) GetCustomProperties added in v1.8.1

func (u *Updater) GetCustomProperties() ([]CustomProperty, error)

GetCustomProperties retrieves custom document properties

func (*Updater) GetImageCount

func (u *Updater) GetImageCount() (int, error)

GetImageCount returns the number of images in the document

func (*Updater) GetParagraphCount

func (u *Updater) GetParagraphCount() (int, error)

GetParagraphCount returns the number of paragraphs in the document

func (*Updater) GetParagraphText

func (u *Updater) GetParagraphText() ([]string, error)

GetParagraphText extracts text from all paragraphs

func (*Updater) GetTOCEntries

func (u *Updater) GetTOCEntries() ([]TOCEntry, error)

GetTOCEntries extracts TOC entries from the document. Returns a slice of TOCEntry with level and text.

func (*Updater) GetTableCount

func (u *Updater) GetTableCount() (int, error)

GetTableCount returns the number of tables in the document

func (*Updater) GetTableText

func (u *Updater) GetTableText() ([][][]string, error)

GetTableText extracts text from all tables Returns a 2D slice where each element represents a table, containing rows of cells

func (*Updater) GetText

func (u *Updater) GetText() (string, error)

GetText extracts all text from the document body

func (*Updater) InsertChart

func (u *Updater) InsertChart(opts ChartOptions) error

InsertChart creates a new chart and inserts it into the document

func (*Updater) InsertComment

func (u *Updater) InsertComment(opts CommentOptions) error

InsertComment adds a comment to the document. The comment range spans the paragraph containing the anchor text.

func (*Updater) InsertEndnote

func (u *Updater) InsertEndnote(opts EndnoteOptions) error

InsertEndnote adds an endnote to the document. The endnote reference marker is placed at the end of the paragraph containing the anchor text.

func (*Updater) InsertFootnote

func (u *Updater) InsertFootnote(opts FootnoteOptions) error

InsertFootnote adds a footnote to the document. The footnote reference marker is placed at the end of the paragraph containing the anchor text.

func (u *Updater) InsertHyperlink(text, urlStr string, opts HyperlinkOptions) error

InsertHyperlink inserts a hyperlink into the document

func (*Updater) InsertImage

func (u *Updater) InsertImage(opts ImageOptions) error

InsertImage inserts an image into the document with optional proportional sizing

func (u *Updater) InsertInternalLink(text, bookmarkName string, opts HyperlinkOptions) error

InsertInternalLink inserts a link to a bookmark within the document

func (*Updater) InsertPageBreak

func (u *Updater) InsertPageBreak(opts BreakOptions) error

InsertPageBreak inserts a page break into the document

func (*Updater) InsertParagraph

func (u *Updater) InsertParagraph(opts ParagraphOptions) error

InsertParagraph inserts a new paragraph into the document

func (*Updater) InsertParagraphs

func (u *Updater) InsertParagraphs(paragraphs []ParagraphOptions) error

InsertParagraphs inserts multiple paragraphs in a single read-modify-write pass, which is significantly more efficient than calling InsertParagraph N times.

func (*Updater) InsertSectionBreak

func (u *Updater) InsertSectionBreak(opts BreakOptions) error

InsertSectionBreak inserts a section break into the document

func (*Updater) InsertTOC

func (u *Updater) InsertTOC(opts TOCOptions) error

InsertTOC inserts a Table of Contents field into the document. The TOC uses Word field codes and will be populated when the document is opened in Word and the user updates the field (Ctrl+A, F9).

func (*Updater) InsertTable

func (u *Updater) InsertTable(opts TableOptions) error

InsertTable inserts a new table into the document

func (*Updater) InsertTrackedText

func (u *Updater) InsertTrackedText(opts TrackedInsertOptions) error

InsertTrackedText inserts a new paragraph with revision tracking. The inserted text appears as a tracked insertion (green underline in Word) that can be accepted or rejected by the reviewer.

func (*Updater) MergeTableCellsHorizontal

func (u *Updater) MergeTableCellsHorizontal(tableIndex, row, startCol, endCol int) error

MergeTableCellsHorizontal merges cells in a single row across columns. tableIndex, row, startCol, endCol are all 1-based. The content of the first cell (startCol) is preserved; merged cells are removed.

Note: nested tables (a table inside a table cell) are not supported.

func (*Updater) MergeTableCellsVertical

func (u *Updater) MergeTableCellsVertical(tableIndex, startRow, endRow, col int) error

MergeTableCellsVertical merges cells in a single column across rows. tableIndex, startRow, endRow, col are all 1-based. The content of the first cell (startRow) is preserved; subsequent cells are marked as continuation cells (their content remains but Word displays only the first cell).

Note: nested tables (a table inside a table cell) are not supported.

func (*Updater) ReplaceText

func (u *Updater) ReplaceText(old, new string, opts ReplaceOptions) (int, error)

ReplaceText replaces all occurrences of old text with new text Returns the number of replacements made

func (*Updater) ReplaceTextRegex

func (u *Updater) ReplaceTextRegex(pattern *regexp.Regexp, replacement string, opts ReplaceOptions) (int, error)

ReplaceTextRegex replaces text matching a regular expression pattern Returns the number of replacements made

func (*Updater) Save

func (u *Updater) Save(outputPath string) error

Save writes the updated DOCX to outputPath.

func (*Updater) SaveToWriter

func (u *Updater) SaveToWriter(w io.Writer) error

SaveToWriter writes the updated DOCX to an io.Writer.

func (*Updater) SetAppProperties

func (u *Updater) SetAppProperties(props AppProperties) error

SetAppProperties sets the application-specific document properties

func (*Updater) SetCoreProperties

func (u *Updater) SetCoreProperties(props CoreProperties) error

SetCoreProperties sets the core document properties

func (*Updater) SetCustomProperties

func (u *Updater) SetCustomProperties(properties []CustomProperty) error

SetCustomProperties sets custom document properties

func (*Updater) SetFooter

func (u *Updater) SetFooter(content HeaderFooterContent, opts FooterOptions) error

SetFooter sets or creates a footer for the document

func (*Updater) SetHeader

func (u *Updater) SetHeader(content HeaderFooterContent, opts HeaderOptions) error

SetHeader sets or creates a header for the document

func (*Updater) SetPageLayout

func (u *Updater) SetPageLayout(pageLayout PageLayoutOptions) error

SetPageLayout sets the page layout for the current or last section in the document This modifies the section properties (sectPr) of the document

func (*Updater) SetPageNumber

func (u *Updater) SetPageNumber(opts PageNumberOptions) error

SetPageNumber configures page numbering for the document. It modifies the section properties to set the starting page number and format.

func (*Updater) SetTextWatermark

func (u *Updater) SetTextWatermark(opts WatermarkOptions) error

SetTextWatermark adds a text watermark to the document. The watermark is inserted into the default header so it appears on every page. If a default header already exists, the watermark is injected into it.

func (*Updater) TempDir

func (u *Updater) TempDir() string

TempDir returns the temporary directory where the DOCX was extracted. It is intended for testing and advanced use only. Callers that read or write files directly inside TempDir bypass all validation and relationship tracking performed by the Updater methods.

func (*Updater) UpdateChart

func (u *Updater) UpdateChart(chartIndex int, data ChartData) error

UpdateChart updates one chart by index (1-based).

func (*Updater) UpdateTOC

func (u *Updater) UpdateTOC() error

UpdateTOC marks an existing Table of Contents for update. When the document is opened in Word, it will prompt the user to update the TOC field to reflect the current document headings.

func (*Updater) UpdateTableCell

func (u *Updater) UpdateTableCell(tableIndex, row, col int, value string) error

UpdateTableCell replaces the text content of a cell in an existing table. tableIndex, row, and col are all 1-based.

Note: nested tables (a table inside a table cell) are not supported.

func (*Updater) WrapTextInBookmark

func (u *Updater) WrapTextInBookmark(name, anchorText string) error

WrapTextInBookmark finds existing text in the document and wraps it with a bookmark

type VerticalAlignment

type VerticalAlignment string

VerticalAlignment defines vertical alignment in cells

const (
	VerticalAlignTop    VerticalAlignment = "top"
	VerticalAlignCenter VerticalAlignment = "center"
	VerticalAlignBottom VerticalAlignment = "bottom"
)

type WatermarkOptions

type WatermarkOptions struct {
	// Text to display (e.g., "DRAFT", "CONFIDENTIAL")
	Text string

	// FontFamily for the watermark text (default: "Calibri")
	FontFamily string

	// Color as hex code without '#' (default: "C0C0C0" for silver)
	Color string

	// Opacity from 0.0 to 1.0 (default: 0.5)
	Opacity float64

	// Diagonal rotates text at -45 degrees (default: true)
	Diagonal bool
}

WatermarkOptions defines options for text watermarks

func DefaultWatermarkOptions

func DefaultWatermarkOptions() WatermarkOptions

DefaultWatermarkOptions returns watermark options with sensible defaults

Jump to

Keyboard shortcuts

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