Documentation
¶
Overview ¶
Package docxtpl provides a library for generating DOCX documents from templates using Go's text/template syntax.
This package wraps the go-docx library (github.com/fumiama/go-docx) and adds template rendering capabilities, making it easy to create dynamic Word documents.
Key Features ¶
- Go template syntax ({{.Field}}, {{range}}, {{if}}) in Word documents
- Automatic handling of fragmented XML tags (common in Word's editing)
- Inline image insertion with automatic sizing and DPI detection
- 60+ built-in template functions for text, math, dates, and more
- Support for headers, footers, footnotes, endnotes, and watermarks
- Custom function registration
Basic Usage ¶
Create a Word document with template placeholders like {{.Name}}, then:
doc, err := docxtpl.ParseFromFilename("template.docx")
if err != nil {
log.Fatal(err)
}
data := map[string]any{
"Name": "John Doe",
"Company": "Acme Corp",
}
if err := doc.Render(data); err != nil {
log.Fatal(err)
}
if err := doc.SaveToFile("output.docx"); err != nil {
log.Fatal(err)
}
Template Syntax ¶
The package supports standard Go text/template syntax:
- Simple fields: {{.Name}}
- Nested fields: {{.Person.Address.City}}
- Conditionals: {{if .Active}}...{{end}}
- Loops: {{range .Items}}{{.Name}}{{end}}
- Functions: {{.Name | upper}} or {{formatMoney .Price "$"}}
Built-in Functions ¶
The package includes many built-in functions:
Text: upper, lower, title, bold, italic, underline, color, highlight Numbers: formatNumber, formatMoney, formatPercent, add, sub, mul, div Dates: now, formatDate, parseDate, addDays, addMonths, addYears Collections: len, first, last, join, contains, index, slice Logic: eq, ne, lt, le, gt, ge, and, or, not Utilities: default, ternary, trim, replace, truncate, pluralize
Inline Images ¶
Images can be inserted using file paths (auto-detected) or InlineImage:
// Auto-detect from file path
data := map[string]any{
"Logo": "/path/to/logo.png",
}
// Or use InlineImage for size control
logo, _ := docxtpl.CreateInlineImage("/path/to/logo.png")
logo.Resize(200, 100)
data := map[string]any{
"Logo": logo,
}
Custom Functions ¶
Register custom template functions before rendering:
doc.RegisterFunction("greet", func(name string) string {
return "Hello, " + name + "!"
})
Then use in template: {{greet .Name}}
Data Types ¶
The Render method accepts structs or maps with various field types:
- Primitives: string, int, float64, bool, etc.
- Structs: regular and nested structs
- Pointers: automatically dereferenced
- Slices: []string, []int, []Struct, []*Struct
- Maps: map[string]any, map[string]string, etc.
Index ¶
- Constants
- func BatchProcess(docs []*DocxTmpl, fn func(*DocxTmpl) error) error
- func CompareMetadata(meta1, meta2 *DocumentMetadata) map[string][2]string
- func CompareStats(stats1, stats2 *DocumentStats) map[string]int
- func ProcessDirectory(inputDir, outputDir string, processor func(*DocxTmpl) error) error
- func ReplaceInAll(docs []*DocxTmpl, oldText, newText string)
- func SaveAllToDirectory(docs []*DocxTmpl, dirPath string, names []string) error
- type ArchiveInfo
- type Bookmark
- type Comment
- type DiffItem
- type DiffSummary
- type DiffType
- type DocumentDiff
- type DocumentMetadata
- type DocumentProperties
- type DocumentStats
- type DocxTmpl
- func BatchRender(templates []*DocxTmpl, dataList []any) ([]*DocxTmpl, error)
- func LoadAllFromDirectory(dirPath string) ([]*DocxTmpl, error)
- func MergeDocuments(docs ...*DocxTmpl) (*DocxTmpl, error)
- func New() *DocxTmpl
- func NewWithOptions(pageSize ...PageSize) *DocxTmpl
- func PackFromDirectory(dirPath string) (*DocxTmpl, error)
- func Parse(reader io.ReaderAt, size int64) (*DocxTmpl, error)
- func ParseFromBytes(data []byte) (*DocxTmpl, error)
- func ParseFromFilename(filename string) (*DocxTmpl, error)
- func (d *DocxTmpl) AcceptAllChanges()
- func (d *DocxTmpl) AddBulletList(items []string) *List
- func (d *DocxTmpl) AddChecklist(items map[string]bool) []*Paragraph
- func (d *DocxTmpl) AddChecklistItem(text string, checked bool) *Paragraph
- func (d *DocxTmpl) AddEmptyParagraph() *Paragraph
- func (d *DocxTmpl) AddHeading(text string, level int) *Paragraph
- func (d *DocxTmpl) AddNestedList(listType ListType, items []ListItem) *List
- func (d *DocxTmpl) AddNumberedList(items []string) *List
- func (d *DocxTmpl) AddOrderedChecklist(items []struct{ ... }) []*Paragraph
- func (d *DocxTmpl) AddPageBreak()
- func (d *DocxTmpl) AddParagraph(text string) *Paragraph
- func (d *DocxTmpl) AddSection() *DocxTmpl
- func (d *DocxTmpl) AddSectionBreak(breakType SectionBreakType) *DocxTmpl
- func (d *DocxTmpl) AddTable(rows, cols int) *Table
- func (d *DocxTmpl) AddTableFromCSV(csvStr string) (*Table, error)
- func (d *DocxTmpl) AddTableFromJSON(jsonStr string, headers ...string) (*Table, error)
- func (d *DocxTmpl) AddTableFromSlice(data [][]string) *Table
- func (d *DocxTmpl) AddTableWithBorders(rows, cols int, colors TableBorderColors) *Table
- func (d *DocxTmpl) AddTableWithHeaders(headers []string, data [][]string) *Table
- func (d *DocxTmpl) AddTableWithWidths(rows int, colWidths []int) *Table
- func (d *DocxTmpl) AllowOnlyComments() error
- func (d *DocxTmpl) AllowOnlyFormFilling() error
- func (d *DocxTmpl) AllowOnlyTrackedChanges() error
- func (d *DocxTmpl) AppendDocument(other *DocxTmpl)
- func (d *DocxTmpl) BookmarksSummary() string
- func (d *DocxTmpl) CleanDocument()
- func (d *DocxTmpl) Clone() (*DocxTmpl, error)
- func (d *DocxTmpl) CommentsSummary() string
- func (d *DocxTmpl) CountBookmarks() int
- func (d *DocxTmpl) CountComments() int
- func (d *DocxTmpl) CountParagraphs() int
- func (d *DocxTmpl) CountTables() int
- func (d *DocxTmpl) CountTrackedChanges() (insertions, deletions int)
- func (d *DocxTmpl) DeleteAllComments()
- func (d *DocxTmpl) DiffWith(other *DocxTmpl) *DocumentDiff
- func (d *DocxTmpl) DisableTrackChanges() error
- func (d *DocxTmpl) DropAllDrawings()
- func (d *DocxTmpl) DropCanvas()
- func (d *DocxTmpl) DropEmptyPictures()
- func (d *DocxTmpl) DropGroups()
- func (d *DocxTmpl) DropShapes()
- func (d *DocxTmpl) EnableTrackChanges() error
- func (d *DocxTmpl) EstimatePageCount() int
- func (d *DocxTmpl) FindText(text string) []string
- func (d *DocxTmpl) FindTextMatch(pattern string) []string
- func (d *DocxTmpl) GenerateSampleData() map[string]interface{}
- func (d *DocxTmpl) GetAllHyperlinks() []HyperlinkInfo
- func (d *DocxTmpl) GetAllMedia() []*Media
- func (d *DocxTmpl) GetAllStyles() []string
- func (d *DocxTmpl) GetArchiveInfo() *ArchiveInfo
- func (d *DocxTmpl) GetBookmarkByName(name string) (Bookmark, bool)
- func (d *DocxTmpl) GetBookmarkNames() []string
- func (d *DocxTmpl) GetBookmarks() []Bookmark
- func (d *DocxTmpl) GetChangesByAuthor(author string) []TrackedChange
- func (d *DocxTmpl) GetCommentAuthors() []string
- func (d *DocxTmpl) GetCommentReplies(commentID int) []Comment
- func (d *DocxTmpl) GetComments() []Comment
- func (d *DocxTmpl) GetCommentsByAuthor(author string) []Comment
- func (d *DocxTmpl) GetCommentsInDateRange(start, end time.Time) []Comment
- func (d *DocxTmpl) GetContentTypesXML() (string, error)
- func (d *DocxTmpl) GetDeletions() []TrackedChange
- func (d *DocxTmpl) GetDocumentXML() (string, error)
- func (d *DocxTmpl) GetInsertions() []TrackedChange
- func (d *DocxTmpl) GetInternalLinks() []InternalLink
- func (d *DocxTmpl) GetMedia(name string) *Media
- func (d *DocxTmpl) GetMetadata() *DocumentMetadata
- func (d *DocxTmpl) GetOutline() []OutlineItem
- func (d *DocxTmpl) GetParagraphTexts() []string
- func (d *DocxTmpl) GetPlaceholderSchema() map[string]FieldSchema
- func (d *DocxTmpl) GetPlaceholders() ([]string, error)
- func (d *DocxTmpl) GetProperties() *DocumentProperties
- func (d *DocxTmpl) GetProtectionInfo() *ProtectionInfo
- func (d *DocxTmpl) GetRegisteredFunctions() *template.FuncMap
- func (d *DocxTmpl) GetRelationships() (string, error)
- func (d *DocxTmpl) GetRequiredFields() []FieldInfo
- func (d *DocxTmpl) GetRestrictions() *RestrictionInfo
- func (d *DocxTmpl) GetSettingsXML() (string, error)
- func (d *DocxTmpl) GetStats() *DocumentStats
- func (d *DocxTmpl) GetStylesXML() (string, error)
- func (d *DocxTmpl) GetTableOfContents() []TableOfContentsEntry
- func (d *DocxTmpl) GetText() string
- func (d *DocxTmpl) GetTextByStyle(style string) []string
- func (d *DocxTmpl) GetTopLevelComments() []Comment
- func (d *DocxTmpl) GetTrackedChanges() []TrackedChange
- func (d *DocxTmpl) GetWatermarks() []string
- func (d *DocxTmpl) GetXMLContent(filePath string) (string, error)
- func (d *DocxTmpl) GetXMLFiles() []string
- func (d *DocxTmpl) HasBookmark(name string) bool
- func (d *DocxTmpl) HasComments() bool
- func (d *DocxTmpl) HasTableOfContents() bool
- func (d *DocxTmpl) HasText(text string) bool
- func (d *DocxTmpl) HasTextMatch(pattern string) bool
- func (d *DocxTmpl) HasTrackedChanges() bool
- func (d *DocxTmpl) IsProtected() bool
- func (d *DocxTmpl) IsReadOnly() bool
- func (d *DocxTmpl) IsTrackChangesEnabled() bool
- func (d *DocxTmpl) KeepBodyElements(names ...string)
- func (d *DocxTmpl) MailMerge(records []map[string]any) ([]*DocxTmpl, error)
- func (d *DocxTmpl) MailMergeToFiles(records []map[string]any, filenamePattern string) error
- func (d *DocxTmpl) MailMergeToSingle(records []map[string]any) (*DocxTmpl, error)
- func (d *DocxTmpl) MergeAllRuns()
- func (d *DocxTmpl) NewListBuilder(listType ListType) *ListBuilder
- func (d *DocxTmpl) PreviewRender(data any) (string, error)
- func (d *DocxTmpl) ProtectionSummary() string
- func (d *DocxTmpl) RegisterFuncMap(funcs template.FuncMap)
- func (d *DocxTmpl) RegisterFunction(name string, fn any) error
- func (d *DocxTmpl) RejectAllChanges()
- func (d *DocxTmpl) RemoveProtection() error
- func (d *DocxTmpl) Render(data any) error
- func (d *DocxTmpl) ReplaceText(oldText, newText string)
- func (d *DocxTmpl) ReplaceTextRegex(pattern, replacement string)
- func (d *DocxTmpl) ReplaceWatermark(oldText, newText string)
- func (d *DocxTmpl) Save(writer io.Writer) error
- func (d *DocxTmpl) SaveToFile(filename string) error
- func (d *DocxTmpl) SearchWithContext(searchText string, contextLines int) []SearchResult
- func (d *DocxTmpl) SetAuthor(author string) *DocxTmpl
- func (d *DocxTmpl) SetCategory(category string) *DocxTmpl
- func (d *DocxTmpl) SetContentStatus(status string) *DocxTmpl
- func (d *DocxTmpl) SetDescription(description string) *DocxTmpl
- func (d *DocxTmpl) SetKeywords(keywords string) *DocxTmpl
- func (d *DocxTmpl) SetMetadata(meta *DocumentMetadata)
- func (d *DocxTmpl) SetProperties(props *DocumentProperties)
- func (d *DocxTmpl) SetProtection(protType ProtectionType) error
- func (d *DocxTmpl) SetReadOnly() error
- func (d *DocxTmpl) SetSubject(subject string) *DocxTmpl
- func (d *DocxTmpl) SetTitle(title string) *DocxTmpl
- func (d *DocxTmpl) SetXMLContent(filePath string, content string) error
- func (d *DocxTmpl) SplitAt(rule SplitRule) []*DocxTmpl
- func (d *DocxTmpl) SplitAtHeading(level int) []*DocxTmpl
- func (d *DocxTmpl) SplitAtRegex(pattern string) []*DocxTmpl
- func (d *DocxTmpl) SplitAtText(text string) []*DocxTmpl
- func (d *DocxTmpl) ToHTML() string
- func (d *DocxTmpl) ToJSON() (string, error)
- func (d *DocxTmpl) ToMarkdown() string
- func (d *DocxTmpl) ToStructured() *StructuredDocument
- func (d *DocxTmpl) TrackedChangesSummary() string
- func (d *DocxTmpl) UnpackToDirectory(dirPath string) error
- func (d *DocxTmpl) Validate() *ValidationResult
- func (d *DocxTmpl) ValidateData(data any) []ValidationError
- func (d *DocxTmpl) ValidatePlaceholderSyntax() []ValidationError
- type ErrorCode
- type ErrorSummary
- type FieldInfo
- type FieldSchema
- type Hyperlink
- type HyperlinkInfo
- type ImageInfo
- type IndentOptions
- type InlineImage
- func CreateInlineImage(filepath string) (*InlineImage, error)
- func CreateInlineImageFromBytes(data []byte, ext string) (*InlineImage, error)
- func CreateInlineImageFromURL(url string) (*InlineImage, error)
- func CreateInlineImageFromURLWithTimeout(url string, timeout time.Duration) (*InlineImage, error)
- type InlineImageError
- type InternalLink
- type Justification
- type List
- type ListBuilder
- type ListItem
- type ListType
- type Margins
- type Media
- type Orientation
- type OutlineItem
- type PageSize
- type Paragraph
- func (p *Paragraph) AddAnchorImage(imageData []byte) (*Run, error)
- func (p *Paragraph) AddAnchorImageFromFile(filepath string) (*Run, error)
- func (p *Paragraph) AddAnchorShape(opts ShapeOptions) *Run
- func (p *Paragraph) AddBreak() *Paragraph
- func (p *Paragraph) AddInlineImage(imageData []byte) (*Run, error)
- func (p *Paragraph) AddInlineImageFromFile(filepath string) (*Run, error)
- func (p *Paragraph) AddInlineShape(opts ShapeOptions) *Run
- func (p *Paragraph) AddLink(text, url string) *Hyperlink
- func (p *Paragraph) AddPageBreak() *Paragraph
- func (p *Paragraph) AddTab() *Paragraph
- func (p *Paragraph) AddTabStop(position int, align, leader string) *Paragraph
- func (p *Paragraph) AddTabStops(stops []TabStop) *Paragraph
- func (p *Paragraph) AddText(text string) *Run
- func (p *Paragraph) Background(hexColor string) *Paragraph
- func (p *Paragraph) Bold() *Paragraph
- func (p *Paragraph) Bullet() *Paragraph
- func (p *Paragraph) Center() *Paragraph
- func (p *Paragraph) ClearTabStops() *Paragraph
- func (p *Paragraph) Color(hexColor string) *Paragraph
- func (p *Paragraph) DropAllDrawings() *Paragraph
- func (p *Paragraph) DropCanvas() *Paragraph
- func (p *Paragraph) DropEmptyPictures() *Paragraph
- func (p *Paragraph) DropGroups() *Paragraph
- func (p *Paragraph) DropShapes() *Paragraph
- func (p *Paragraph) Font(fontName string) *Paragraph
- func (p *Paragraph) GetRaw() *docx.Paragraph
- func (p *Paragraph) GetText() string
- func (p *Paragraph) Highlight(color string) *Paragraph
- func (p *Paragraph) Indent(opts IndentOptions) *Paragraph
- func (p *Paragraph) IndentFirstLine(inches float64) *Paragraph
- func (p *Paragraph) IndentHanging(inches float64) *Paragraph
- func (p *Paragraph) IndentLeft(inches float64) *Paragraph
- func (p *Paragraph) IndentRight(inches float64) *Paragraph
- func (p *Paragraph) Italic() *Paragraph
- func (p *Paragraph) Justified() *Paragraph
- func (p *Paragraph) Justify(j Justification) *Paragraph
- func (p *Paragraph) KeepElements(names ...string) *Paragraph
- func (p *Paragraph) Left() *Paragraph
- func (p *Paragraph) LineSpacing(twips int) *Paragraph
- func (p *Paragraph) LineSpacingDouble() *Paragraph
- func (p *Paragraph) LineSpacingOneAndHalf() *Paragraph
- func (p *Paragraph) LineSpacingSingle() *Paragraph
- func (p *Paragraph) MergeAllRuns() *Paragraph
- func (p *Paragraph) MergeRuns() *Paragraph
- func (p *Paragraph) Numbered() *Paragraph
- func (p *Paragraph) Right() *Paragraph
- func (p *Paragraph) Shade(pattern, color, fill string) *Paragraph
- func (p *Paragraph) Size(halfPoints int) *Paragraph
- func (p *Paragraph) SizePoints(points int) *Paragraph
- func (p *Paragraph) Spacing(opts SpacingOptions) *Paragraph
- func (p *Paragraph) SpacingAfter(points int) *Paragraph
- func (p *Paragraph) SpacingBefore(points int) *Paragraph
- func (p *Paragraph) Strike() *Paragraph
- func (p *Paragraph) Style(styleID string) *Paragraph
- func (p *Paragraph) Underline() *Paragraph
- type ProtectionInfo
- type ProtectionType
- type RestrictionInfo
- type Run
- func (r *Run) AddTab() *Run
- func (r *Run) AllCaps() *Run
- func (r *Run) Background(hexColor string) *Run
- func (r *Run) Bold() *Run
- func (r *Run) CharacterSpacing(twips int) *Run
- func (r *Run) Color(hexColor string) *Run
- func (r *Run) Condense(points float64) *Run
- func (r *Run) DoubleStrike() *Run
- func (r *Run) Expand(points float64) *Run
- func (r *Run) Font(fontName string) *Run
- func (r *Run) GetRaw() *docx.Run
- func (r *Run) GetText() string
- func (r *Run) Highlight(color string) *Run
- func (r *Run) Italic() *Run
- func (r *Run) KeepElements(names ...string) *Run
- func (r *Run) Kern(halfPoints int) *Run
- func (r *Run) Shade(pattern, color, fill string) *Run
- func (r *Run) Size(halfPoints int) *Run
- func (r *Run) SizePoints(points int) *Run
- func (r *Run) SmallCaps() *Run
- func (r *Run) Strike() *Run
- func (r *Run) Subscript() *Run
- func (r *Run) Superscript() *Run
- func (r *Run) Then() *Paragraph
- func (r *Run) Underline(style ...string) *Run
- type SearchResult
- type SectionBreakType
- type ShapeOptions
- type ShapePreset
- type SpacingOptions
- type SplitRule
- type StructuredDocument
- type StructuredParagraph
- type StructuredRun
- type StructuredTable
- type TabStop
- type Table
- func (t *Table) AddColumn() *Table
- func (t *Table) AddRow() *TableRow
- func (t *Table) AddRowWithData(values ...string) *TableRow
- func (t *Table) Cell(row, col int) *TableCell
- func (t *Table) Center() *Table
- func (t *Table) ClearColumn(col int) *Table
- func (t *Table) ClearRow(rowIdx int) *Table
- func (t *Table) Cols() int
- func (t *Table) DeleteColumn(index int) *Table
- func (t *Table) DeleteRow(index int) *Table
- func (t *Table) FillColumn(col int, value string) *Table
- func (t *Table) FillRow(rowIdx int, value string) *Table
- func (t *Table) FindAllRows(col int, value string) []int
- func (t *Table) FindRow(col int, value string) int
- func (t *Table) GetColumn(col int) []string
- func (t *Table) GetRaw() *docx.Table
- func (t *Table) GetRowData(rowIdx int) []string
- func (t *Table) InsertColumn(index int) *Table
- func (t *Table) InsertRow(index int) *TableRow
- func (t *Table) Justify(alignment string) *Table
- func (t *Table) Row(index int) *TableRow
- func (t *Table) Rows() int
- func (t *Table) SetAllColumnWidths(widths []int) *Table
- func (t *Table) SetBorderColors(colors TableBorderColors) *Table
- func (t *Table) SetCell(row, col int, text string) *TableCell
- func (t *Table) SetColumnWidth(col int, twips int) *Table
- func (t *Table) SetRowHeight(rowIdx int, twips int) *Table
- func (t *Table) SortByColumn(col int, ascending, skipHeader bool) *Table
- func (t *Table) ToCSV() string
- func (t *Table) ToJSON(headers bool) (string, error)
- func (t *Table) ToSlice() [][]string
- type TableBorderColors
- type TableCell
- func (c *TableCell) AddParagraph(text string) *Paragraph
- func (c *TableCell) Background(hexColor string) *TableCell
- func (c *TableCell) Bold() *TableCell
- func (c *TableCell) Borders(color string, width int) *TableCell
- func (c *TableCell) Center() *TableCell
- func (c *TableCell) GetRaw() *docx.WTableCell
- func (c *TableCell) MergeHorizontal(count int) *TableCell
- func (c *TableCell) MergeVerticalContinue() *TableCell
- func (c *TableCell) MergeVerticalStart() *TableCell
- func (c *TableCell) NoBorders() *TableCell
- func (c *TableCell) SetText(text string) *TableCell
- func (c *TableCell) Shade(pattern, color, fill string) *TableCell
- func (c *TableCell) VAlign(align VerticalAlignment) *TableCell
- func (c *TableCell) VAlignBottom() *TableCell
- func (c *TableCell) VAlignCenter() *TableCell
- func (c *TableCell) VAlignTop() *TableCell
- func (c *TableCell) Width(twips int) *TableCell
- func (c *TableCell) WidthCm(cm float64) *TableCell
- func (c *TableCell) WidthInches(inches float64) *TableCell
- func (c *TableCell) WidthPercent(percent int) *TableCell
- type TableOfContentsEntry
- type TableRow
- type TemplateError
- func ErrFileParse(filename string, cause error) *TemplateError
- func ErrImageLoad(path string, cause error) *TemplateError
- func ErrInvalidFunc(funcName string) *TemplateError
- func ErrSyntax(message string) *TemplateError
- func ErrUnclosedTag(location string) *TemplateError
- func ErrUndefinedField(field string, location string) *TemplateError
- func ErrUnmatchedEnd(tag string, location string) *TemplateError
- func IsTemplateError(err error) (*TemplateError, bool)
- func NewTemplateError(code ErrorCode, message string) *TemplateError
- func (e *TemplateError) Error() string
- func (e *TemplateError) String() string
- func (e *TemplateError) Unwrap() error
- func (e *TemplateError) WithCause(cause error) *TemplateError
- func (e *TemplateError) WithLocation(location string) *TemplateError
- func (e *TemplateError) WithPlaceholder(placeholder string) *TemplateError
- func (e *TemplateError) WithSuggestions(suggestions ...string) *TemplateError
- type TrackedChange
- type TrackedChangeType
- type TrackedChangesConfig
- type UnpackedDocument
- type ValidationError
- type ValidationErrorType
- type ValidationResult
- type VerticalAlignment
- type XMLFile
Constants ¶
const ( EMUS_PER_INCH = 914400 DEFAULT_DPI = 72 )
const ( PageWidthA4 = 8.27 PageHeightA4 = 11.69 PageWidthA3 = 11.69 PageHeightA3 = 16.54 PageWidthLetter = 8.5 PageHeightLetter = 11.0 PageWidthLegal = 8.5 PageHeightLegal = 14.0 )
Custom page size constants (in inches)
Variables ¶
This section is empty.
Functions ¶
func BatchProcess ¶ added in v0.1.1
BatchProcess applies a function to each document in a list.
err := docxtpl.BatchProcess(docs, func(doc *DocxTmpl) error {
doc.ReplaceText("COMPANY", "Acme Corp")
return nil
})
func CompareMetadata ¶ added in v0.1.1
func CompareMetadata(meta1, meta2 *DocumentMetadata) map[string][2]string
CompareMetadata compares document metadata
func CompareStats ¶ added in v0.1.1
func CompareStats(stats1, stats2 *DocumentStats) map[string]int
CompareStats compares document statistics
statsDiff := docxtpl.CompareStats(doc1.GetStats(), doc2.GetStats())
func ProcessDirectory ¶ added in v0.1.1
ProcessDirectory processes all .docx files in a directory.
err := docxtpl.ProcessDirectory("input/", "output/", func(doc *DocxTmpl) error {
return doc.Render(data)
})
func ReplaceInAll ¶ added in v0.1.1
ReplaceInAll replaces text in all provided documents.
docxtpl.ReplaceInAll(docs, "OLD", "NEW")
Types ¶
type ArchiveInfo ¶ added in v0.1.1
type ArchiveInfo struct {
TotalFiles int // Total number of files in archive
XMLFiles int // Number of XML files
MediaFiles int // Number of media files
TotalSize int64 // Total uncompressed size
FileList []string // List of all file paths
HasComments bool // Whether the document has comments.xml
HasSettings bool // Whether the document has settings.xml
HasFootnotes bool // Whether the document has footnotes.xml
HasEndnotes bool // Whether the document has endnotes.xml
}
ArchiveInfo returns information about the DOCX archive.
type Bookmark ¶ added in v0.1.1
type Bookmark struct {
ID int // Bookmark ID
Name string // Bookmark name
Text string // Text content at the bookmark location
}
Bookmark represents a bookmark in the document
type Comment ¶ added in v0.1.1
type Comment struct {
ID int // Comment ID
Author string // Comment author
Initials string // Author initials
Date time.Time // When the comment was created
Text string // Comment text content
ParentID int // Parent comment ID for replies (-1 if not a reply)
Paragraph int // Paragraph index where comment is attached
}
Comment represents a comment in the document
type DiffItem ¶ added in v0.1.1
type DiffItem struct {
Type DiffType // Type of change
Location string // Where the change occurred (paragraph index, table location, etc.)
OldValue string // Original value (empty for additions)
NewValue string // New value (empty for removals)
}
DiffItem represents a single difference between two documents
type DiffSummary ¶ added in v0.1.1
type DiffSummary struct {
TotalChanges int
AddedParagraphs int
RemovedParagraphs int
ModifiedParagraphs int
AddedTables int
RemovedTables int
}
DiffSummary contains summary statistics of differences
type DocumentDiff ¶ added in v0.1.1
type DocumentDiff struct {
Added []DiffItem // Content added in the new document
Removed []DiffItem // Content removed from the original
Modified []DiffItem // Content that was modified
Summary DiffSummary
}
DocumentDiff represents the differences between two documents
func CompareDocuments ¶ added in v0.1.1
func CompareDocuments(doc1, doc2 *DocxTmpl) *DocumentDiff
CompareDocuments compares two documents and returns their differences.
doc1, _ := docxtpl.ParseFromFilename("version1.docx")
doc2, _ := docxtpl.ParseFromFilename("version2.docx")
diff := docxtpl.CompareDocuments(doc1, doc2)
func (*DocumentDiff) GetChanges ¶ added in v0.1.1
func (d *DocumentDiff) GetChanges() []DiffItem
GetChanges returns all changes as a flat list
func (*DocumentDiff) HasChanges ¶ added in v0.1.1
func (d *DocumentDiff) HasChanges() bool
HasChanges returns true if there are any differences
func (*DocumentDiff) String ¶ added in v0.1.1
func (d *DocumentDiff) String() string
String returns a human-readable summary of changes
type DocumentMetadata ¶ added in v0.1.1
type DocumentMetadata struct {
Title string
Subject string
Creator string // Author
Keywords string
Description string
LastModifiedBy string
Revision string
Created time.Time
Modified time.Time
Category string
ContentStatus string
Language string
}
DocumentMetadata contains document properties.
type DocumentProperties ¶ added in v0.1.1
type DocumentProperties struct {
Title string
Subject string
Creator string // Author
Keywords string
Description string
LastModifiedBy string
Revision string
Created time.Time
Modified time.Time
Category string
ContentStatus string // e.g., "Draft", "Final"
}
DocumentProperties contains the core document metadata.
type DocumentStats ¶ added in v0.1.1
type DocumentStats struct {
ParagraphCount int
TableCount int
WordCount int
CharCount int // without spaces
CharCountSpace int // with spaces
LineCount int
ImageCount int
LinkCount int
}
DocumentStats contains document statistics.
type DocxTmpl ¶
func BatchRender ¶ added in v0.1.1
BatchRender renders multiple templates with corresponding data.
docs, err := docxtpl.BatchRender(templates, dataList)
func LoadAllFromDirectory ¶ added in v0.1.1
LoadAllFromDirectory loads all .docx files from a directory.
docs, err := docxtpl.LoadAllFromDirectory("templates/")
func MergeDocuments ¶ added in v0.1.1
MergeDocuments combines multiple documents into one. Documents are appended in order with page breaks between them.
merged := docxtpl.MergeDocuments(doc1, doc2, doc3)
func New ¶ added in v0.1.1
func New() *DocxTmpl
New creates a new empty document from scratch. Use this when you want to build a document programmatically without a template.
doc := docxtpl.New()
doc.AddHeading("My Document", 1)
doc.AddParagraph("Hello, World!")
doc.SaveToFile("output.docx")
func NewWithOptions ¶ added in v0.1.1
NewWithOptions creates a new document with optional configuration.
doc := docxtpl.NewWithOptions(docxtpl.PageSizeA4)
func PackFromDirectory ¶ added in v0.1.1
PackFromDirectory creates a DOCX file from an unpacked directory. This is the reverse of UnpackToDirectory.
doc, err := docxtpl.PackFromDirectory("/tmp/unpacked")
func Parse ¶
Parse the document from a reader and store it in memory. You can it invoke from a file.
reader, err := os.Open("path_to_doc.docx")
if err != nil {
panic(err)
}
fileinfo, err := reader.Stat()
if err != nil {
panic(err)
}
size := fileinfo.Size()
doc, err := docxtpl.Parse(reader, int64(size))
func ParseFromBytes ¶
Parse the document from a byte slice and store it in memory. Useful for documents loaded from HTTP responses or other in-memory sources.
data, err := io.ReadAll(resp.Body)
if err != nil {
panic(err)
}
doc, err := docxtpl.ParseFromBytes(data)
func ParseFromFilename ¶
Parse the document from a filename and store it in memory.
doc, err := docxtpl.ParseFromFilename("path_to_doc.docx")
func (*DocxTmpl) AcceptAllChanges ¶ added in v0.1.1
func (d *DocxTmpl) AcceptAllChanges()
AcceptAllChanges accepts all tracked changes, making insertions permanent and removing deleted text. Note: This modifies the processable files (headers, footers, etc.). Document body changes require re-parsing after save.
doc.AcceptAllChanges()
func (*DocxTmpl) AddBulletList ¶ added in v0.1.1
AddBulletList adds a bullet list to the document. Each string in items becomes a bullet point.
doc.AddBulletList([]string{"First item", "Second item", "Third item"})
func (*DocxTmpl) AddChecklist ¶ added in v0.1.1
AddChecklist adds a checklist to the document. items is a map of text to checked status.
doc.AddChecklist(map[string]bool{
"Task 1": true,
"Task 2": false,
"Task 3": false,
})
func (*DocxTmpl) AddChecklistItem ¶ added in v0.1.1
AddChecklistItem adds a checkbox item to the document. checked determines if the checkbox appears checked.
doc.AddChecklistItem("Complete task", true)
doc.AddChecklistItem("Pending task", false)
func (*DocxTmpl) AddEmptyParagraph ¶ added in v0.1.1
AddEmptyParagraph adds an empty paragraph to the document. Useful for adding spacing between elements.
func (*DocxTmpl) AddHeading ¶ added in v0.1.1
AddHeading adds a heading with the specified level (0-9). Level 0 is the document title, level 1 is Heading 1, etc.
doc.AddHeading("Chapter 1", 1)
doc.AddHeading("Section 1.1", 2)
func (*DocxTmpl) AddNestedList ¶ added in v0.1.1
AddNestedList adds a nested list with multiple levels. Use ListItem.Level to control indentation (0-8). Use ListItem.Children for nested items.
doc.AddNestedList(ListTypeBullet, []ListItem{
{Text: "Item 1", Children: []ListItem{
{Text: "Sub-item 1.1"},
{Text: "Sub-item 1.2"},
}},
{Text: "Item 2"},
})
func (*DocxTmpl) AddNumberedList ¶ added in v0.1.1
AddNumberedList adds a numbered list to the document. Each string in items becomes a numbered item (1, 2, 3...).
doc.AddNumberedList([]string{"First step", "Second step", "Third step"})
func (*DocxTmpl) AddOrderedChecklist ¶ added in v0.1.1
AddOrderedChecklist adds a checklist with preserved order.
doc.AddOrderedChecklist([]struct{Text string; Checked bool}{
{"Task 1", true},
{"Task 2", false},
})
func (*DocxTmpl) AddPageBreak ¶ added in v0.1.1
func (d *DocxTmpl) AddPageBreak()
AddPageBreak inserts a page break at the current position.
func (*DocxTmpl) AddParagraph ¶ added in v0.1.1
AddParagraph adds a new paragraph with the given text to the document. Returns a Paragraph wrapper for further formatting.
para := doc.AddParagraph("Hello, World!")
para.Bold().Color("FF0000")
func (*DocxTmpl) AddSection ¶ added in v0.1.1
AddSection adds a new section with a page break. This is a convenience method for common use cases.
doc.AddSection()
func (*DocxTmpl) AddSectionBreak ¶ added in v0.1.1
func (d *DocxTmpl) AddSectionBreak(breakType SectionBreakType) *DocxTmpl
AddSectionBreak adds a visual section break to the document. For SectionBreakNextPage, this creates a page break. For other types, it creates appropriate spacing.
doc.AddSectionBreak(SectionBreakNextPage)
func (*DocxTmpl) AddTable ¶ added in v0.1.1
AddTable creates a new table with the specified number of rows and columns. Returns a Table wrapper for populating and formatting.
table := doc.AddTable(3, 4) // 3 rows, 4 columns table.SetCell(0, 0, "Header 1")
func (*DocxTmpl) AddTableFromCSV ¶ added in v0.1.1
AddTableFromCSV creates a table from CSV data.
doc.AddTableFromCSV("Name,Age\nJohn,30\nJane,25")
func (*DocxTmpl) AddTableFromJSON ¶ added in v0.1.1
AddTableFromJSON creates a table from JSON data. Accepts either [][]string or []map[string]string format.
doc.AddTableFromJSON(`[["A","B"],["1","2"]]`)
doc.AddTableFromJSON(`[{"Name":"John","Age":"30"}]`)
func (*DocxTmpl) AddTableFromSlice ¶ added in v0.1.1
AddTableFromSlice creates a table from a 2D string slice.
doc.AddTableFromSlice([][]string{{"A","B"},{"1","2"}})
func (*DocxTmpl) AddTableWithBorders ¶ added in v0.1.1
func (d *DocxTmpl) AddTableWithBorders(rows, cols int, colors TableBorderColors) *Table
AddTableWithBorders creates a table with custom border colors. Use TableBorderColors to specify colors for each border type.
doc.AddTableWithBorders(3, 4, TableBorderColors{
Top: "FF0000", Bottom: "FF0000",
Left: "0000FF", Right: "0000FF",
InsideH: "00FF00", InsideV: "00FF00",
})
func (*DocxTmpl) AddTableWithHeaders ¶ added in v0.1.1
AddTableWithHeaders creates a table with a header row. The first row is automatically bolded and centered.
doc.AddTableWithHeaders([]string{"Name", "Age", "City"}, [][]string{
{"John", "30", "NYC"},
{"Jane", "25", "LA"},
})
func (*DocxTmpl) AddTableWithWidths ¶ added in v0.1.1
AddTableWithWidths creates a table with custom column widths (in twips). 1 inch = 1440 twips, 1 cm = 567 twips.
doc.AddTableWithWidths(3, []int{2880, 1440, 1440}) // 3 rows, columns: 2", 1", 1"
func (*DocxTmpl) AllowOnlyComments ¶ added in v0.1.1
AllowOnlyComments sets protection to allow only comments.
err := doc.AllowOnlyComments()
func (*DocxTmpl) AllowOnlyFormFilling ¶ added in v0.1.1
AllowOnlyFormFilling sets protection to allow only form filling.
err := doc.AllowOnlyFormFilling()
func (*DocxTmpl) AllowOnlyTrackedChanges ¶ added in v0.1.1
AllowOnlyTrackedChanges sets protection to allow only tracked changes.
err := doc.AllowOnlyTrackedChanges()
func (*DocxTmpl) AppendDocument ¶ added in v0.1.1
AppendDocument appends all contents from another document to this document. This is useful for merging multiple documents into one.
doc1, _ := docxtpl.ParseFromFilename("chapter1.docx")
doc2, _ := docxtpl.ParseFromFilename("chapter2.docx")
doc1.AppendDocument(doc2)
doc1.SaveToFile("combined.docx")
func (*DocxTmpl) BookmarksSummary ¶ added in v0.1.1
BookmarksSummary returns a text summary of all bookmarks.
summary := doc.BookmarksSummary()
func (*DocxTmpl) CleanDocument ¶ added in v0.1.1
func (d *DocxTmpl) CleanDocument()
CleanDocument performs common cleanup operations: - Merges runs with same formatting - Removes empty picture references This is useful before saving to reduce file size.
func (*DocxTmpl) Clone ¶ added in v0.1.1
Clone creates a deep copy of the document. The cloned document can be modified independently.
clone := doc.Clone()
clone.Render(differentData)
clone.SaveToFile("copy.docx")
func (*DocxTmpl) CommentsSummary ¶ added in v0.1.1
CommentsSummary returns a text summary of all comments.
summary := doc.CommentsSummary() fmt.Println(summary)
func (*DocxTmpl) CountBookmarks ¶ added in v0.1.1
CountBookmarks returns the total number of bookmarks in the document.
count := doc.CountBookmarks()
func (*DocxTmpl) CountComments ¶ added in v0.1.1
CountComments returns the total number of comments in the document.
count := doc.CountComments()
func (*DocxTmpl) CountParagraphs ¶ added in v0.1.1
CountParagraphs returns the number of paragraphs in the document.
func (*DocxTmpl) CountTables ¶ added in v0.1.1
CountTables returns the number of tables in the document.
func (*DocxTmpl) CountTrackedChanges ¶ added in v0.1.1
CountTrackedChanges returns the count of tracked changes by type.
ins, del := doc.CountTrackedChanges()
func (*DocxTmpl) DeleteAllComments ¶ added in v0.1.1
func (d *DocxTmpl) DeleteAllComments()
DeleteAllComments removes all comments from the document. This modifies the comments.xml file.
doc.DeleteAllComments()
func (*DocxTmpl) DiffWith ¶ added in v0.1.1
func (d *DocxTmpl) DiffWith(other *DocxTmpl) *DocumentDiff
DiffWith compares this document with another and returns differences.
diff := doc1.DiffWith(doc2)
func (*DocxTmpl) DisableTrackChanges ¶ added in v0.1.1
DisableTrackChanges disables track changes mode in document settings.
doc.DisableTrackChanges()
func (*DocxTmpl) DropAllDrawings ¶ added in v0.1.1
func (d *DocxTmpl) DropAllDrawings()
DropAllDrawings removes all shapes, canvases, and groups from the entire document. This is useful for extracting just the text content.
func (*DocxTmpl) DropCanvas ¶ added in v0.1.1
func (d *DocxTmpl) DropCanvas()
DropCanvas removes all canvas elements from the entire document.
func (*DocxTmpl) DropEmptyPictures ¶ added in v0.1.1
func (d *DocxTmpl) DropEmptyPictures()
DropEmptyPictures removes all nil/empty picture references from the document.
func (*DocxTmpl) DropGroups ¶ added in v0.1.1
func (d *DocxTmpl) DropGroups()
DropGroups removes all group elements from the entire document.
func (*DocxTmpl) DropShapes ¶ added in v0.1.1
func (d *DocxTmpl) DropShapes()
DropShapes removes all shapes from the entire document.
func (*DocxTmpl) EnableTrackChanges ¶ added in v0.1.1
EnableTrackChanges enables track changes mode in document settings. Note: This modifies settings.xml to enable revision tracking. Requires settings.xml to be in processable files.
doc.EnableTrackChanges()
func (*DocxTmpl) EstimatePageCount ¶ added in v0.1.1
EstimatePageCount estimates the number of pages in the document. This is a rough estimate based on paragraph count and assumes: - Single spacing, 12pt font - About 50 lines per page for Letter size - Tables count as 3 paragraphs
pages := doc.EstimatePageCount()
func (*DocxTmpl) FindText ¶ added in v0.1.1
FindText returns all paragraphs containing the specified text.
func (*DocxTmpl) FindTextMatch ¶ added in v0.1.1
FindTextMatch returns all paragraphs matching the regex pattern.
func (*DocxTmpl) GenerateSampleData ¶ added in v0.1.1
GenerateSampleData generates sample data matching the template placeholders. This is useful for testing and documentation.
sample := doc.GenerateSampleData()
func (*DocxTmpl) GetAllHyperlinks ¶ added in v0.1.1
func (d *DocxTmpl) GetAllHyperlinks() []HyperlinkInfo
GetAllHyperlinks returns all hyperlinks in the document.
links := doc.GetAllHyperlinks()
for _, link := range links {
fmt.Printf("%s -> %s\n", link.Text, link.URL)
}
func (*DocxTmpl) GetAllMedia ¶ added in v0.1.1
GetAllMedia returns all embedded media files in the document.
mediaFiles := doc.GetAllMedia()
for _, m := range mediaFiles {
os.WriteFile(m.Name, m.Data, 0644)
}
func (*DocxTmpl) GetAllStyles ¶ added in v0.1.1
GetAllStyles returns all paragraph styles used in the document.
styles := doc.GetAllStyles() // Returns: ["Normal", "Heading1", "Heading2", ...]
func (*DocxTmpl) GetArchiveInfo ¶ added in v0.1.1
func (d *DocxTmpl) GetArchiveInfo() *ArchiveInfo
GetArchiveInfo returns information about the DOCX archive structure.
info := doc.GetArchiveInfo()
fmt.Printf("Total files: %d\n", info.TotalFiles)
func (*DocxTmpl) GetBookmarkByName ¶ added in v0.1.1
GetBookmarkByName returns a bookmark by its name.
bookmark, found := doc.GetBookmarkByName("Chapter1")
func (*DocxTmpl) GetBookmarkNames ¶ added in v0.1.1
GetBookmarkNames returns just the names of all bookmarks.
names := doc.GetBookmarkNames()
func (*DocxTmpl) GetBookmarks ¶ added in v0.1.1
GetBookmarks extracts all bookmarks from the document. Bookmarks are named locations in the document that can be linked to.
bookmarks := doc.GetBookmarks()
for _, b := range bookmarks {
fmt.Printf("%s (ID: %d)\n", b.Name, b.ID)
}
func (*DocxTmpl) GetChangesByAuthor ¶ added in v0.1.1
func (d *DocxTmpl) GetChangesByAuthor(author string) []TrackedChange
GetChangesByAuthor returns tracked changes filtered by author.
claudeChanges := doc.GetChangesByAuthor("Claude")
func (*DocxTmpl) GetCommentAuthors ¶ added in v0.1.1
GetCommentAuthors returns a list of unique comment authors.
authors := doc.GetCommentAuthors()
func (*DocxTmpl) GetCommentReplies ¶ added in v0.1.1
GetCommentReplies returns all replies to a specific comment.
replies := doc.GetCommentReplies(0) // Get replies to comment with ID 0
func (*DocxTmpl) GetComments ¶ added in v0.1.1
GetComments extracts all comments from the document. Returns both top-level comments and replies.
comments := doc.GetComments()
for _, c := range comments {
fmt.Printf("[%s] %s: %s\n", c.Date.Format("2006-01-02"), c.Author, c.Text)
}
func (*DocxTmpl) GetCommentsByAuthor ¶ added in v0.1.1
GetCommentsByAuthor returns comments filtered by author name.
myComments := doc.GetCommentsByAuthor("John Doe")
func (*DocxTmpl) GetCommentsInDateRange ¶ added in v0.1.1
GetCommentsInDateRange returns comments within a specific date range.
start := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC) end := time.Date(2024, 12, 31, 23, 59, 59, 0, time.UTC) comments := doc.GetCommentsInDateRange(start, end)
func (*DocxTmpl) GetContentTypesXML ¶ added in v0.1.1
GetContentTypesXML returns the content types XML.
types, err := doc.GetContentTypesXML()
func (*DocxTmpl) GetDeletions ¶ added in v0.1.1
func (d *DocxTmpl) GetDeletions() []TrackedChange
GetDeletions returns only deletion changes.
deletions := doc.GetDeletions()
func (*DocxTmpl) GetDocumentXML ¶ added in v0.1.1
GetDocumentXML returns the main document XML.
xml, err := doc.GetDocumentXML()
func (*DocxTmpl) GetInsertions ¶ added in v0.1.1
func (d *DocxTmpl) GetInsertions() []TrackedChange
GetInsertions returns only insertion changes.
insertions := doc.GetInsertions()
func (*DocxTmpl) GetInternalLinks ¶ added in v0.1.1
func (d *DocxTmpl) GetInternalLinks() []InternalLink
GetInternalLinks returns all internal hyperlinks (links to bookmarks).
links := doc.GetInternalLinks()
func (*DocxTmpl) GetMedia ¶ added in v0.1.1
GetMedia retrieves an embedded media file by name. Returns nil if the media is not found.
media := doc.GetMedia("image1.png")
if media != nil {
os.WriteFile("extracted.png", media.Data, 0644)
}
func (*DocxTmpl) GetMetadata ¶ added in v0.1.1
func (d *DocxTmpl) GetMetadata() *DocumentMetadata
GetMetadata extracts document metadata from core.xml and app.xml. Returns empty values for fields not found in the document.
meta := doc.GetMetadata()
fmt.Println("Author:", meta.Creator)
func (*DocxTmpl) GetOutline ¶ added in v0.1.1
func (d *DocxTmpl) GetOutline() []OutlineItem
GetOutline extracts the document structure as a hierarchical outline. Returns headings organized by their levels.
outline := doc.GetOutline()
for _, item := range outline {
fmt.Printf("H%d: %s\n", item.Level, item.Text)
}
func (*DocxTmpl) GetParagraphTexts ¶ added in v0.1.1
GetParagraphTexts returns the text content of each paragraph as a slice.
paragraphs := doc.GetParagraphTexts()
func (*DocxTmpl) GetPlaceholderSchema ¶ added in v0.1.1
func (d *DocxTmpl) GetPlaceholderSchema() map[string]FieldSchema
GetPlaceholderSchema returns a schema-like map of all placeholders. Useful for generating data templates or documentation.
schema := doc.GetPlaceholderSchema()
func (*DocxTmpl) GetPlaceholders ¶
GetPlaceholders returns a list of all unique placeholders found in the document. This is useful for validating templates or showing what data is expected. Placeholders are returned in the format they appear (e.g., "{{.Name}}", "{{range .Items}}").
placeholders, err := doc.GetPlaceholders()
// Returns: []string{"{{.FirstName}}", "{{.LastName}}", "{{range .Items}}", "{{end}}"}
func (*DocxTmpl) GetProperties ¶ added in v0.1.1
func (d *DocxTmpl) GetProperties() *DocumentProperties
GetProperties returns the document properties. For documents created from scratch, this returns default/empty properties. For parsed documents, this extracts properties from docProps/core.xml.
func (*DocxTmpl) GetProtectionInfo ¶ added in v0.1.1
func (d *DocxTmpl) GetProtectionInfo() *ProtectionInfo
GetProtectionInfo returns information about document protection.
info := doc.GetProtectionInfo()
if info.IsProtected {
fmt.Printf("Document is protected: %s\n", info.Type)
}
func (*DocxTmpl) GetRegisteredFunctions ¶
Get a pointer to the documents function map. This will include built-in functions.
func (*DocxTmpl) GetRelationships ¶ added in v0.1.1
GetRelationships returns the document relationships.
rels, err := doc.GetRelationships()
func (*DocxTmpl) GetRequiredFields ¶ added in v0.1.1
GetRequiredFields returns information about all fields required by the template.
fields := doc.GetRequiredFields()
for _, f := range fields {
fmt.Printf("Field: %s, Occurrences: %d\n", f.Name, f.Occurrences)
}
func (*DocxTmpl) GetRestrictions ¶ added in v0.1.1
func (d *DocxTmpl) GetRestrictions() *RestrictionInfo
GetRestrictions returns detailed information about what actions are allowed.
restrictions := doc.GetRestrictions()
if restrictions.CanComment {
fmt.Println("Comments are allowed")
}
func (*DocxTmpl) GetSettingsXML ¶ added in v0.1.1
GetSettingsXML returns the settings XML.
settings, err := doc.GetSettingsXML()
func (*DocxTmpl) GetStats ¶ added in v0.1.1
func (d *DocxTmpl) GetStats() *DocumentStats
GetStats returns document statistics including word count, paragraph count, etc.
stats := doc.GetStats()
fmt.Printf("Words: %d, Paragraphs: %d\n", stats.WordCount, stats.ParagraphCount)
func (*DocxTmpl) GetStylesXML ¶ added in v0.1.1
GetStylesXML returns the styles XML.
styles, err := doc.GetStylesXML()
func (*DocxTmpl) GetTableOfContents ¶ added in v0.1.1
func (d *DocxTmpl) GetTableOfContents() []TableOfContentsEntry
GetTableOfContents extracts the table of contents if present. Returns nil if no TOC is found.
toc := doc.GetTableOfContents()
func (*DocxTmpl) GetText ¶ added in v0.1.1
GetText extracts all plain text from the document body. Paragraphs are separated by newlines.
text := doc.GetText()
func (*DocxTmpl) GetTextByStyle ¶ added in v0.1.1
GetTextByStyle returns all text from paragraphs with the specified style.
headings := doc.GetTextByStyle("Heading1")
func (*DocxTmpl) GetTopLevelComments ¶ added in v0.1.1
GetTopLevelComments returns only top-level comments (not replies).
topComments := doc.GetTopLevelComments()
func (*DocxTmpl) GetTrackedChanges ¶ added in v0.1.1
func (d *DocxTmpl) GetTrackedChanges() []TrackedChange
GetTrackedChanges extracts all tracked changes from the document. Returns insertions and deletions found in the document XML.
changes := doc.GetTrackedChanges()
for _, change := range changes {
fmt.Printf("%s by %s: %s\n", change.Type, change.Author, change.Text)
}
func (*DocxTmpl) GetWatermarks ¶
GetWatermarks returns all watermark texts found in the document headers. Watermarks are stored as VML shapes with textpath elements in header files.
func (*DocxTmpl) GetXMLContent ¶ added in v0.1.1
GetXMLContent returns the content of a specific XML file within the document.
content, err := doc.GetXMLContent("word/document.xml")
func (*DocxTmpl) GetXMLFiles ¶ added in v0.1.1
GetXMLFiles returns a list of all XML files in the document.
files := doc.GetXMLFiles()
for _, f := range files {
fmt.Println(f)
}
func (*DocxTmpl) HasBookmark ¶ added in v0.1.1
HasBookmark checks if a bookmark with the given name exists.
if doc.HasBookmark("Chapter1") {
fmt.Println("Found Chapter1 bookmark")
}
func (*DocxTmpl) HasComments ¶ added in v0.1.1
HasComments returns true if the document contains any comments.
if doc.HasComments() {
fmt.Println("Document has comments")
}
func (*DocxTmpl) HasTableOfContents ¶ added in v0.1.1
HasTableOfContents checks if the document has a table of contents.
if doc.HasTableOfContents() {
fmt.Println("Document has TOC")
}
func (*DocxTmpl) HasText ¶ added in v0.1.1
HasText checks if the document contains the specified text.
if doc.HasText("confidential") {
// Handle confidential document
}
func (*DocxTmpl) HasTextMatch ¶ added in v0.1.1
HasTextMatch checks if the document contains text matching the regex pattern.
if doc.HasTextMatch(`\d{3}-\d{2}-\d{4}`) {
// Document contains SSN pattern
}
func (*DocxTmpl) HasTrackedChanges ¶ added in v0.1.1
HasTrackedChanges returns true if the document contains any tracked changes.
if doc.HasTrackedChanges() {
fmt.Println("Document has pending changes")
}
func (*DocxTmpl) IsProtected ¶ added in v0.1.1
IsProtected returns true if the document has any protection enabled.
if doc.IsProtected() {
fmt.Println("Document is protected")
}
func (*DocxTmpl) IsReadOnly ¶ added in v0.1.1
IsReadOnly returns true if the document is read-only protected.
if doc.IsReadOnly() {
fmt.Println("Document is read-only")
}
func (*DocxTmpl) IsTrackChangesEnabled ¶ added in v0.1.1
IsTrackChangesEnabled checks if track changes mode is enabled.
if doc.IsTrackChangesEnabled() {
fmt.Println("Track changes is enabled")
}
func (*DocxTmpl) KeepBodyElements ¶ added in v0.1.1
KeepBodyElements keeps only specified element types in the document body. Valid names: "*docx.Paragraph", "*docx.Table"
doc.KeepBodyElements("*docx.Paragraph") // Keep only paragraphs, remove tables
func (*DocxTmpl) MailMerge ¶ added in v0.1.1
MailMerge renders the template with multiple data records. Returns a slice of rendered documents, one per record.
records := []map[string]any{
{"Name": "John", "Email": "john@example.com"},
{"Name": "Jane", "Email": "jane@example.com"},
}
docs, err := template.MailMerge(records)
func (*DocxTmpl) MailMergeToFiles ¶ added in v0.1.1
MailMergeToFiles renders the template and saves each result to a file. filenamePattern should contain %d for the record number (e.g., "letter_%d.docx").
err := template.MailMergeToFiles(records, "output/letter_%d.docx")
func (*DocxTmpl) MailMergeToSingle ¶ added in v0.1.1
MailMergeToSingle renders the template with multiple records and combines into a single document with page breaks between each.
merged, err := template.MailMergeToSingle(records)
func (*DocxTmpl) MergeAllRuns ¶ added in v0.1.1
func (d *DocxTmpl) MergeAllRuns()
MergeAllRuns merges contiguous runs with same formatting in all paragraphs. This reduces document complexity and can decrease file size.
func (*DocxTmpl) NewListBuilder ¶ added in v0.1.1
func (d *DocxTmpl) NewListBuilder(listType ListType) *ListBuilder
NewListBuilder creates a new list builder
list := doc.NewListBuilder(ListTypeBullet).
Item("First").
Item("Second").
Indent().Item("Nested").
Outdent().Item("Third").
Build()
func (*DocxTmpl) PreviewRender ¶ added in v0.1.1
PreviewRender renders the template with data but returns the text content instead of saving to a file. Useful for validation and previewing.
preview, err := doc.PreviewRender(data)
func (*DocxTmpl) ProtectionSummary ¶ added in v0.1.1
ProtectionSummary returns a text summary of protection status.
summary := doc.ProtectionSummary()
func (*DocxTmpl) RegisterFuncMap ¶ added in v0.2.0
RegisterFuncMap registers all functions from a template.FuncMap. This is useful for adding external function libraries like Sprig.
doc.RegisterFuncMap(sprig.FuncMap())
func (*DocxTmpl) RegisterFunction ¶
Register a function which can then be used within your template
d.RegisterFunction("sayHello", func(text string) string {
return "Hello " + text
})
func (*DocxTmpl) RejectAllChanges ¶ added in v0.1.1
func (d *DocxTmpl) RejectAllChanges()
RejectAllChanges rejects all tracked changes, removing insertions and restoring deleted text. Note: This modifies the processable files (headers, footers, etc.). Document body changes require re-parsing after save.
doc.RejectAllChanges()
func (*DocxTmpl) RemoveProtection ¶ added in v0.1.1
RemoveProtection removes document protection (without password). Note: This only works for documents without password protection.
err := doc.RemoveProtection()
func (*DocxTmpl) Render ¶
Replace the placeholders in the document with passed in data. Data can be a struct or map
data := struct {
FirstName string
LastName string
Gender string
}{
FirstName: "Tom",
LastName: "Watkins",
Gender: "Male",
}
err = doc.Render(data)
OR ¶
data := map[string]any{
"ProjectNumber": "B-00001",
"Client": "TW Software",
"Status": "New",
}
err = doc.Render(data)
func (*DocxTmpl) ReplaceText ¶ added in v0.1.1
ReplaceText replaces all occurrences of old text with new text in the document. This is a simple text replacement that works on the rendered document. For template-based replacement, use Render() instead.
doc.ReplaceText("COMPANY_NAME", "Acme Corp")
func (*DocxTmpl) ReplaceTextRegex ¶ added in v0.1.1
ReplaceTextRegex replaces text matching the pattern with replacement. The replacement can include $1, $2, etc. for captured groups.
doc.ReplaceTextRegex(`\bfoo\b`, "bar")
func (*DocxTmpl) ReplaceWatermark ¶
ReplaceWatermark replaces a specific watermark text with a new value. This should be called before Render() if you want to change watermark text.
doc.ReplaceWatermark("DRAFT", "FINAL")
doc.Render(data)
func (*DocxTmpl) Save ¶
Save the document to a writer. This could be a new file.
f, err := os.Create(FILE_PATH)
if err != nil {
panic(err)
}
err = doc.Save(f)
if err != nil {
panic(err)
}
err = f.Close()
if err != nil {
panic(err)
}
func (*DocxTmpl) SaveToFile ¶
Save the document directly to a file path. This is a convenience method that creates the file and calls Save().
err := doc.SaveToFile("output.docx")
if err != nil {
panic(err)
}
func (*DocxTmpl) SearchWithContext ¶ added in v0.1.1
func (d *DocxTmpl) SearchWithContext(searchText string, contextLines int) []SearchResult
SearchWithContext searches for text and returns matches with context. contextLines specifies how many lines of context to include.
results := doc.SearchWithContext("important", 2)
func (*DocxTmpl) SetCategory ¶ added in v0.1.1
SetCategory sets the document category.
func (*DocxTmpl) SetContentStatus ¶ added in v0.1.1
SetContentStatus sets the document status (e.g., "Draft", "Final", "Approved").
func (*DocxTmpl) SetDescription ¶ added in v0.1.1
SetDescription sets the document description/comments.
func (*DocxTmpl) SetKeywords ¶ added in v0.1.1
SetKeywords sets the document keywords.
func (*DocxTmpl) SetMetadata ¶ added in v0.1.1
func (d *DocxTmpl) SetMetadata(meta *DocumentMetadata)
SetMetadata sets document metadata in core.xml. Only non-empty fields are updated.
doc.SetMetadata(&DocumentMetadata{
Title: "My Report",
Creator: "John Doe",
})
func (*DocxTmpl) SetProperties ¶ added in v0.1.1
func (d *DocxTmpl) SetProperties(props *DocumentProperties)
SetProperties updates the document properties. The properties will be written when the document is saved.
func (*DocxTmpl) SetProtection ¶ added in v0.1.1
func (d *DocxTmpl) SetProtection(protType ProtectionType) error
SetProtection sets document protection. Note: This sets protection without a password. For password protection, use the Word application or a dedicated library.
err := doc.SetProtection(docxtpl.ProtectionReadOnly)
func (*DocxTmpl) SetReadOnly ¶ added in v0.1.1
SetReadOnly sets the document to read-only mode.
err := doc.SetReadOnly()
func (*DocxTmpl) SetSubject ¶ added in v0.1.1
SetSubject sets the document subject.
func (*DocxTmpl) SetXMLContent ¶ added in v0.1.1
SetXMLContent sets the content of a processable XML file. Only works for files in the processable files list (headers, footers, settings, etc.)
err := doc.SetXMLContent("word/settings.xml", newContent)
func (*DocxTmpl) SplitAt ¶ added in v0.1.1
SplitAt splits the document into multiple documents based on a rule. The rule function receives paragraph text, whether it's a heading, and heading level. Returns a slice of new DocxTmpl documents.
// Split at each Heading 1
docs := doc.SplitAt(func(text string, isHeading bool, level int) bool {
return isHeading && level == 1
})
func (*DocxTmpl) SplitAtHeading ¶ added in v0.1.1
SplitAtHeading splits the document at each heading of the specified level. Level 0 splits at Title, level 1-9 splits at Heading1-Heading9.
chapters := doc.SplitAtHeading(1) // Split at each Heading 1
func (*DocxTmpl) SplitAtRegex ¶ added in v0.1.1
SplitAtRegex splits the document at paragraphs matching the regex pattern.
parts := doc.SplitAtRegex(`^Chapter \d+`) // Split at "Chapter 1", "Chapter 2", etc.
func (*DocxTmpl) SplitAtText ¶ added in v0.1.1
SplitAtText splits the document at paragraphs containing the specified text.
parts := doc.SplitAtText("---") // Split at paragraphs containing "---"
func (*DocxTmpl) ToHTML ¶ added in v0.1.1
ToHTML converts the document to basic HTML format.
html := doc.ToHTML()
func (*DocxTmpl) ToJSON ¶ added in v0.1.1
ToJSON returns the document structure as JSON.
jsonStr, err := doc.ToJSON()
func (*DocxTmpl) ToMarkdown ¶ added in v0.1.1
ToMarkdown converts the document to Markdown format. Supports headings, bold, italic, lists, tables, and links.
markdown := doc.ToMarkdown()
func (*DocxTmpl) ToStructured ¶ added in v0.1.1
func (d *DocxTmpl) ToStructured() *StructuredDocument
ToStructured converts the document to a structured representation. This is useful for AI/LLM consumption and document analysis.
structured := doc.ToStructured() jsonBytes, _ := json.Marshal(structured)
func (*DocxTmpl) TrackedChangesSummary ¶ added in v0.1.1
TrackedChangesSummary returns a text summary of all tracked changes.
summary := doc.TrackedChangesSummary() fmt.Println(summary)
func (*DocxTmpl) UnpackToDirectory ¶ added in v0.1.1
UnpackToDirectory extracts the DOCX file to a directory. This allows direct access to all XML files for advanced manipulation.
err := doc.UnpackToDirectory("/tmp/unpacked")
func (*DocxTmpl) Validate ¶ added in v0.2.1
func (d *DocxTmpl) Validate() *ValidationResult
Validate checks the template for common errors without rendering. It returns a ValidationResult containing any errors found.
result := doc.Validate()
if result.HasErrors() {
for _, err := range result.Errors {
fmt.Println(err)
}
}
func (*DocxTmpl) ValidateData ¶ added in v0.1.1
func (d *DocxTmpl) ValidateData(data any) []ValidationError
ValidateData validates that the provided data contains all required template fields. Returns a slice of validation errors, or empty slice if valid.
errors := doc.ValidateData(data)
if len(errors) > 0 {
for _, err := range errors {
fmt.Println(err)
}
}
func (*DocxTmpl) ValidatePlaceholderSyntax ¶ added in v0.1.1
func (d *DocxTmpl) ValidatePlaceholderSyntax() []ValidationError
ValidatePlaceholderSyntax checks all placeholders for correct syntax. Returns errors for malformed placeholders.
errors := doc.ValidatePlaceholderSyntax()
type ErrorCode ¶ added in v0.2.1
type ErrorCode string
ErrorCode represents a specific error type for programmatic handling.
const ( // Parse errors ErrCodeInvalidFile ErrorCode = "INVALID_FILE" ErrCodeCorruptedDocx ErrorCode = "CORRUPTED_DOCX" ErrCodeFileNotFound ErrorCode = "FILE_NOT_FOUND" ErrCodeReadError ErrorCode = "READ_ERROR" // Template errors ErrCodeSyntaxError ErrorCode = "SYNTAX_ERROR" ErrCodeUnclosedTag ErrorCode = "UNCLOSED_TAG" ErrCodeUnmatchedEnd ErrorCode = "UNMATCHED_END" ErrCodeUndefinedField ErrorCode = "UNDEFINED_FIELD" ErrCodeInvalidFunc ErrorCode = "INVALID_FUNCTION" ErrCodeExecutionError ErrorCode = "EXECUTION_ERROR" // Render errors ErrCodeDataConversion ErrorCode = "DATA_CONVERSION" ErrCodeImageError ErrorCode = "IMAGE_ERROR" ErrCodeMarshalError ErrorCode = "MARSHAL_ERROR" // Save errors ErrCodeWriteError ErrorCode = "WRITE_ERROR" ErrCodeZipError ErrorCode = "ZIP_ERROR" // Merge errors ErrCodeMergeError ErrorCode = "MERGE_ERROR" )
type ErrorSummary ¶ added in v0.2.1
type ErrorSummary struct {
Errors []*TemplateError
}
ErrorSummary provides a summary of multiple errors.
func (*ErrorSummary) Add ¶ added in v0.2.1
func (s *ErrorSummary) Add(err *TemplateError)
Add adds an error to the summary.
func (*ErrorSummary) ByCode ¶ added in v0.2.1
func (s *ErrorSummary) ByCode(code ErrorCode) []*TemplateError
ByCode returns all errors with a specific code.
func (*ErrorSummary) ByLocation ¶ added in v0.2.1
func (s *ErrorSummary) ByLocation(location string) []*TemplateError
ByLocation returns all errors from a specific location.
func (*ErrorSummary) Error ¶ added in v0.2.1
func (s *ErrorSummary) Error() string
Error implements the error interface.
func (*ErrorSummary) HasErrors ¶ added in v0.2.1
func (s *ErrorSummary) HasErrors() bool
HasErrors returns true if there are any errors.
func (*ErrorSummary) String ¶ added in v0.2.1
func (s *ErrorSummary) String() string
String returns a detailed multi-line description of all errors.
type FieldInfo ¶ added in v0.1.1
type FieldInfo struct {
Name string // Field name (e.g., "Person.Name")
Required bool // Whether the field is required
Type string // Expected type (string, slice, etc.)
Example string // Example value
Occurrences int // Number of times field appears
Locations []string // Where field appears (body, header, footer)
}
FieldInfo represents information about a template field
type FieldSchema ¶ added in v0.1.1
type FieldSchema struct {
Type string `json:"type"` // "string", "number", "boolean", "array", "object"
Required bool `json:"required"`
Properties map[string]FieldSchema `json:"properties,omitempty"` // For nested objects
Items *FieldSchema `json:"items,omitempty"` // For arrays
}
FieldSchema represents a JSON schema-like field definition
type Hyperlink ¶ added in v0.1.1
type Hyperlink struct {
// contains filtered or unexported fields
}
Hyperlink wraps a Word hyperlink.
type HyperlinkInfo ¶ added in v0.1.1
type HyperlinkInfo struct {
Text string // Display text
URL string // Target URL
Index int // Paragraph index
IsInternal bool // True if internal bookmark link
}
HyperlinkInfo contains information about a hyperlink in the document.
type ImageInfo ¶ added in v0.1.1
type ImageInfo struct {
Name string `json:"name"`
Format string `json:"format"`
Size int `json:"size"` // bytes
}
ImageInfo represents an embedded image
type IndentOptions ¶ added in v0.1.1
type IndentOptions struct {
Left int // Left indent in twips (1/20 of a point, 1440 = 1 inch)
Right int // Right indent in twips
FirstLine int // First line indent in twips (positive = indent, use Hanging for outdent)
Hanging int // Hanging indent in twips (first line outdent)
LeftChars int // Left indent in character units (100 = 1 character)
FirstLineChars int // First line indent in character units
}
IndentOptions configures paragraph indentation
type InlineImage ¶
type InlineImage struct {
Ext string
// contains filtered or unexported fields
}
func CreateInlineImage ¶
func CreateInlineImage(filepath string) (*InlineImage, error)
Take a filenane for an image and return a pointer to an InlineImage struct. Images can be Jpegs (.jpg or .jpeg) or PNGs
img, err := CreateInlineImage("example_img.png")
func CreateInlineImageFromBytes ¶ added in v0.2.1
func CreateInlineImageFromBytes(data []byte, ext string) (*InlineImage, error)
CreateInlineImageFromBytes creates an InlineImage from raw bytes. You must specify the extension (.jpg, .jpeg, or .png).
img, err := CreateInlineImageFromBytes(imageData, ".png")
func CreateInlineImageFromURL ¶ added in v0.2.1
func CreateInlineImageFromURL(url string) (*InlineImage, error)
CreateInlineImageFromURL downloads an image from a URL and returns an InlineImage. Images can be Jpegs (.jpg or .jpeg) or PNGs. Timeout defaults to 30 seconds.
img, err := CreateInlineImageFromURL("https://example.com/image.png")
func CreateInlineImageFromURLWithTimeout ¶ added in v0.2.1
func CreateInlineImageFromURLWithTimeout(url string, timeout time.Duration) (*InlineImage, error)
CreateInlineImageFromURLWithTimeout downloads an image from a URL with a custom timeout.
img, err := CreateInlineImageFromURLWithTimeout("https://example.com/image.png", 10*time.Second)
func (*InlineImage) GetExifData ¶
func (i *InlineImage) GetExifData() (map[string]imagemeta.TagInfo, error)
Return a map of EXIF data from the image.
func (*InlineImage) GetResolution ¶
func (i *InlineImage) GetResolution() (wDpi int, hDpi int)
Get the resolution (DPI) of the image. It gets this from EXIF data and defaults to 72 if not found.
type InlineImageError ¶
type InlineImageError struct {
Message string
}
func (*InlineImageError) Error ¶
func (e *InlineImageError) Error() string
type InternalLink ¶ added in v0.1.1
type InternalLink struct {
Anchor string // Bookmark name this link points to
Text string // Display text
}
InternalLink represents an internal hyperlink (link to bookmark)
type Justification ¶ added in v0.1.1
type Justification string
Justification represents paragraph alignment
const ( JustifyLeft Justification = "left" JustifyCenter Justification = "center" JustifyRight Justification = "right" JustifyBoth Justification = "both" // Justified JustifyDistribute Justification = "distribute" // Distributed )
type List ¶ added in v0.1.1
type List struct {
// contains filtered or unexported fields
}
List wraps a collection of list paragraphs
func (*List) AddSubItem ¶ added in v0.1.1
AddSubItem adds a nested item to the list.
func (*List) GetParagraphs ¶ added in v0.1.1
GetParagraphs returns all paragraphs in the list.
type ListBuilder ¶ added in v0.1.1
type ListBuilder struct {
// contains filtered or unexported fields
}
ListBuilder provides a fluent interface for building complex lists
func (*ListBuilder) Build ¶ added in v0.1.1
func (lb *ListBuilder) Build() *List
Build creates the list and adds it to the document
func (*ListBuilder) Indent ¶ added in v0.1.1
func (lb *ListBuilder) Indent() *ListBuilder
Indent increases the indentation level for subsequent items
func (*ListBuilder) Item ¶ added in v0.1.1
func (lb *ListBuilder) Item(text string) *ListBuilder
Item adds an item at the current indentation level
func (*ListBuilder) Level ¶ added in v0.1.1
func (lb *ListBuilder) Level(level int) *ListBuilder
Level sets the indentation level directly
func (*ListBuilder) Outdent ¶ added in v0.1.1
func (lb *ListBuilder) Outdent() *ListBuilder
Outdent decreases the indentation level for subsequent items
type ListItem ¶ added in v0.1.1
type ListItem struct {
Text string // Item text
Level int // Nesting level (0-8)
Children []ListItem // Nested items
}
ListItem represents an item in a list with optional nesting
type Margins ¶ added in v0.1.1
Margins represents page margins in inches
func DefaultMargins ¶ added in v0.1.1
func DefaultMargins() Margins
DefaultMargins returns the default Word margins (1 inch all around)
func NarrowMargins ¶ added in v0.1.1
func NarrowMargins() Margins
NarrowMargins returns narrow margins (0.5 inch all around)
func WideMargins ¶ added in v0.1.1
func WideMargins() Margins
WideMargins returns wide margins (1 inch top/bottom, 2 inch left/right)
type Orientation ¶ added in v0.1.1
type Orientation string
Orientation represents page orientation
const ( OrientationPortrait Orientation = "portrait" OrientationLandscape Orientation = "landscape" )
type OutlineItem ¶ added in v0.1.1
type OutlineItem struct {
Level int // Heading level (0=Title, 1-9=Heading1-9)
Text string // Heading text
Index int // Paragraph index in document
Children []OutlineItem // Nested headings
}
OutlineItem represents a heading in the document outline.
type Paragraph ¶ added in v0.1.1
type Paragraph struct {
// contains filtered or unexported fields
}
Paragraph wraps a Word paragraph with formatting methods. Methods can be chained for fluent API usage.
func (*Paragraph) AddAnchorImage ¶ added in v0.1.1
AddAnchorImage adds a floating/anchored image to the paragraph. The image can be positioned independently of text flow.
data, _ := os.ReadFile("logo.png")
para.AddAnchorImage(data)
func (*Paragraph) AddAnchorImageFromFile ¶ added in v0.1.1
AddAnchorImageFromFile adds a floating/anchored image from a file path.
para.AddAnchorImageFromFile("logo.png")
func (*Paragraph) AddAnchorShape ¶ added in v0.1.1
func (p *Paragraph) AddAnchorShape(opts ShapeOptions) *Run
AddAnchorShape adds a floating shape to the paragraph. Use ShapeOptions to configure the shape appearance.
para.AddAnchorShape(ShapeOptions{
Width: 914400, Height: 914400, // 1 inch x 1 inch
Preset: ShapeRectangle,
LineColor: "000000",
})
func (*Paragraph) AddInlineImage ¶ added in v0.1.1
AddInlineImage adds an inline image to the paragraph. Inline images flow with the text.
data, _ := os.ReadFile("icon.png")
para.AddInlineImage(data)
func (*Paragraph) AddInlineImageFromFile ¶ added in v0.1.1
AddInlineImageFromFile adds an inline image from a file path.
para.AddInlineImageFromFile("icon.png")
func (*Paragraph) AddInlineShape ¶ added in v0.1.1
func (p *Paragraph) AddInlineShape(opts ShapeOptions) *Run
AddInlineShape adds an inline shape to the paragraph. Inline shapes flow with the text.
func (*Paragraph) AddLink ¶ added in v0.1.1
AddLink adds a hyperlink to the paragraph. Returns the Hyperlink for further customization.
para.AddLink("Click here", "https://example.com")
func (*Paragraph) AddPageBreak ¶ added in v0.1.1
AddPageBreak adds a page break after this paragraph.
func (*Paragraph) AddTabStop ¶ added in v0.1.1
AddTabStop adds a tab stop at the specified position. Align can be: "left", "center", "right", "decimal" Leader can be: "none", "dot", "hyphen", "underscore"
para.AddTabStop(4320, "left", "none")
func (*Paragraph) AddTabStops ¶ added in v0.1.1
AddTabStops adds multiple tab stops from a slice of TabStop.
para.AddTabStops([]TabStop{
{Position: 1440, Align: "left"},
{Position: 4320, Align: "center"},
{Position: 7200, Align: "right"},
})
func (*Paragraph) AddText ¶ added in v0.1.1
AddText adds more text to the paragraph and returns a Run for formatting.
para := doc.AddParagraph("Hello ")
para.AddText("World").Bold().Color("FF0000")
func (*Paragraph) Background ¶ added in v0.1.1
Background sets a solid background color for the text.
func (*Paragraph) ClearTabStops ¶ added in v0.1.1
ClearTabStops removes all tab stops from the paragraph.
func (*Paragraph) Color ¶ added in v0.1.1
Color sets the text color for all text in the paragraph. Use hex color code without # (e.g., "FF0000" for red).
func (*Paragraph) DropAllDrawings ¶ added in v0.1.1
DropAllDrawings removes all shapes, canvases, and groups from the paragraph.
func (*Paragraph) DropCanvas ¶ added in v0.1.1
DropCanvas removes all canvas elements from the paragraph.
func (*Paragraph) DropEmptyPictures ¶ added in v0.1.1
DropEmptyPictures removes nil/empty picture references from the paragraph.
func (*Paragraph) DropGroups ¶ added in v0.1.1
DropGroups removes all group elements from the paragraph.
func (*Paragraph) DropShapes ¶ added in v0.1.1
DropShapes removes all shapes from the paragraph.
func (*Paragraph) GetRaw ¶ added in v0.1.1
GetRaw returns the underlying go-docx paragraph for advanced usage.
func (*Paragraph) GetText ¶ added in v0.1.1
GetText returns the plain text content of the paragraph.
text := para.GetText()
func (*Paragraph) Highlight ¶ added in v0.1.1
Highlight applies a highlight color to the paragraph text. Valid colors: yellow, green, cyan, magenta, blue, red, darkBlue, darkCyan, darkGreen, darkMagenta, darkRed, darkYellow, darkGray, lightGray, black
func (*Paragraph) Indent ¶ added in v0.1.1
func (p *Paragraph) Indent(opts IndentOptions) *Paragraph
Indent sets paragraph indentation options.
para.Indent(IndentOptions{Left: 720, FirstLine: 360})
func (*Paragraph) IndentFirstLine ¶ added in v0.1.1
IndentFirstLine sets the first line indentation in inches.
para.IndentFirstLine(0.5)
func (*Paragraph) IndentHanging ¶ added in v0.1.1
IndentHanging sets a hanging indent (outdent for first line) in inches.
para.IndentHanging(0.5)
func (*Paragraph) IndentLeft ¶ added in v0.1.1
IndentLeft sets the left indentation in inches.
para.IndentLeft(0.5)
func (*Paragraph) IndentRight ¶ added in v0.1.1
IndentRight sets the right indentation in inches.
func (*Paragraph) Italic ¶ added in v0.1.1
Italic applies italic formatting to all text in the paragraph.
func (*Paragraph) Justify ¶ added in v0.1.1
func (p *Paragraph) Justify(j Justification) *Paragraph
Justify sets the paragraph alignment.
para.Justify(docxtpl.JustifyCenter)
func (*Paragraph) KeepElements ¶ added in v0.1.1
KeepElements keeps only the specified element types in the paragraph. Valid names: "w:r" (runs), "w:hyperlink", "w:bookmarkStart", "w:bookmarkEnd"
para.KeepElements("w:r", "w:hyperlink")
func (*Paragraph) LineSpacing ¶ added in v0.1.1
LineSpacing sets the line spacing in twips. Use "single" (240), "1.5" (360), "double" (480), or a custom value.
para.LineSpacing(360) // 1.5 line spacing
func (*Paragraph) LineSpacingDouble ¶ added in v0.1.1
LineSpacingDouble sets double line spacing.
func (*Paragraph) LineSpacingOneAndHalf ¶ added in v0.1.1
LineSpacingOneAndHalf sets 1.5 line spacing.
func (*Paragraph) LineSpacingSingle ¶ added in v0.1.1
LineSpacingSingle sets single line spacing.
func (*Paragraph) MergeAllRuns ¶ added in v0.1.1
MergeAllRuns merges all contiguous runs regardless of formatting.
func (*Paragraph) MergeRuns ¶ added in v0.1.1
MergeRuns merges contiguous runs with the same formatting into single runs.
para.MergeRuns()
func (*Paragraph) Shade ¶ added in v0.1.1
Shade applies background shading to the text. pattern: "clear", "solid", "horzStripe", "vertStripe", "diagStripe", etc. color: the pattern color (hex) fill: the background fill color (hex)
func (*Paragraph) Size ¶ added in v0.1.1
Size sets the font size for all text in the paragraph. Size is in half-points (e.g., 24 = 12pt).
func (*Paragraph) SizePoints ¶ added in v0.1.1
SizePoints sets the font size in points (convenience method). e.g., SizePoints(12) sets 12pt font.
func (*Paragraph) Spacing ¶ added in v0.1.1
func (p *Paragraph) Spacing(opts SpacingOptions) *Paragraph
Spacing sets paragraph spacing options.
para.Spacing(SpacingOptions{Before: 240, After: 120, Line: 360})
func (*Paragraph) SpacingAfter ¶ added in v0.1.1
SpacingAfter sets the space after the paragraph in points.
para.SpacingAfter(6)
func (*Paragraph) SpacingBefore ¶ added in v0.1.1
SpacingBefore sets the space before the paragraph in points.
para.SpacingBefore(12)
func (*Paragraph) Strike ¶ added in v0.1.1
Strike applies strikethrough formatting to the paragraph text.
type ProtectionInfo ¶ added in v0.1.1
type ProtectionInfo struct {
IsProtected bool // Whether the document is protected
Type ProtectionType // Type of protection
HasPassword bool // Whether a password is set
EnforceMessage string // Enforcement message if any
}
ProtectionInfo contains information about document protection
type ProtectionType ¶ added in v0.1.1
type ProtectionType string
ProtectionType represents the type of document protection
const ( ProtectionNone ProtectionType = "none" ProtectionReadOnly ProtectionType = "readOnly" ProtectionComments ProtectionType = "comments" // Allow only comments ProtectionTrackedChanges ProtectionType = "trackedChanges" // Allow only tracked changes ProtectionForms ProtectionType = "forms" // Allow only form filling )
type RestrictionInfo ¶ added in v0.1.1
type RestrictionInfo struct {
CanEdit bool // Can edit the document
CanComment bool // Can add comments
CanTrack bool // Can make tracked changes
CanFillForms bool // Can fill forms
CanFormatText bool // Can format text
}
RestrictionInfo provides detailed restriction information
type Run ¶ added in v0.1.1
type Run struct {
// contains filtered or unexported fields
}
Run wraps a Word text run with formatting methods. A run is a contiguous piece of text with the same formatting. Methods can be chained for fluent API usage.
func (*Run) Background ¶ added in v0.1.1
Background sets a solid background color for this run.
func (*Run) Bold ¶ added in v0.1.1
Bold applies bold formatting to this run.
para.AddText("Bold text").Bold()
func (*Run) CharacterSpacing ¶ added in v0.1.1
CharacterSpacing sets the spacing between characters in twips. Positive values expand spacing, negative values condense. 20 twips = 1 point.
run.CharacterSpacing(40) // Expand by 2pt
func (*Run) Color ¶ added in v0.1.1
Color sets the text color for this run. Use hex color code without # (e.g., "FF0000" for red).
func (*Run) Condense ¶ added in v0.1.1
Condense condenses character spacing by the specified points.
run.Condense(1) // Condense by 1pt
func (*Run) DoubleStrike ¶ added in v0.1.1
DoubleStrike applies double strikethrough formatting.
func (*Run) Expand ¶ added in v0.1.1
Expand expands character spacing by the specified points.
run.Expand(2) // Expand by 2pt
func (*Run) Font ¶ added in v0.1.1
Font sets the font family for this run. fontName is applied to ASCII and high ANSI characters.
func (*Run) Highlight ¶ added in v0.1.1
Highlight applies a highlight color to this run. Valid colors: yellow, green, cyan, magenta, blue, red, darkBlue, darkCyan, darkGreen, darkMagenta, darkRed, darkYellow, darkGray, lightGray, black
func (*Run) KeepElements ¶ added in v0.1.1
KeepElements keeps only specified element types in this run. Valid names depend on run content (e.g., "w:t" for text, "w:drawing" for drawings)
func (*Run) Kern ¶ added in v0.1.1
Kern sets the minimum font size for kerning in half-points. Kerning adjusts spacing between certain character pairs.
run.Kern(24) // Kern text 12pt and larger
func (*Run) Shade ¶ added in v0.1.1
Shade applies background shading to this run. pattern: "clear", "solid", "horzStripe", "vertStripe", "diagStripe", etc. color: the pattern color (hex) fill: the background fill color (hex)
func (*Run) Size ¶ added in v0.1.1
Size sets the font size for this run. Size is in half-points (e.g., 24 = 12pt).
func (*Run) SizePoints ¶ added in v0.1.1
SizePoints sets the font size in points (convenience method). e.g., SizePoints(12) sets 12pt font.
func (*Run) Subscript ¶ added in v0.1.1
Subscript applies subscript formatting to this run.
para.AddText("H").Then().AddText("2").Subscript().Then().AddText("O") // H₂O
func (*Run) Superscript ¶ added in v0.1.1
Superscript applies superscript formatting to this run.
para.AddText("x").Then().AddText("2").Superscript() // x²
type SearchResult ¶ added in v0.1.1
type SearchResult struct {
Text string // The matched text
Line int // Line number (1-indexed)
Paragraph int // Paragraph index (0-indexed)
Context string // Surrounding context
MatchStart int // Start position of match in context
}
SearchResult contains information about a text match.
type SectionBreakType ¶ added in v0.1.1
type SectionBreakType string
SectionBreakType represents the type of section break
const ( SectionBreakNextPage SectionBreakType = "nextPage" SectionBreakContinuous SectionBreakType = "continuous" SectionBreakEvenPage SectionBreakType = "evenPage" SectionBreakOddPage SectionBreakType = "oddPage" )
type ShapeOptions ¶ added in v0.1.1
type ShapeOptions struct {
Width int64 // Width in EMUs (English Metric Units, 914400 = 1 inch)
Height int64 // Height in EMUs
Preset ShapePreset // Shape preset (rectangle, ellipse, etc.)
Name string // Shape name
LineColor string // Outline color (hex without #)
LineWidth int64 // Outline width in EMUs
BWMode string // Black and white mode ("auto", "black", "white", etc.)
}
ShapeOptions configures a shape
type ShapePreset ¶ added in v0.1.1
type ShapePreset string
ShapePreset defines common shape presets
const ( ShapeRectangle ShapePreset = "rect" ShapeRoundedRect ShapePreset = "roundRect" ShapeEllipse ShapePreset = "ellipse" ShapeTriangle ShapePreset = "triangle" ShapeDiamond ShapePreset = "diamond" ShapePentagon ShapePreset = "pentagon" ShapeHexagon ShapePreset = "hexagon" ShapeArrowRight ShapePreset = "rightArrow" ShapeArrowLeft ShapePreset = "leftArrow" ShapeArrowUp ShapePreset = "upArrow" ShapeArrowDown ShapePreset = "downArrow" ShapeStar5 ShapePreset = "star5" ShapeStar6 ShapePreset = "star6" ShapeHeart ShapePreset = "heart" ShapeLightningBolt ShapePreset = "lightningBolt" ShapeSun ShapePreset = "sun" ShapeMoon ShapePreset = "moon" ShapeCloud ShapePreset = "cloud" ShapeLine ShapePreset = "line" ShapeStraightConnect ShapePreset = "straightConnector1" )
type SpacingOptions ¶ added in v0.1.1
type SpacingOptions struct {
Before int // Space before paragraph (in twips, 1/20 of a point)
After int // Space after paragraph (in twips)
Line int // Line spacing (in twips or percentage depending on LineRule)
LineRule string // "auto", "exact", "atLeast"
BeforeLines int // Space before in lines (1 = 100)
}
SpacingOptions configures paragraph spacing
type SplitRule ¶ added in v0.1.1
SplitRule defines a function that determines where to split a document. Return true to split before the paragraph that matches.
type StructuredDocument ¶ added in v0.1.1
type StructuredDocument struct {
Metadata DocumentMetadata `json:"metadata"`
Stats DocumentStats `json:"stats"`
Outline []OutlineItem `json:"outline"`
Paragraphs []StructuredParagraph `json:"paragraphs"`
Tables []StructuredTable `json:"tables"`
Images []ImageInfo `json:"images"`
Links []HyperlinkInfo `json:"links"`
}
StructuredDocument represents the document in a structured format suitable for AI consumption
type StructuredParagraph ¶ added in v0.1.1
type StructuredParagraph struct {
Index int `json:"index"`
Text string `json:"text"`
Style string `json:"style"`
IsList bool `json:"is_list,omitempty"`
ListLevel int `json:"list_level,omitempty"`
Alignment string `json:"alignment,omitempty"`
Runs []StructuredRun `json:"runs,omitempty"`
}
StructuredParagraph represents a paragraph with its metadata
type StructuredRun ¶ added in v0.1.1
type StructuredRun struct {
Text string `json:"text"`
Bold bool `json:"bold,omitempty"`
Italic bool `json:"italic,omitempty"`
Underline bool `json:"underline,omitempty"`
Strike bool `json:"strike,omitempty"`
Color string `json:"color,omitempty"`
FontSize int `json:"font_size,omitempty"`
FontFamily string `json:"font_family,omitempty"`
Highlight string `json:"highlight,omitempty"`
}
StructuredRun represents a text run with formatting
type StructuredTable ¶ added in v0.1.1
type StructuredTable struct {
Index int `json:"index"`
Rows int `json:"rows"`
Cols int `json:"cols"`
Data [][]string `json:"data"`
Headers []string `json:"headers,omitempty"`
}
StructuredTable represents a table with its data
type TabStop ¶ added in v0.1.1
type TabStop struct {
Position int // Position in twips (1440 = 1 inch)
Align string // "left", "center", "right", "decimal"
Leader string // "none", "dot", "hyphen", "underscore"
}
TabStop defines a tab stop position and alignment
type Table ¶ added in v0.1.1
type Table struct {
// contains filtered or unexported fields
}
Table wraps a Word table with formatting and manipulation methods.
func (*Table) AddColumn ¶ added in v0.1.1
AddColumn adds a new column to the table.
table.AddColumn()
func (*Table) AddRow ¶ added in v0.1.1
AddRow adds a new empty row to the table. Returns the new TableRow for populating.
row := table.AddRow() row.SetCell(0, "New cell")
func (*Table) AddRowWithData ¶ added in v0.1.1
AddRowWithData adds a new row with the given cell values.
table.AddRowWithData("Col1", "Col2", "Col3")
func (*Table) Cell ¶ added in v0.1.1
Cell returns the cell at the specified row and column (0-indexed). Returns nil if the indices are out of bounds.
func (*Table) ClearColumn ¶ added in v0.1.1
ClearColumn clears all cell content in a column.
table.ClearColumn(0)
func (*Table) ClearRow ¶ added in v0.1.1
ClearRow clears all cell content in a row.
table.ClearRow(0)
func (*Table) DeleteColumn ¶ added in v0.1.1
DeleteColumn removes the column at the specified index.
table.DeleteColumn(2)
func (*Table) DeleteRow ¶ added in v0.1.1
DeleteRow removes the row at the specified index.
table.DeleteRow(2)
func (*Table) FillColumn ¶ added in v0.1.1
FillColumn fills all cells in a column with the same value.
table.FillColumn(0, "N/A")
func (*Table) FillRow ¶ added in v0.1.1
FillRow fills all cells in a row with the same value.
table.FillRow(0, "Header")
func (*Table) FindAllRows ¶ added in v0.1.1
FindAllRows finds all rows where the specified column contains the value.
rows := table.FindAllRows(1, "Active")
func (*Table) FindRow ¶ added in v0.1.1
FindRow finds the first row where the specified column contains the value. Returns -1 if not found.
rowIdx := table.FindRow(0, "John")
func (*Table) GetColumn ¶ added in v0.1.1
GetColumn returns all values in a column.
values := table.GetColumn(0)
func (*Table) GetRaw ¶ added in v0.1.1
GetRaw returns the underlying go-docx table for advanced usage.
func (*Table) GetRowData ¶ added in v0.1.1
GetRowData returns all values in a row.
values := table.GetRowData(0)
func (*Table) InsertColumn ¶ added in v0.1.1
InsertColumn inserts a new column at the specified index.
table.InsertColumn(1)
func (*Table) InsertRow ¶ added in v0.1.1
InsertRow inserts a new row at the specified index. Existing rows are shifted down.
table.InsertRow(1)
func (*Table) Justify ¶ added in v0.1.1
Justify sets the table alignment. Valid values: "left", "center", "right"
func (*Table) SetAllColumnWidths ¶ added in v0.1.1
SetAllColumnWidths sets widths for all columns.
table.SetAllColumnWidths([]int{2880, 1440, 1440})
func (*Table) SetBorderColors ¶ added in v0.1.1
func (t *Table) SetBorderColors(colors TableBorderColors) *Table
SetBorderColors sets border colors for all cells in the table. Note: For best results, use AddTableWithBorders when creating the table.
func (*Table) SetCell ¶ added in v0.1.1
SetCell sets the text content of a cell at the specified row and column. Returns the TableCell for further formatting.
table.SetCell(0, 0, "Header 1").Bold().Background("CCCCCC")
func (*Table) SetColumnWidth ¶ added in v0.1.1
SetColumnWidth sets the width for a specific column in twips.
table.SetColumnWidth(0, 2880)
func (*Table) SetRowHeight ¶ added in v0.1.1
SetRowHeight sets the height for a specific row in twips.
table.SetRowHeight(0, 720)
func (*Table) SortByColumn ¶ added in v0.1.1
SortByColumn sorts the table rows by the specified column. Set ascending to false for descending order. skipHeader skips the first row (treats it as a header).
table.SortByColumn(0, true, true)
type TableBorderColors ¶ added in v0.1.1
type TableBorderColors struct {
Top string // Top border color
Left string // Left border color
Bottom string // Bottom border color
Right string // Right border color
InsideH string // Inside horizontal border color
InsideV string // Inside vertical border color
}
TableBorderColors defines custom border colors for tables. Use hex color codes without # (e.g., "000000" for black).
type TableCell ¶ added in v0.1.1
type TableCell struct {
// contains filtered or unexported fields
}
TableCell wraps a Word table cell.
func (*TableCell) AddParagraph ¶ added in v0.1.1
AddParagraph adds a new paragraph to the cell and returns it.
func (*TableCell) Background ¶ added in v0.1.1
Background sets a solid background color for the cell.
func (*TableCell) Borders ¶ added in v0.1.1
Borders sets all borders for this cell. color is a hex color code without # (e.g., "000000" for black). width is the border width in eighths of a point.
cell.Borders("000000", 4) // Black border, 0.5pt width
func (*TableCell) GetRaw ¶ added in v0.1.1
func (c *TableCell) GetRaw() *docx.WTableCell
GetRaw returns the underlying go-docx table cell for advanced usage.
func (*TableCell) MergeHorizontal ¶ added in v0.1.1
MergeHorizontal merges this cell with the specified number of cells to the right. Uses GridSpan to span multiple columns.
table.Cell(0, 0).MergeHorizontal(2) // Merge with 2 cells to the right (3 total)
func (*TableCell) MergeVerticalContinue ¶ added in v0.1.1
MergeVerticalContinue marks this cell as a continuation of a vertical merge. The cell above must have MergeVerticalStart or MergeVerticalContinue.
func (*TableCell) MergeVerticalStart ¶ added in v0.1.1
MergeVerticalStart marks this cell as the start of a vertical merge. Use with MergeVerticalContinue on cells below.
table.Cell(0, 0).MergeVerticalStart() // Start of vertical merge table.Cell(1, 0).MergeVerticalContinue() // Continue merge
func (*TableCell) SetText ¶ added in v0.1.1
SetText sets the text content of the cell. Clears any existing content and adds a new paragraph with the text.
func (*TableCell) Shade ¶ added in v0.1.1
Shade applies background shading to the cell. pattern: "clear", "solid", etc. color: pattern color (hex) fill: background fill color (hex)
func (*TableCell) VAlign ¶ added in v0.1.1
func (c *TableCell) VAlign(align VerticalAlignment) *TableCell
VAlign sets the vertical alignment of the cell content.
cell.VAlign(docxtpl.VAlignCenter)
func (*TableCell) VAlignBottom ¶ added in v0.1.1
VAlignBottom aligns cell content to the bottom.
func (*TableCell) VAlignCenter ¶ added in v0.1.1
VAlignCenter vertically centers cell content.
func (*TableCell) Width ¶ added in v0.1.1
Width sets the cell width in twips (1/20 of a point). 1 inch = 1440 twips, 1 cm = 567 twips.
cell.Width(2880) // 2 inches
func (*TableCell) WidthCm ¶ added in v0.1.1
WidthCm sets the cell width in centimeters.
cell.WidthCm(3.5) // 3.5 cm
func (*TableCell) WidthInches ¶ added in v0.1.1
WidthInches sets the cell width in inches.
cell.WidthInches(1.5) // 1.5 inches
func (*TableCell) WidthPercent ¶ added in v0.1.1
WidthPercent sets the cell width as a percentage of table width.
cell.WidthPercent(25) // 25% of table width
type TableOfContentsEntry ¶ added in v0.1.1
type TableOfContentsEntry struct {
Level int // Entry level (1, 2, 3, etc.)
Text string // Entry text
Page string // Page number (may be empty if not updated)
Bookmark string // Bookmark reference
}
TableOfContentsEntry represents an entry in the table of contents
type TableRow ¶ added in v0.1.1
type TableRow struct {
// contains filtered or unexported fields
}
TableRow wraps a Word table row.
func (*TableRow) GetRaw ¶ added in v0.1.1
GetRaw returns the underlying go-docx table row for advanced usage.
type TemplateError ¶ added in v0.2.1
type TemplateError struct {
// Code is a programmatic error code for categorization.
Code ErrorCode
// Message is a human-readable error description.
Message string
// Location describes where the error occurred (e.g., "document body", "header1").
Location string
// Placeholder is the template tag that caused the error, if applicable.
Placeholder string
// LineNumber is the approximate line in the template, if available.
LineNumber int
// Cause is the underlying error that caused this error.
Cause error
// Suggestions provides possible fixes for the error.
Suggestions []string
}
TemplateError is an enhanced error type that provides detailed context about where and why an error occurred during template processing.
func ErrFileParse ¶ added in v0.2.1
func ErrFileParse(filename string, cause error) *TemplateError
ErrFileParse creates a file parsing error.
func ErrImageLoad ¶ added in v0.2.1
func ErrImageLoad(path string, cause error) *TemplateError
ErrImageLoad creates an image loading error.
func ErrInvalidFunc ¶ added in v0.2.1
func ErrInvalidFunc(funcName string) *TemplateError
ErrInvalidFunc creates an invalid function error.
func ErrSyntax ¶ added in v0.2.1
func ErrSyntax(message string) *TemplateError
ErrSyntax creates a syntax error.
func ErrUnclosedTag ¶ added in v0.2.1
func ErrUnclosedTag(location string) *TemplateError
ErrUnclosedTag creates an unclosed tag error.
func ErrUndefinedField ¶ added in v0.2.1
func ErrUndefinedField(field string, location string) *TemplateError
ErrUndefinedField creates an undefined field error.
func ErrUnmatchedEnd ¶ added in v0.2.1
func ErrUnmatchedEnd(tag string, location string) *TemplateError
ErrUnmatchedEnd creates an unmatched end error.
func IsTemplateError ¶ added in v0.2.1
func IsTemplateError(err error) (*TemplateError, bool)
IsTemplateError checks if an error is a TemplateError and returns it.
func NewTemplateError ¶ added in v0.2.1
func NewTemplateError(code ErrorCode, message string) *TemplateError
NewTemplateError creates a new TemplateError.
func (*TemplateError) Error ¶ added in v0.2.1
func (e *TemplateError) Error() string
Error implements the error interface.
func (*TemplateError) String ¶ added in v0.2.1
func (e *TemplateError) String() string
String returns a detailed multi-line error description.
func (*TemplateError) Unwrap ¶ added in v0.2.1
func (e *TemplateError) Unwrap() error
Unwrap returns the underlying error for errors.Is and errors.As support.
func (*TemplateError) WithCause ¶ added in v0.2.1
func (e *TemplateError) WithCause(cause error) *TemplateError
WithCause returns a copy of the error with the cause set.
func (*TemplateError) WithLocation ¶ added in v0.2.1
func (e *TemplateError) WithLocation(location string) *TemplateError
WithLocation returns a copy of the error with the location set.
func (*TemplateError) WithPlaceholder ¶ added in v0.2.1
func (e *TemplateError) WithPlaceholder(placeholder string) *TemplateError
WithPlaceholder returns a copy of the error with the placeholder set.
func (*TemplateError) WithSuggestions ¶ added in v0.2.1
func (e *TemplateError) WithSuggestions(suggestions ...string) *TemplateError
WithSuggestions returns a copy of the error with suggestions added.
type TrackedChange ¶ added in v0.1.1
type TrackedChange struct {
ID int // Change ID
Type TrackedChangeType // insertion or deletion
Author string // Author who made the change
Date time.Time // When the change was made
Text string // The changed text
Location string // Location description (paragraph index, etc.)
}
TrackedChange represents a tracked change in the document
type TrackedChangeType ¶ added in v0.1.1
type TrackedChangeType string
TrackedChangeType represents the type of tracked change
const ( ChangeTypeInsertion TrackedChangeType = "insertion" ChangeTypeDeletion TrackedChangeType = "deletion" )
type TrackedChangesConfig ¶ added in v0.1.1
type TrackedChangesConfig struct {
Author string // Default author name
Initials string // Default author initials
}
TrackedChangesConfig holds configuration for tracked changes
func DefaultTrackedChangesConfig ¶ added in v0.1.1
func DefaultTrackedChangesConfig() TrackedChangesConfig
DefaultTrackedChangesConfig returns default configuration
type UnpackedDocument ¶ added in v0.1.1
UnpackedDocument represents an unpacked DOCX document
type ValidationError ¶ added in v0.1.1
type ValidationError struct {
Field string // Field name that caused the error
Message string // Error description
Placeholder string // Original placeholder text
}
ValidationError represents a template validation error
func (ValidationError) Error ¶ added in v0.1.1
func (e ValidationError) Error() string
type ValidationErrorType ¶ added in v0.2.1
type ValidationErrorType string
ValidationErrorType represents the type of validation error.
const ( ErrorUnclosedTag ValidationErrorType = "UNCLOSED_TAG" ErrorUnmatchedEnd ValidationErrorType = "UNMATCHED_END" ErrorSyntaxError ValidationErrorType = "SYNTAX_ERROR" ErrorUndefinedField ValidationErrorType = "UNDEFINED_FIELD" ErrorInvalidFunction ValidationErrorType = "INVALID_FUNCTION" )
type ValidationResult ¶ added in v0.2.1
type ValidationResult struct {
Valid bool
Errors []ValidationError
}
ValidationResult contains the results of template validation.
func (*ValidationResult) Error ¶ added in v0.2.1
func (r *ValidationResult) Error() string
Error returns a combined error message for all validation errors.
func (*ValidationResult) HasErrors ¶ added in v0.2.1
func (r *ValidationResult) HasErrors() bool
HasErrors returns true if there are any validation errors.
type VerticalAlignment ¶ added in v0.1.1
type VerticalAlignment string
VerticalAlignment represents vertical alignment in table cells.
const ( VAlignTop VerticalAlignment = "top" VAlignCenter VerticalAlignment = "center" VAlignBottom VerticalAlignment = "bottom" )
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
test_template
command
|
|
|
Example demonstrates basic usage of go-docxgen
|
Example demonstrates basic usage of go-docxgen |
|
internal
|
|
|
docx
Package docx is one of the most functional libraries to read and write .docx (a.k.a.
|
Package docx is one of the most functional libraries to read and write .docx (a.k.a. |
|
docx/cmd/main
command
Package main is a function demo
|
Package main is a function demo |