word

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2026 License: LGPL-3.0 Imports: 23 Imported by: 0

README

GoWord

English | 中文

Go Version Go Reference CI


English

Introduction

GoWord is a pure-Go library for creating, reading, and filling Microsoft Word documents. It writes native OpenXML Word2007 (.docx) packages and ports the core architecture of PHPWord / PHPOffice.

The public API keeps PHPWord names (AddSection, AddText, IOFactory, TemplateProcessor) while using idiomatic Go types and error returns.

Zero third-party dependencies: go.mod has no external require. OOXML is serialized with the standard library encoding/xml; .docx packages are packed and unpacked with archive/zip.

Features
  • Zero dependencies — Go standard library only (encoding/xml, archive/zip, image, …)
  • Word 2007 / OpenXML — generate and load .docx / .docm (WordprocessingML)
  • Paragraphs & rich text — AddText, TextRun, headings, breaks, hyperlinks, bookmarks
  • Tables — rows, cells, width, merge, borders, shading
  • Images — from file path or in-memory bytes
  • Headers & footers — default, first page, even page; watermarks
  • Formulas — Office Math (OMML) via pkg/math (fractions, superscripts, identifiers, operators)
  • Styles — font, paragraph, table, numbering, section, paper size and margins
  • Template fill — ${variable} placeholders, nested ${block} loops, ${if} / ${endif} clipping, merged-cell row cloning, images and charts
  • Streaming writer — NewStreamWriter writes paragraphs and tables into the ZIP stream as they are produced
  • Memory pooling — sync.Pool reuses buffers, XML writers, and core style structs
  • More — lists, charts, footnotes/endnotes, Markdown/HTML import, comments, track changes, document properties
Installation
go get github.com/yunkeweb/go-word@v0.4.0

Requires Go 1.21+.

Quick Start

Create a document, register paragraph styles, and save output.docx:

package main

import (
	"log"

	"github.com/yunkeweb/go-word"
	"github.com/yunkeweb/go-word/style"
)

