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:
- PositionEnd — appends to the document body
- PositionBeginning — prepends to the document body
- PositionAfterText — inserts after the paragraph containing Anchor text
- PositionBeforeText — inserts before the paragraph containing Anchor text
Document Properties ¶
Properties correspond to the Info panel and Advanced Properties dialog in Microsoft Word.
- Updater.SetCoreProperties / Updater.GetCoreProperties — title, author, keywords, status, dates
- Updater.SetAppProperties / Updater.GetAppProperties — company, manager, template, statistics
- Updater.SetCustomProperties / Updater.GetCustomProperties — user-defined name/value pairs
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
- func FormatCaptionText(opts CaptionOptions) string
- func NewChartNotFoundError(index int) error
- func NewFileNotFoundError(path string) error
- func NewHeaderFooterError(reason string, err error) error
- func NewHyperlinkError(reason string, err error) error
- func NewImageFormatError(format string) error
- func NewImageNotFoundError(path string) error
- func NewInvalidChartDataError(reason string) error
- func NewInvalidFileError(reason string, err error) error
- func NewInvalidRegexError(pattern string, err error) error
- func NewInvalidURLError(url string) error
- func NewRelationshipError(reason string, err error) error
- func NewTextNotFoundError(text string) error
- func NewValidationError(field, reason string) error
- func NewXMLParseError(file string, err error) error
- func NewXMLWriteError(file string, err error) error
- func ValidateCaptionOptions(opts *CaptionOptions) error
- type AppProperties
- type Axis
- type AxisOptions
- type AxisPosition
- type AxisTitle
- type BarChartOptions
- type BarDirection
- type BarGrouping
- type BookmarkOptions
- type BorderStyle
- type BreakOptions
- type CaptionOptions
- type CaptionPosition
- type CaptionType
- type CellAlignment
- type CellStyle
- type Chart
- type ChartData
- type ChartKind
- type ChartOptions
- type ChartProperties
- type ChartSpace
- type ChartStyle
- type ChartTitle
- type ChartType
- type ColumnDefinition
- type Comment
- type CommentOptions
- type CoreProperties
- type CustomProperty
- type DataLabelOptions
- type DataLabelPosition
- type DeleteOptions
- type DocxError
- type EndnoteOptions
- type ErrorCode
- type FindOptions
- type FooterOptions
- type FooterType
- type FootnoteOptions
- type HeaderFooterContent
- type HeaderOptions
- type HeaderType
- type HyperlinkOptions
- type ImageDimensions
- type ImageOptions
- type InsertPosition
- type LegendOptions
- type ListType
- type NumCache
- type NumPt
- type PageLayoutOptions
- func PageLayoutA3Landscape() *PageLayoutOptions
- func PageLayoutA3Portrait() *PageLayoutOptions
- func PageLayoutA4Landscape() *PageLayoutOptions
- func PageLayoutA4Portrait() *PageLayoutOptions
- func PageLayoutLegalPortrait() *PageLayoutOptions
- func PageLayoutLetterLandscape() *PageLayoutOptions
- func PageLayoutLetterPortrait() *PageLayoutOptions
- type PageNumberFormat
- type PageNumberOptions
- type PageOrientation
- type ParagraphAlignment
- type ParagraphOptions
- type ParagraphStyle
- type PlotArea
- type ReplaceOptions
- type RowHeightRule
- type RunOptions
- type ScatterChartOptions
- type SectionBreakType
- type Series
- type SeriesData
- type SeriesOptions
- type SeriesRef
- type SeriesText
- type StrCache
- type StrPt
- type StyleDefinition
- type StyleType
- type TOCEntry
- type TOCOptions
- type TableAlignment
- type TableOptions
- type TableStyle
- type TableWidthType
- type TextMatch
- type TickLabelPosition
- type TickMark
- type TrackedDeleteOptions
- type TrackedInsertOptions
- type Updater
- func (u *Updater) AddBulletItem(text string, level int, position InsertPosition) error
- func (u *Updater) AddBulletList(items []string, level int, position InsertPosition) error
- func (u *Updater) AddHeading(level int, text string, position InsertPosition) error
- func (u *Updater) AddNumberedItem(text string, level int, position InsertPosition) error
- func (u *Updater) AddNumberedList(items []string, level int, position InsertPosition) error
- func (u *Updater) AddStyle(def StyleDefinition) error
- func (u *Updater) AddStyles(defs []StyleDefinition) error
- func (u *Updater) AddText(text string, position InsertPosition) error
- func (u *Updater) Cleanup() error
- func (u *Updater) CreateBookmark(name string, opts BookmarkOptions) error
- func (u *Updater) CreateBookmarkWithText(name, text string, opts BookmarkOptions) error
- func (u *Updater) DeleteChart(chartIndex int) error
- func (u *Updater) DeleteImage(imageIndex int) error
- func (u *Updater) DeleteParagraphs(text string, opts DeleteOptions) (int, error)
- func (u *Updater) DeleteTable(tableIndex int) error
- func (u *Updater) DeleteTrackedText(opts TrackedDeleteOptions) error
- func (u *Updater) FindText(pattern string, opts FindOptions) ([]TextMatch, error)
- func (u *Updater) GetAppProperties() (*AppProperties, error)
- func (u *Updater) GetChartCount() (int, error)
- func (u *Updater) GetChartData(chartIndex int) (ChartData, error)
- func (u *Updater) GetComments() ([]Comment, error)
- func (u *Updater) GetCoreProperties() (*CoreProperties, error)
- func (u *Updater) GetCustomProperties() ([]CustomProperty, error)
- func (u *Updater) GetImageCount() (int, error)
- func (u *Updater) GetParagraphCount() (int, error)
- func (u *Updater) GetParagraphText() ([]string, error)
- func (u *Updater) GetTOCEntries() ([]TOCEntry, error)
- func (u *Updater) GetTableCount() (int, error)
- func (u *Updater) GetTableText() ([][][]string, error)
- func (u *Updater) GetText() (string, error)
- func (u *Updater) InsertChart(opts ChartOptions) error
- func (u *Updater) InsertComment(opts CommentOptions) error
- func (u *Updater) InsertEndnote(opts EndnoteOptions) error
- func (u *Updater) InsertFootnote(opts FootnoteOptions) error
- func (u *Updater) InsertHyperlink(text, urlStr string, opts HyperlinkOptions) error
- func (u *Updater) InsertImage(opts ImageOptions) error
- func (u *Updater) InsertInternalLink(text, bookmarkName string, opts HyperlinkOptions) error
- func (u *Updater) InsertPageBreak(opts BreakOptions) error
- func (u *Updater) InsertParagraph(opts ParagraphOptions) error
- func (u *Updater) InsertParagraphs(paragraphs []ParagraphOptions) error
- func (u *Updater) InsertSectionBreak(opts BreakOptions) error
- func (u *Updater) InsertTOC(opts TOCOptions) error
- func (u *Updater) InsertTable(opts TableOptions) error
- func (u *Updater) InsertTrackedText(opts TrackedInsertOptions) error
- func (u *Updater) MergeTableCellsHorizontal(tableIndex, row, startCol, endCol int) error
- func (u *Updater) MergeTableCellsVertical(tableIndex, startRow, endRow, col int) error
- func (u *Updater) ReplaceText(old, new string, opts ReplaceOptions) (int, error)
- func (u *Updater) ReplaceTextRegex(pattern *regexp.Regexp, replacement string, opts ReplaceOptions) (int, error)
- func (u *Updater) Save(outputPath string) error
- func (u *Updater) SaveToWriter(w io.Writer) error
- func (u *Updater) SetAppProperties(props AppProperties) error
- func (u *Updater) SetCoreProperties(props CoreProperties) error
- func (u *Updater) SetCustomProperties(properties []CustomProperty) error
- func (u *Updater) SetFooter(content HeaderFooterContent, opts FooterOptions) error
- func (u *Updater) SetHeader(content HeaderFooterContent, opts HeaderOptions) error
- func (u *Updater) SetPageLayout(pageLayout PageLayoutOptions) error
- func (u *Updater) SetPageNumber(opts PageNumberOptions) error
- func (u *Updater) SetTextWatermark(opts WatermarkOptions) error
- func (u *Updater) TempDir() string
- func (u *Updater) UpdateChart(chartIndex int, data ChartData) error
- func (u *Updater) UpdateTOC() error
- func (u *Updater) UpdateTableCell(tableIndex, row, col int, value string) error
- func (u *Updater) WrapTextInBookmark(name, anchorText string) error
- type VerticalAlignment
- type WatermarkOptions
Constants ¶
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
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
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
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
const ( BulletListNumID = 1 // Numbering ID for bullet lists NumberedListNumID = 2 // Numbering ID for numbered lists )
List numbering IDs
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 MarginHeaderFooterDefault = 720 )
Page size constants in twips (1/1440 inch)
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 ¶
NewChartNotFoundError creates an error for when a chart is not found
func NewFileNotFoundError ¶
NewFileNotFoundError creates an error for missing files
func NewHeaderFooterError ¶
NewHeaderFooterError creates an error for header/footer operations
func NewHyperlinkError ¶
NewHyperlinkError creates an error for hyperlink creation failures
func NewImageFormatError ¶
NewImageFormatError creates an error for unsupported image formats
func NewImageNotFoundError ¶
NewImageNotFoundError creates an error for when an image file is not found
func NewInvalidChartDataError ¶
NewInvalidChartDataError creates an error for invalid chart data
func NewInvalidFileError ¶
NewInvalidFileError creates an error for invalid DOCX files
func NewInvalidRegexError ¶
NewInvalidRegexError creates an error for invalid regex patterns
func NewInvalidURLError ¶
NewInvalidURLError creates an error for invalid URLs
func NewRelationshipError ¶
NewRelationshipError creates an error for relationship issues
func NewTextNotFoundError ¶
NewTextNotFoundError creates an error for when text is not found in document
func NewValidationError ¶
NewValidationError creates an error for validation failures
func NewXMLParseError ¶
NewXMLParseError creates an error for XML parsing failures
func NewXMLWriteError ¶
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 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 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" 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 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 FooterType
DifferentFirst bool
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 FooterType = "first" FooterEven FooterType = "even" 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 string
CenterText string
RightText string
PageNumber bool
PageNumberFormat string
Date bool
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 ¶
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 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
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 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 ¶
SeriesText contains the series name.
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 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 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 NewBlank ¶ added in v1.8.1
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
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 ¶
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) 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 ¶
DeleteChart removes a chart by index (1-based).
func (*Updater) DeleteImage ¶
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 ¶
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 ¶
GetChartCount returns the number of charts embedded in the document. Returns 0 if the document contains no charts.
func (*Updater) GetChartData ¶
GetChartData reads the categories, series names, and values from chart N (1-based).
func (*Updater) GetComments ¶
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 ¶
GetImageCount returns the number of images in the document
func (*Updater) GetParagraphCount ¶
GetParagraphCount returns the number of paragraphs in the document
func (*Updater) GetParagraphText ¶
GetParagraphText extracts text from all paragraphs
func (*Updater) GetTOCEntries ¶
GetTOCEntries extracts TOC entries from the document. Returns a slice of TOCEntry with level and text.
func (*Updater) GetTableCount ¶
GetTableCount returns the number of tables in the document
func (*Updater) GetTableText ¶
GetTableText extracts text from all tables Returns a 2D slice where each element represents a table, containing rows of cells
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 (*Updater) InsertHyperlink ¶
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 (*Updater) InsertInternalLink ¶
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 ¶
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 ¶
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) SaveToWriter ¶
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 ¶
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 ¶
UpdateChart updates one chart by index (1-based).
func (*Updater) UpdateTOC ¶
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 ¶
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 ¶
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
Source Files
¶
- bookmark.go
- breaks.go
- caption.go
- chart.go
- chart_extended.go
- chart_read.go
- chart_updater.go
- chart_xml.go
- comment.go
- constants.go
- delete.go
- doc.go
- errors.go
- excel_handler.go
- footnote.go
- headerfooter.go
- helpers.go
- hyperlink.go
- image.go
- list.go
- merge.go
- pagenumber.go
- paragraph.go
- properties.go
- read.go
- replace.go
- styles.go
- table.go
- table_update.go
- toc.go
- trackchanges.go
- types.go
- utils.go
- watermark.go