func main() {
	doc := word.New()

	doc.AddFontStyle("rStyle", style.Font{
		Bold: true,
		Size: 16,
		Name: "Calibri",
	})
	doc.AddParagraphStyle("pStyle", style.Paragraph{
		Alignment: style.JcCenter,
		Spacing:   style.Spacing{After: 200},
	})
	doc.AddTitleStyle(1, style.Font{Bold: true, Size: 18}, style.Paragraph{
		Spacing: style.Spacing{After: 240},
	})

	section := doc.AddSection()
	section.AddTitle("Welcome to GoWord", 1)
	section.AddText("Hello, Word 2007.", "rStyle", "pStyle")
	section.AddText("This document was built with the Go standard library.")

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

A longer runnable sample lives in examples/simple. API docs: pkg.go.dev/github.com/yunkeweb/go-word.

Streaming writer

For large tables or reports, write body content incrementally so document.xml is never fully buffered:

package main

import (
	"log"
	"os"

	"github.com/yunkeweb/go-word"
	"github.com/yunkeweb/go-word/element"
	"github.com/yunkeweb/go-word/style"
)

func main() {
	f, err := os.Create("report.docx")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	sw := word.NewStreamWriter(f)
	if err := sw.WriteParagraph("Quarterly report", style.Font{Bold: true, Size: 16}); err != nil {
		log.Fatal(err)
	}

	tbl := element.NewTable(style.Table{Width: 9000})
	row := tbl.AddRow()
	row.AddCell(4500).AddText("Item")
	row.AddCell(4500).AddText("Amount")
	if err := sw.WriteTable(tbl); err != nil {
		log.Fatal(err)
	}
	if err := sw.Close(); err != nil {
		log.Fatal(err)
	}
}

Document.Save and Document.WriteTo also stream word/document.xml into the ZIP package.

What's new in v0.4.0
  • Charts & DrawingML — AddChart for bar, column, line, and pie charts; writes word/charts/chartN.xml plus Content Types and relationships
  • Markdown / HTML import — AddMarkdown and AddHTML turn headings, bold/italic/underline, lists, and code blocks into native Word elements
  • Comments & track changes — CommentOn writes word/comments.xml; EnableTrackChanges, AddInsertion, and AddDeletion emit w:ins / w:del
What's new in v0.3.0
  • Nested block loops — ${block_a} may contain ${block_b}; CloneNestedBlock fills hierarchical lists
  • Conditional blocks — ${if condition} … ${endif} drops the covering paragraphs or table rows when false or empty
  • Merged-cell row cloning — CloneRow / DeleteRow keep w:vMerge restart/continue groups and gridSpan together
What's new in v0.2.0
  • StreamWriter for incremental paragraphs, tables, and other body elements
  • Streaming Save / WriteTo so the full document XML is not held in one buffer
  • sync.Pool reuse of bytes.Buffer, XML writers, and Font / Paragraph / Table styles
  • Benchmarks versus v0.1.1 (median of 3): BenchmarkTableRender about 74% fewer B/op and 37% fewer allocs/op; BenchmarkSaveDocx about 52% fewer B/op and 34% fewer allocs/op
License

GNU Lesser General Public License version 3, same family as PHPWord. See LICENSE.


中文

项目简介

GoWord 是纯 Go 实现的 Word 文档库,面向原生 OpenXML Word2007(.docx) 读写,移植自 PHPWord / PHPOffice 的核心架构与文档模型。

公开 API 沿用 PHPWord 命名(AddSection、AddText、IOFactory、TemplateProcessor),同时采用惯用的 Go 类型与 error 返回。

零第三方依赖: go.mod 不含任何外部 require。OpenXML 仅使用标准库 encoding/xml 序列化;.docx 仅使用 archive/zip 打包与解包。

核心特性
  • 零依赖 — 仅使用 Go 标准库(encoding/xml、archive/zip、image 等)
  • Word 2007 / OpenXML — 生成与加载 .docx / .docm(WordprocessingML)
  • 段落与富文本 — AddText、TextRun、标题、换行、超链接、书签
  • 表格 — 行、单元格、宽度、合并、边框、底纹
  • 图片 — 本地路径或内存字节
  • 页眉页脚 — 默认 / 首页 / 偶数页,以及水印
  • 公式 — 通过 pkg/math 写入 Office Math(OMML):分数、上下标、标识符与运算符
  • 样式配置 — 字体、段落、表格、编号、节、纸张与页边距
  • 模板变量 — ${variable} 占位符、嵌套 ${block} 循环、${if} / ${endif} 裁剪、合并单元格行克隆,以及图片与图表
  • 流式写入 — NewStreamWriter 边生成边写入 ZIP 流中的段落与表格
  • 对象池 — 通过 sync.Pool 复用缓冲区、XML 写入器与核心样式结构
  • 更多 — 列表、图表、脚注/尾注、Markdown/HTML 导入、批注、修订模式、文档属性
安装
go get github.com/yunkeweb/go-word@v0.4.0

需要 Go 1.21 或更高版本。

快速开始

新建文档、添加段落样式,并保存为 output.docx:

package main

import (
	"log"

	"github.com/yunkeweb/go-word"
	"github.com/yunkeweb/go-word/style"
)

func main() {
	doc := word.New()

	doc.AddFontStyle("rStyle", style.Font{
		Bold: true,
		Size: 16,
		Name: "Calibri",
	})
	doc.AddParagraphStyle("pStyle", style.Paragraph{
		Alignment: style.JcCenter,
		Spacing:   style.Spacing{After: 200},
	})
	doc.AddTitleStyle(1, style.Font{Bold: true, Size: 18}, style.Paragraph{
		Spacing: style.Spacing{After: 240},
	})

	section := doc.AddSection()
	section.AddTitle("Welcome to GoWord", 1)
	section.AddText("Hello, Word 2007.", "rStyle", "pStyle")
	section.AddText("This document was built with the Go standard library.")

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

更完整的可运行示例见 examples/simple。包文档:pkg.go.dev/github.com/yunkeweb/go-word。

流式写入器

大表格或长报告可按行写入,避免把整份 document.xml 缓存在内存中:

package main

import (
	"log"
	"os"

	"github.com/yunkeweb/go-word"
	"github.com/yunkeweb/go-word/element"
	"github.com/yunkeweb/go-word/style"
)

func main() {
	f, err := os.Create("report.docx")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	sw := word.NewStreamWriter(f)
	if err := sw.WriteParagraph("季度报告", style.Font{Bold: true, Size: 16}); err != nil {
		log.Fatal(err)
	}

	tbl := element.NewTable(style.Table{Width: 9000})
	row := tbl.AddRow()
	row.AddCell(4500).AddText("项目")
	row.AddCell(4500).AddText("金额")
	if err := sw.WriteTable(tbl); err != nil {
		log.Fatal(err)
	}
	if err := sw.Close(); err != nil {
		log.Fatal(err)
	}
}

Document.Save 与 Document.WriteTo 同样将 word/document.xml 流式写入 ZIP 包。

v0.4.0 更新
  • 图表与 DrawingML:AddChart 支持柱状、条形、折线、饼图,写入 word/charts/chartN.xml 并注册 Content Types 与关系
  • Markdown / HTML 导入:AddMarkdown 与 AddHTML 将标题、加粗/斜体/下划线、列表、代码块转为原生 Word 元素
  • 批注与修订:CommentOn 生成 word/comments.xml;EnableTrackChanges、AddInsertion、AddDeletion 输出 w:ins / w:del
v0.3.0 更新
  • 嵌套块循环:${block_a} 内可再套 ${block_b};CloneNestedBlock 填充多级列表
  • 条件块:${if condition} … ${endif} 在条件为假或空时裁掉覆盖的段落或表格行
  • 合并单元格行克隆:CloneRow / DeleteRow 将 w:vMerge 的 restart/continue 组与 gridSpan 一并处理
v0.2.0 更新
  • StreamWriter:按段写入段落、表格及其他正文元素
  • 流式 Save / WriteTo:不再把整份文档 XML 放进单一缓冲区
  • sync.Pool:复用 bytes.Buffer、XML 写入器以及 Font / Paragraph / Table 样式
  • 相对 v0.1.1 的基准(三次中位数):BenchmarkTableRender 约减少 74% B/op、37% allocs/op;BenchmarkSaveDocx 约减少 52% B/op、34% allocs/op
开源协议

GNU Lesser General Public License version 3,与 PHPWord 同族。详见 LICENSE。

Documentation

Overview

Package word is a pure-Go port of PHPWord for creating, reading, and filling Microsoft Word documents.

The public API follows PHPWord naming (AddSection, AddText, IOFactory) while using idiomatic Go types and error returns. The library depends only on the Go standard library.

doc := word.New()
section := doc.AddSection()
section.AddText("Hello World")
if err := doc.Save("hello.docx"); err != nil {
    log.Fatal(err)
}

Index

Constants

View Source
const (
	ChartTypeBar    = "bar"
	ChartTypeColumn = "column"
	ChartTypeLine   = "line"
	ChartTypePie    = "pie"
)

Chart type names used by AddChart and Container.AddChart.

View Source
const (
	UnitTwip  = "twip"
	UnitCM    = "cm"
	UnitMM    = "mm"
	UnitInch  = "inch"
	UnitPoint = "point"
	UnitPica  = "pica"
)

Variables

This section is empty.

Functions

func AddHTML

func AddHTML(dst htmlContainer, html string, fullHTML ...bool) error

AddHTML parses HTML and appends equivalent elements to dst (PHPWord Shared\Html::addHtml).

func AddMarkdown added in v0.4.0

func AddMarkdown(dst htmlContainer, md string) error

AddMarkdown parses Markdown and appends native GoWord elements to dst.

func DefaultAsianFontName

func DefaultAsianFontName() string

DefaultAsianFontName returns the process-wide default East-Asian font.

func DefaultFontColor

func DefaultFontColor() string

DefaultFontColor returns the process-wide default color (hex, no #).

func DefaultFontName

func DefaultFontName() string

DefaultFontName returns the process-wide default font.

func DefaultFontSize

func DefaultFontSize() float64

DefaultFontSize returns the process-wide default size in points.

func DefaultPaper

func DefaultPaper() string

DefaultPaper returns the process-wide default paper size name.

func ExtractVariables

func ExtractVariables(filename string, readerName ...string) ([]string, error)

ExtractVariables returns ${placeholder} names from a template file.

func HasCompatibility

func HasCompatibility() bool

HasCompatibility reports XMLWriter compatibility mode (PHP Settings::hasCompatibility).

func IsDefaultRtl

func IsDefaultRtl() *bool

IsDefaultRtl reports the process-wide default RTL flag.

func IsOutputEscapingEnabled

func IsOutputEscapingEnabled() bool

IsOutputEscapingEnabled reports whether XML escaping is on.

func MeasurementUnit

func MeasurementUnit() string

MeasurementUnit returns the process-wide unit (twip, cm, mm, inch, point, pica).

func SetCompatibility

func SetCompatibility(v bool)

SetCompatibility toggles XMLWriter compatibility mode.

func SetDefaultAsianFontName

func SetDefaultAsianFontName(name string)

SetDefaultAsianFontName sets the process-wide default East-Asian font.

func SetDefaultFontColor

func SetDefaultFontColor(color string)

SetDefaultFontColor sets the process-wide default color.

func SetDefaultFontName

func SetDefaultFontName(name string)

SetDefaultFontName sets the process-wide default font.

func SetDefaultFontSize

func SetDefaultFontSize(size float64)

SetDefaultFontSize sets the process-wide default size in points.

func SetDefaultPaper

func SetDefaultPaper(name string)

SetDefaultPaper sets the process-wide default paper size name.

func SetDefaultRtl

func SetDefaultRtl(v *bool)

SetDefaultRtl sets the process-wide default RTL flag.

func SetMacroChars

func SetMacroChars(open, close string)

SetMacroChars sets both placeholder delimiters.

func SetMacroClosingChars

func SetMacroClosingChars(s string)

SetMacroClosingChars sets the placeholder closing delimiter.

func SetMacroOpeningChars

func SetMacroOpeningChars(s string)

SetMacroOpeningChars sets the placeholder opening delimiter (PHPWord).

func SetMeasurementUnit

func SetMeasurementUnit(unit string)

SetMeasurementUnit sets the process-wide unit.

func SetOutputEscapingEnabled

func SetOutputEscapingEnabled(v bool)

SetOutputEscapingEnabled toggles XML escaping of text (always recommended).

func SetTempDir

func SetTempDir(dir string)

SetTempDir sets a user-defined temporary directory.

func SetZipClass

func SetZipClass(name string)

SetZipClass is accepted for PHP parity; Go always uses archive/zip.

func TempDir

func TempDir() string

TempDir returns the user-defined temporary directory.

func ZipClass

func ZipClass() string

ZipClass returns the zip backend name (always ZipArchive in Go).

Types

type BlockData added in v0.3.0

type BlockData struct {
	Values map[string]string
	Blocks map[string][]BlockData
	If     map[string]bool
}

BlockData is one clone of a named template block, including nested blocks and ${if} conditions scoped to that instance.

type Document

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

Document is the PHPWord PhpWord class: an in-memory word-processing document.

func Load

func Load(filename string, readerName ...string) (*Document, error)

Load loads a document (PHPWord IOFactory::load). If readerName is omitted, the format is inferred from the file extension.

func LoadBytes

func LoadBytes(data []byte) (*Document, error)

func New

func New() *Document

New creates an empty document (PHPWord constructor).

func (*Document) AddChart added in v0.4.0

func (d *Document) AddChart(chartType string, categories []string, seriesData ...[]float64) *element.Chart

AddChart appends a native OpenXML chart to the last (or a new) section. seriesData is one or more value series aligned with categories.

func (*Document) AddChartStyled added in v0.4.0

func (d *Document) AddChartStyled(chartType string, categories []string, values []float64, st style.Chart) *element.Chart

AddChartStyled is AddChart with DrawingML chart style options.

func (*Document) AddDeletion added in v0.4.0

func (d *Document) AddDeletion(text, author, date string, styles ...any) *element.Text

AddDeletion appends tracked-delete text (w:del).

func (*Document) AddFontStyle

func (d *Document) AddFontStyle(name string, font any, para ...any)

AddFontStyle registers a named character style (PHPWord addFontStyle).

func (*Document) AddHTML added in v0.4.0

func (d *Document) AddHTML(htmlText string) error

AddHTML parses HTML into the last (or a new) section.

func (*Document) AddInsertion added in v0.4.0

func (d *Document) AddInsertion(text, author, date string, styles ...any) *element.Text

AddInsertion appends tracked-insert text (w:ins).

func (*Document) AddLinkStyle

func (d *Document) AddLinkStyle(name string, font any)

AddLinkStyle registers the Hyperlink character style.

func (*Document) AddMarkdown added in v0.4.0

func (d *Document) AddMarkdown(mdText string) error

AddMarkdown parses Markdown into the last (or a new) section.

func (*Document) AddNumberingStyle

func (d *Document) AddNumberingStyle(name string, num any)

AddNumberingStyle registers a named numbering definition.

func (*Document) AddParagraphStyle

func (d *Document) AddParagraphStyle(name string, para any)

AddParagraphStyle registers a named paragraph style.

func (*Document) AddSection

func (d *Document) AddSection(st ...any) *element.Section

AddSection appends a section (PHPWord addSection).

func (*Document) AddTableStyle

func (d *Document) AddTableStyle(name string, table any, firstRow ...any)

AddTableStyle registers a named table style.

func (*Document) AddTitleStyle

func (d *Document) AddTitleStyle(depth int, font any, para ...any)

AddTitleStyle registers HeadingN (depth 1-9). depth 0 is Title.

func (*Document) Bytes

func (d *Document) Bytes() ([]byte, error)

Bytes returns the Word2007 package as a byte slice.

func (*Document) CommentOn added in v0.4.0

func (d *Document) CommentOn(text, body, author string, extras ...string) *element.Text

CommentOn annotates text in the last (or a new) section. extras is optional initials then date.

func (*Document) Compatibility

func (d *Document) Compatibility() *metadata.Compatibility

Compatibility returns OOXML compatibility settings.

func (*Document) CountStyles

func (d *Document) CountStyles() int

CountStyles returns the number of registered named styles.

func (*Document) DocInfo

func (d *Document) DocInfo() *metadata.DocInfo

DocInfo returns document properties.

func (*Document) EnableTrackChanges added in v0.4.0

func (d *Document) EnableTrackChanges(on bool)

EnableTrackChanges turns on document-level revision tracking (w:trackRevisions).

func (*Document) GetBookmarks

func (d *Document) GetBookmarks() []*element.Bookmark

GetBookmarks returns bookmark elements.

func (*Document) GetCharts

func (d *Document) GetCharts() []*element.Chart

GetCharts returns chart elements.

func (*Document) GetComments

func (d *Document) GetComments() []*element.Comment

GetComments returns comment elements, including those attached as ranges.

func (*Document) GetCompatibility

func (d *Document) GetCompatibility() *metadata.Compatibility

GetCompatibility is the PHPWord name for Compatibility.

func (*Document) GetDefaultAsianFontName

func (d *Document) GetDefaultAsianFontName() string

func (*Document) GetDefaultFontColor

func (d *Document) GetDefaultFontColor() string

func (*Document) GetDefaultFontName

func (d *Document) GetDefaultFontName() string

func (*Document) GetDefaultFontSize

func (d *Document) GetDefaultFontSize() float64

func (*Document) GetDocInfo

func (d *Document) GetDocInfo() *metadata.DocInfo

GetDocInfo is the PHPWord name for DocInfo.

func (*Document) GetEndnotes

func (d *Document) GetEndnotes() []*element.Endnote

GetEndnotes returns endnote elements.

func (*Document) GetFootnotes

func (d *Document) GetFootnotes() []*element.Footnote

GetFootnotes returns footnote elements.

func (*Document) GetSection

func (d *Document) GetSection(index int) *element.Section

GetSection returns the section at index, or nil.

func (*Document) GetSections

func (d *Document) GetSections() []*element.Section

GetSections is the PHPWord name for Sections.

func (*Document) GetSettings

func (d *Document) GetSettings() *metadata.Settings

GetSettings is the PHPWord name for Settings.

func (*Document) GetStyle

func (d *Document) GetStyle(name string) *NamedStyle

GetStyle returns a named style, or nil.

func (*Document) GetStyles

func (d *Document) GetStyles() []NamedStyle

GetStyles returns registered named styles (PHPWord Style::getStyles).

func (*Document) GetTitles

func (d *Document) GetTitles() []*element.Title

GetTitles returns heading elements in document order.

func (*Document) ResetStyles

func (d *Document) ResetStyles()

ResetStyles clears the named-style registry (PHPWord Style::resetStyles).

func (*Document) Save

func (d *Document) Save(filename string) error

Save writes the document as Word2007 (.docx).

func (*Document) SaveAs

func (d *Document) SaveAs(filename, format string) error

SaveAs writes the document in the named format.

func (*Document) Sections

func (d *Document) Sections() []*element.Section

Sections returns all sections.

func (*Document) SetDefaultAsianFontName

func (d *Document) SetDefaultAsianFontName(name string)

func (*Document) SetDefaultFontColor

func (d *Document) SetDefaultFontColor(color string)

func (*Document) SetDefaultFontName

func (d *Document) SetDefaultFontName(name string)

func (*Document) SetDefaultFontSize

func (d *Document) SetDefaultFontSize(size float64)

func (*Document) SetDefaultParagraphStyle

func (d *Document) SetDefaultParagraphStyle(para any)

SetDefaultParagraphStyle sets the Normal style.

func (*Document) Settings

func (d *Document) Settings() *metadata.Settings

Settings returns document settings.

func (*Document) SortSections

func (d *Document) SortSections(less func(a, b *element.Section) bool)

SortSections sorts sections with the given comparison.

func (*Document) TrackRevisions added in v0.4.0

func (d *Document) TrackRevisions() bool

TrackRevisions reports whether revision tracking is on.

func (*Document) WriteTo

func (d *Document) WriteTo(dest io.Writer) (int64, error)

WriteTo writes a Word2007 package to dest.

type NamedStyle

type NamedStyle struct {
	Name      string
	Kind      string
	Font      *style.Font
	Paragraph *style.Paragraph
	Table     *style.Table
	FirstRow  *style.Table
	Numbering *style.Numbering
	Depth     int
}

NamedStyle is a document-scoped style definition (PHPWord Style registry entry).

type PhpWord

type PhpWord = Document

PhpWord is an alias for Document, matching the PHP class name.

type Reader

type Reader interface {
	Load(filename string) (*Document, error)
}

Reader loads a document from a file.

func CreateReader

func CreateReader(name string) (Reader, error)

CreateReader returns a reader for the named format (PHPWord IOFactory::createReader).

type StreamWriter added in v0.2.0

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

StreamWriter writes paragraphs and tables incrementally into a Word2007 (.docx) ZIP stream. document.xml is opened on the first write so large tables never accumulate as a single in-memory XML tree.

Close finishes document.xml and emits the remaining OOXML parts (content types, relationships, styles, media). StreamWriter is not safe for concurrent use.

func NewStreamWriter added in v0.2.0

func NewStreamWriter(dest io.Writer) *StreamWriter

NewStreamWriter starts a Word2007 package on dest.

func (*StreamWriter) BytesWritten added in v0.2.0

func (s *StreamWriter) BytesWritten() int64

BytesWritten returns the number of bytes written to dest so far.

func (*StreamWriter) Close added in v0.2.0

func (s *StreamWriter) Close() error

Close finishes document.xml and writes the remaining package parts.

func (*StreamWriter) WriteElement added in v0.2.0

func (s *StreamWriter) WriteElement(el element.Element) error

WriteElement writes any document body element into the stream.

func (*StreamWriter) WriteParagraph added in v0.2.0

func (s *StreamWriter) WriteParagraph(text string, styles ...any) error

WriteParagraph writes a paragraph of text into the open document.xml stream. styles follows Section.AddText: optional font then paragraph style.

func (*StreamWriter) WriteTable added in v0.2.0

func (s *StreamWriter) WriteTable(tbl *element.Table) error

WriteTable writes a table, flushing XML after each row.

type TemplateProcessor

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

TemplateProcessor fills ${placeholders} in an existing .docx (PHPWord TemplateProcessor).

func NewTemplateProcessor

func NewTemplateProcessor(filename string) (*TemplateProcessor, error)

NewTemplateProcessor opens a .docx template from disk.

func NewTemplateProcessorBytes

func NewTemplateProcessorBytes(data []byte) (*TemplateProcessor, error)

NewTemplateProcessorBytes opens a .docx template from memory.

func (*TemplateProcessor) ApplyConditionsFromValues added in v0.3.0

func (t *TemplateProcessor) ApplyConditionsFromValues(values map[string]string) error

ApplyConditionsFromValues treats empty/"0"/"false"/"no"/"off" as false.

func (*TemplateProcessor) Bytes

func (t *TemplateProcessor) Bytes() ([]byte, error)

Bytes returns the filled template as a .docx package.

func (*TemplateProcessor) CloneBlock

func (t *TemplateProcessor) CloneBlock(blockName string, count int) error

CloneBlock clones the region between ${block} and ${/block} count times. Nested ${inner}...${/inner} markers are indexed (${inner#1}) so they can be cloned per instance. Matching uses nesting depth for same-named blocks.

func (*TemplateProcessor) CloneBlockAndSetValues

func (t *TemplateProcessor) CloneBlockAndSetValues(blockName string, values []map[string]string) error

CloneBlockAndSetValues clones ${block}...${/block} once per values row (PHPWord).

func (*TemplateProcessor) CloneNestedBlock added in v0.3.0

func (t *TemplateProcessor) CloneNestedBlock(blockName string, items []BlockData) error

CloneNestedBlock clones ${name}...${/name} once per item, then clones nested blocks and applies values / conditions with #n suffixes.

func (*TemplateProcessor) CloneRow

func (t *TemplateProcessor) CloneRow(search string, count int) error

CloneRow clones the table row that contains ${search} count times, renaming macros to ${search#1}, ${search#2}, ... Vertically merged (w:vMerge restart/continue) rows are cloned as a single group.

func (*TemplateProcessor) CloneRowAndSetValues

func (t *TemplateProcessor) CloneRowAndSetValues(search string, values []map[string]string) error

CloneRowAndSetValues clones a row and fills ${name#n} from values.

func (*TemplateProcessor) DeleteBlock

func (t *TemplateProcessor) DeleteBlock(blockName string) error

DeleteBlock removes the region between ${block} and ${/block}.

func (*TemplateProcessor) DeleteRow

func (t *TemplateProcessor) DeleteRow(search string) error

DeleteRow removes the table row that contains ${search}.

func (*TemplateProcessor) GetVariableCount

func (t *TemplateProcessor) GetVariableCount() map[string]int

GetVariableCount returns placeholder name → occurrence count (PHPWord getVariableCount).

func (*TemplateProcessor) GetVariables

func (t *TemplateProcessor) GetVariables() []string

GetVariables returns unique placeholder names in first-seen order.

func (*TemplateProcessor) ReplaceBlock

func (t *TemplateProcessor) ReplaceBlock(blockName, replacement string) error

ReplaceBlock replaces the region between ${block} and ${/block}.

func (*TemplateProcessor) ReplaceCarriageReturns

func (t *TemplateProcessor) ReplaceCarriageReturns(s string) string

ReplaceCarriageReturns turns newlines into Word break runs (PHPWord).

func (*TemplateProcessor) ReplaceXmlBlock

func (t *TemplateProcessor) ReplaceXmlBlock(macroName, block, blockType string) error

ReplaceXmlBlock replaces the XML element of blockType that contains ${macro}.

func (*TemplateProcessor) Save

func (t *TemplateProcessor) Save(filename string) error

Save writes the filled template to filename.

func (*TemplateProcessor) SaveAs

func (t *TemplateProcessor) SaveAs(filename string) error

SaveAs is an alias for Save (PHPWord).

func (*TemplateProcessor) SetChart

func (t *TemplateProcessor) SetChart(search string, ch *element.Chart) error

SetChart replaces ${search} with a chart drawing and chart XML part (PHPWord).

func (*TemplateProcessor) SetCheckbox

func (t *TemplateProcessor) SetCheckbox(search string, checked bool)

SetCheckbox toggles a content-control checkbox at ${search}.

func (*TemplateProcessor) SetComplexBlock

func (t *TemplateProcessor) SetComplexBlock(search string, el element.Element) error

SetComplexBlock replaces the w:p containing ${search} with the rendered element.

func (*TemplateProcessor) SetComplexValue

func (t *TemplateProcessor) SetComplexValue(search string, el element.Element) error

SetComplexValue replaces the w:r containing ${search} with the rendered element.

func (*TemplateProcessor) SetCondition added in v0.3.0

func (t *TemplateProcessor) SetCondition(name string, keep bool) error

SetCondition keeps or clips ${if name}...${endif}.

func (*TemplateProcessor) SetConditions added in v0.3.0

func (t *TemplateProcessor) SetConditions(conds map[string]bool) error

SetConditions applies many named ${if} blocks.

func (*TemplateProcessor) SetImageValue

func (t *TemplateProcessor) SetImageValue(search, path string) error

SetImageValue replaces a placeholder with a drawing that references a new image part.

func (*TemplateProcessor) SetImageValueBytes

func (t *TemplateProcessor) SetImageValueBytes(search, filename string, data []byte) error

SetImageValueBytes embeds image bytes at ${search}.

func (*TemplateProcessor) SetMacroChars

func (t *TemplateProcessor) SetMacroChars(open, close string)

func (*TemplateProcessor) SetMacroClosingChars

func (t *TemplateProcessor) SetMacroClosingChars(s string)

func (*TemplateProcessor) SetMacroOpeningChars

func (t *TemplateProcessor) SetMacroOpeningChars(s string)

func (*TemplateProcessor) SetUpdateFields

func (t *TemplateProcessor) SetUpdateFields(update bool)

SetUpdateFields sets w:updateFields in word/settings.xml.

func (*TemplateProcessor) SetValue

func (t *TemplateProcessor) SetValue(search, replace string)

SetValue replaces ${search} with replace across document parts.

func (*TemplateProcessor) SetValueLimit

func (t *TemplateProcessor) SetValueLimit(search, replace string, limit int)

SetValueLimit replaces at most limit occurrences (-1 = all).

func (*TemplateProcessor) SetValues

func (t *TemplateProcessor) SetValues(values map[string]string)

SetValues replaces many placeholders.

type Writer

type Writer interface {
	Save(filename string) error
	WriteTo(w io.Writer) (int64, error)
}

Writer writes a document to a file or stream.

func CreateWriter

func CreateWriter(doc *Document, name string) (Writer, error)

CreateWriter returns a writer for the named format (PHPWord IOFactory::createWriter).

Directories

Path Synopsis
examples
simple command
pkg

Jump to

Keyboard shortcuts

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