word

package module
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: LGPL-3.0 Imports: 28 Imported by: 0

README

GoWord

中文文档 | English

Go Version Go Reference CI

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

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

Features

  • Zero External Dependencies — 100% Go standard library (encoding/xml, archive/zip, image, sync). go.mod has no third-party require.
  • DOCX to HTML — render documents as fragments or standalone pages, stream output to io.Writer, and inspect conversion diagnostics. Configure ZIP read limits and image URLs without cgo or an external office suite.
  • SDT form controls — AddSDTText, AddSDTDropdown, AddSDTDate, and AddSDTCheckbox emit Word content controls (w:sdt → w:sdtPr → w:sdtContent), including Word 2010 w14:checkbox.
  • Table Mechanics Plus — repeating headers (w:tblHeader via SetHeader / SetHeaderRow), unbreakable rows (w:cantSplit), cell vertical align (SetVAlign), and text direction (SetTextDirection).
  • Tiled / image watermarks — SetTextWatermark(text, WatermarkOptions{Tile, Angle, …}) writes a 3×3 VML grid; SetImageWatermark / SetImageWatermarkFile add a washout picture watermark.
  • Region edit exceptions — Protect still writes w:documentProtection; AllowEdit("Everyone") on a paragraph, cell, or table wraps w:permStart / w:permEnd so those ranges stay editable.
  • Office Math (OMML) — AddMath turns basic LaTeX (\frac{a}{b}, x^{2}, \sqrt{x_1}, \pi) into Word-native m:oMathPara / m:oMath equations that open in the built-in equation editor.
  • Document Merger — AppendDocument clones source sections and remaps colliding style IDs, bookmark names, and image rId / media parts so several .docx trees splice without resource clashes.
  • DrawingML & Charts — bar, column, line, pie, area, stacked, and dual-axis combo charts, plus vector shapes and text boxes (wps:wsp, w:txbxContent) with fill, outline, and inner text.
  • Streaming Parser — StreamExtractText / StreamExtractImages walk a .docx ZIP with (O(1)) extra memory, emitting paragraphs and pictures as they are read.
  • Bounded ZIP reads — ReadOptions limits archive bytes, uncompressed part size, total declared expansion, and entry count through additive WithOptions APIs; zero keeps legacy unlimited behavior.
  • Template Engine v2 — ${variable} placeholders, nested ${block} loops, binary ${if} / ${endif} clipping, and chained ${var | pipe} filters (formatDate, formatCurrency, trim, upper, lower, truncate, default).
  • Advanced Layout — mixed portrait/landscape sections, multi-column layout (w:cols), automatic TOC, VML watermarks, and read-only document protection.

Also included: tables with nested cells, headers/footers, images, lists, footnotes/endnotes, bookmarks and internal hyperlinks, Markdown/HTML import, DOCX to HTML rendering, comments, track changes, a streaming Save / StreamWriter, and sync.Pool buffer reuse.

Installation

go get github.com/yunkeweb/go-word@v0.13.0

Requires Go 1.21+.

DOCX to HTML in v0.13.0

RenderHTMLFile returns HTML bytes. Save them with os.WriteFile, or load a document and use Document.WriteHTML for direct writer output. The DOCX to HTML guide includes complete programs, all seven entry points, image handling, diagnostics, and ZIP read limits.

The renderer supports nested lists and numbering, DOM table merges, bookmarks, section boundaries, and optional headers/footers. Conversion targets readable HTML; Word pagination and arbitrary DOCX fidelity are not guaranteed. Strict mode checks retained DOM elements, not content omitted during reading.

When upgrading, use keyed style.ListItem and style.Spacing literals: these types add Start and BeforeSet/AfterSet, respectively. See the upgrade notes and changelog.

v0.13.0 fixes: With Standalone: true and IncludeCSS: true, HTML uses each section's paper size, orientation and margins to preserve the DOCX content width on screen and when printing. Explicit hyperlink colors and underline settings override browser defaults. Screen previews grow vertically; Word's automatic pagination is not reproduced. The DOCX style inheritance fixes from v0.12.1 remain included.

DOCX to HTML fidelity work for v0.13.0

The v0.13.0 renderer keeps the existing HTML APIs and adds paragraph pagination hints, section-aware header/footer containers, safe print repetition for a simple default header/footer pair, repeating table headers, fixed table layout, borders, spacing and cell padding, EMU image dimensions and wrapping metadata, theme font/color resolution, font fallback and additional paragraph metrics. Unknown image wrapping remains visible and is reported through HTMLDiagnostic (or strict mode). Screen output still uses flowing sections; it is not a Word pagination engine. See the DOCX to HTML guide for browser and print boundaries.

Quick Start

Create a protected form with SDT controls, a repeating table header, a tiled diagonal watermark, and an editable exception range:

package main

import (
	"log"

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

func main() {
	doc := word.New()
	doc.SetDefaultFontName("Calibri")

	doc.SetTextWatermark("CONFIDENTIAL", word.WatermarkOptions{
		Angle: -45, Color: "C0C0C0", FontSize: 36, Opacity: 0.28,
		Tile: true, Rows: 3, Cols: 3,
	})
	if err := doc.Protect(word.ProtectTypeReadOnly, "goword"); err != nil {
		log.Fatal(err)
	}

	sec := doc.AddSection()
	sec.AddTitle("GoWord v0.13.0", 1)
	sec.AddSDTText("Full name", "full_name", "Enter full name")
	sec.AddSDTDropdown("Department", "dept", map[string]string{
		"eng": "Engineering",
		"hr":  "Human Resources",
	})
	sec.AddSDTDate("Start date", "start_date", "yyyy-MM-dd")
	sec.AddText("Party A: ________________").AllowEdit("Everyone")

	tbl := sec.AddTable(style.Table{Width: 9000})
	hdr := tbl.AddRow()
	tbl.SetHeaderRow(hdr)
	hdr.SetCantSplit(true)
	hdr.AddCell(3000).SetVAlign("center").AddText("Field", style.Font{Bold: true})
	hdr.AddCell(6000).SetVAlign("center").AddText("Value", style.Font{Bold: true})
	row := tbl.AddRow()
	row.AddCell(3000).SetTextDirection("tbRl").AddText("Note")
	row.AddCell(6000).AllowEdit("Everyone").AddText("CN-2026-001")

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

Runnable samples:

Example What it shows
examples/v0.9.0_sdt Plain text, drop-down, date, checkbox SDT
examples/v0.9.0_table_advanced tblHeader, cantSplit, vAlign, textDirection
examples/v0.9.0_watermark_security Tiled text watermark, image washout, AllowEdit
examples/v0.8.0_demo OMML, DrawingML shapes, columns, AppendDocument
examples/read_limits Bounded ZIP reads with ReadOptions
examples/docx_to_html Render a DOCX DOM as standalone HTML
examples/simple Styles, titles, and a first .docx

API reference: pkg.go.dev/github.com/yunkeweb/go-word. Site: go-word.yunkeweb.com. The DOCX to HTML guide covers file conversion, image assets, diagnostics, and strict mode.

Full-feature matrix

tests/matrix writes 80 randomly combined .docx files covering every public API from v0.1.0 through v0.9.0 (typography, multi-section, headers/footers, tables, images/shapes, TOC/bookmarks/comments, OMML, charts, SDT, watermark/protection). Generated files stay in ./test_output_docs (gitignored).

go run ./tests/matrix
go run tests/matrix/validate_reader.go

validate_reader.go reverse-parses each file through word.Open / word.Read, word.StreamExtractText, and word.StreamExtractImages (there is no ReadDOM). The 80-document matrix can be generated and reverse-parsed locally; opening files in Microsoft Word remains an optional Windows-only manual check.

Document merger

dst := word.New()
src := word.New()
// ... fill both documents ...
if err := dst.AppendDocument(src, word.MergeOptions{
	StylePrefix:    "src_",
	BookmarkPrefix: "src_",
	SectionBreak:   "nextPage",
}); err != nil {
	log.Fatal(err)
}

Colliding paragraph style names and bookmark names are prefixed; image parts receive fresh relationship IDs when the package is written.

Reader and template APIs

  • The reader restores section properties, common header/footer parts, notes, comments, tracked changes, and list numbering during DOCX round trips.
  • TemplateProcessor.SetValue recognizes macros split across adjacent Word text runs while retaining run properties.
  • NewWithOptions isolates default font settings per document, and ValidatePackage reports ZIP/XML/relationship/bookmark diagnostics.

See the reader and diagnostics guide.

License

GNU Lesser General Public License version 3, same family as PHPWord. See 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"
	ChartTypeArea               = "area"
	ChartTypeStackedArea        = "stacked_area"
	ChartTypePercentStackedArea = "percent_stacked_area"
	ChartTypeCombo              = "combo"
)

Chart type names used by AddChart and Container.AddChart.

View Source
const (
	LegendTop    = "t"
	LegendBottom = "b"
	LegendLeft   = "l"
	LegendRight  = "r"
)

Legend positions (c:legendPos).

View Source
const (
	DataLabelPosBestFit = "bestFit"
	DataLabelPosBottom  = "b"
	DataLabelPosCenter  = "ctr"
	DataLabelPosInBase  = "inBase"
	DataLabelPosInEnd   = "inEnd"
	DataLabelPosLeft    = "l"
	DataLabelPosOutEnd  = "outEnd"
	DataLabelPosRight   = "r"
	DataLabelPosTop     = "t"
)

Data label positions (c:dLblPos).

View Source
const (
	ProtectTypeNone           = style.DocProtectNone
	ProtectTypeReadOnly       = style.DocProtectReadOnly
	ProtectTypeComments       = style.DocProtectComments
	ProtectTypeTrackedChanges = style.DocProtectTrackedChanges
	ProtectTypeForms          = style.DocProtectForms
)

Document protection modes (OOXML ST_DocProtect).

View Source
const (
	VAlignTop    = style.VAlignTop
	VAlignCenter = style.VAlignCenter
	VAlignBottom = style.VAlignBottom
)

Vertical cell alignment (ST_VerticalJc), re-exported for document APIs.

View Source
const (
	TextDirectionHorizontal = style.TextDirectionLrTb
	TextDirectionVertical   = style.TextDirectionTbRl
)

Text direction (ST_TextDirection).

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

Variables

View Source
var ErrInvalidReadOptions = errors.New("word: invalid read options")

ErrInvalidReadOptions reports an invalid negative read budget.

View Source
var ErrReadLimitExceeded = common.ErrZipLimitExceeded

ErrReadLimitExceeded reports that a configured ZIP read budget was exceeded. Use errors.Is to recognize it through contextual errors.

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 RegisterTemplateFilter added in v0.7.0

func RegisterTemplateFilter(name string, fn func(in any, args ...string) string)

RegisterTemplateFilter installs or replaces a named pipe filter.

func RenderHTML added in v0.12.0

func RenderHTML(r io.Reader, opts HTMLOptions) ([]byte, error)

RenderHTML reads a DOCX from r and renders it as HTML.

func RenderHTMLFile added in v0.12.0

func RenderHTMLFile(path string, opts HTMLOptions) ([]byte, error)

RenderHTMLFile loads a DOCX file and renders it as HTML.

func RenderHTMLFileWithOptions added in v0.12.0

func RenderHTMLFileWithOptions(path string, readOpts ReadOptions, htmlOpts HTMLOptions) ([]byte, error)

RenderHTMLFileWithOptions loads a DOCX with read budgets and renders it as HTML.

func RenderHTMLWithOptions added in v0.12.0

func RenderHTMLWithOptions(r io.Reader, readOpts ReadOptions, htmlOpts HTMLOptions) ([]byte, error)

RenderHTMLWithOptions reads a DOCX with read budgets and renders it as HTML.

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 StreamExtractImages added in v0.7.0

func StreamExtractImages(r io.Reader, fn func(img ImageFile) error) error

StreamExtractImages scans word/document.xml for DrawingML blips and VML imagedata, then streams each referenced media part from the ZIP into fn.

func StreamExtractImagesWithOptions added in v0.10.0

func StreamExtractImagesWithOptions(r io.Reader, fn func(img ImageFile) error, opts ReadOptions) error

StreamExtractImagesWithOptions scans images with optional ZIP budgets.

func StreamExtractText added in v0.7.0

func StreamExtractText(r io.Reader, fn func(paragraphText string) error) error

StreamExtractText scans word/document.xml with xml.Decoder and invokes fn once for every complete w:p. Paragraph buffers are discarded after each callback so memory stays O(1) relative to document size.

func StreamExtractTextWithOptions added in v0.10.0

func StreamExtractTextWithOptions(r io.Reader, fn func(paragraphText string) error, opts ReadOptions) error

StreamExtractTextWithOptions scans word/document.xml with optional ZIP budgets.

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 ChartDataLabelOptions added in v0.7.0

type ChartDataLabelOptions = style.DataLabelOptions

ChartDataLabelOptions configures c:dLbls on a chart.

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 LoadBytesWithOptions added in v0.10.0

func LoadBytesWithOptions(data []byte, opts ReadOptions) (*Document, error)

LoadBytesWithOptions loads a document with optional ZIP read budgets.

func LoadWithOptions added in v0.10.0

func LoadWithOptions(filename string, opts ReadOptions) (*Document, error)

LoadWithOptions loads a document from disk with optional ZIP read budgets.

func New

func New() *Document

New creates an empty document (PHPWord constructor).

func NewWithOptions added in v0.11.0

func NewWithOptions(opts DocumentOptions) *Document

NewWithOptions creates a document with instance-local defaults.

func Open added in v0.6.0

func Open(filePath string) (*Document, error)

Open loads a .docx from a filesystem path into an in-memory DOM.

func OpenWithOptions added in v0.10.0

func OpenWithOptions(filename string, opts ReadOptions) (*Document, error)

OpenWithOptions is the Open counterpart with optional ZIP read budgets.

func Read added in v0.6.0

func Read(r io.Reader) (*Document, error)

Read loads a .docx from r into an in-memory DOM.

func ReadWithOptions added in v0.10.0

func ReadWithOptions(r io.Reader, opts ReadOptions) (*Document, error)

ReadWithOptions loads a document from r with optional ZIP read budgets.

func (*Document) AddBookmark added in v0.6.0

func (d *Document) AddBookmark(p *Paragraph, name string) *element.Bookmark

AddBookmark writes a bookmarkStart/bookmarkEnd pair on paragraph p. If p is nil, the bookmark is appended to the last section.

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) AddHyperlinkToBookmark added in v0.6.0

func (d *Document) AddHyperlinkToBookmark(p *Paragraph, text, bookmarkName string) *element.Link

AddHyperlinkToBookmark appends an internal hyperlink (w:hyperlink w:anchor) that jumps to bookmarkName. If p is nil, the link is added to the last 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) AddMath added in v0.8.0

func (d *Document) AddMath(formula string) *element.Formula

AddMath appends a display OMML equation parsed from a basic LaTeX string to the last (or a new) section.

func (*Document) AddNumPages added in v0.5.0

func (d *Document) AddNumPages() *element.Field

AddNumPages inserts a NUMPAGES field into the current section.

func (*Document) AddNumberingStyle

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

AddNumberingStyle registers a named numbering definition.

func (*Document) AddPageNumber added in v0.5.0

func (d *Document) AddPageNumber() *element.Field

AddPageNumber inserts a PAGE field into the current section.

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) AddShape added in v0.8.0

func (d *Document) AddShape(shapeType ShapeType, opts ShapeOptions) *element.DMLShape

AddShape appends a DrawingML shape (rectangle, rounded rectangle, arrow, or text box) to the last (or a new) section.

func (*Document) AddTableOfContents added in v0.5.0

func (d *Document) AddTableOfContents(depth ...int) *element.TOC

AddTableOfContents inserts an OpenXML TOC field covering Heading 1–3 by default (TOC \o "1-3" \h \z \u). Optional depth is max, or min,max.

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) AppendDocument added in v0.8.0

func (d *Document) AppendDocument(src *Document, opts MergeOptions) error

AppendDocument clones src onto d, remapping colliding style names, bookmark names, and media so the merged package writes unique rIds and part paths.

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) ExtractImages added in v0.6.0

func (d *Document) ExtractImages() ([]ImageFile, error)

ExtractImages returns pictures from word/media/ (after Open/Read) or from in-memory image elements on a newly built document.

func (*Document) ExtractText added in v0.6.0

func (d *Document) ExtractText() string

ExtractText returns document body text in paragraph and table order.

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) GetMetadata added in v0.6.0

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

GetMetadata returns core document properties (author, created, modified, ...).

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) Protect added in v0.5.0

func (d *Document) Protect(editing, password string) error

Protect enables document protection (w:documentProtection). An empty password writes an unenforced-hash protection node; a non-empty password uses the Office SHA-1 / 100000-spin algorithm (ECMA-376).

func (*Document) RenderHTML added in v0.12.0

func (d *Document) RenderHTML(opts HTMLOptions) ([]byte, error)

RenderHTML renders a loaded document as an HTML fragment or standalone page.

func (*Document) RenderHTMLWithDiagnostics added in v0.12.0

func (d *Document) RenderHTMLWithDiagnostics(opts HTMLOptions) (HTMLRenderResult, error)

RenderHTMLWithDiagnostics renders a document and returns conversion diagnostics.

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) SetDifferentFirstPage added in v0.5.0

func (d *Document) SetDifferentFirstPage(enable bool)

SetDifferentFirstPage enables a first-page header/footer on the current section (w:titlePg plus HeaderFirst / FooterFirst).

func (*Document) SetEvenAndOddHeaders added in v0.5.0

func (d *Document) SetEvenAndOddHeaders(enable bool)

SetEvenAndOddHeaders toggles odd/even page headers and footers (w:evenAndOddHeaders plus HeaderEven / FooterEven parts).

func (*Document) SetImageWatermark added in v0.5.0

func (d *Document) SetImageWatermark(imageBytes []byte, opts ...ImageWatermarkOptions)

SetImageWatermark stores a document-wide image watermark applied to every section header as VML v:imagedata (Word watermark drawing).

func (*Document) SetImageWatermarkFile added in v0.9.0

func (d *Document) SetImageWatermarkFile(path string, opts ...ImageWatermarkOptions) error

SetImageWatermarkFile loads a PNG or JPEG from disk as a page watermark.

func (*Document) SetTextWatermark added in v0.5.0

func (d *Document) SetTextWatermark(text string, opts ...WatermarkOptions)

SetTextWatermark stores a document-wide text watermark applied to every section header as Word-native VML (PowerPlusWaterMarkObject).

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) StreamExtractImages added in v0.7.0

func (d *Document) StreamExtractImages(r io.Reader, fn func(img ImageFile) error) error

StreamExtractImages is the Document-method form of the package-level extractor.

func (*Document) StreamExtractImagesWithOptions added in v0.10.0

func (d *Document) StreamExtractImagesWithOptions(r io.Reader, fn func(img ImageFile) error, opts ReadOptions) error

StreamExtractImagesWithOptions is the Document-method form with ZIP budgets.

func (*Document) StreamExtractText added in v0.7.0

func (d *Document) StreamExtractText(r io.Reader, fn func(paragraphText string) error) error

StreamExtractText is the Document-method form of the package-level extractor.

func (*Document) StreamExtractTextWithOptions added in v0.10.0

func (d *Document) StreamExtractTextWithOptions(r io.Reader, fn func(paragraphText string) error, opts ReadOptions) error

StreamExtractTextWithOptions is the Document-method form with ZIP budgets.

func (*Document) TrackRevisions added in v0.4.0

func (d *Document) TrackRevisions() bool

TrackRevisions reports whether revision tracking is on.

func (*Document) WriteHTML added in v0.12.0

func (d *Document) WriteHTML(w io.Writer, opts HTMLOptions) error

WriteHTML renders the document directly to an output stream.

func (*Document) WriteTo

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

WriteTo writes a Word2007 package to dest.

type DocumentOptions added in v0.11.0

type DocumentOptions struct {
	DefaultFontName      string
	DefaultAsianFontName string
	DefaultFontSize      float64
	DefaultFontColor     string
}

DocumentOptions configures defaults for one document instance. Zero values inherit the package defaults used by New.

type HTMLDiagnostic added in v0.12.0

type HTMLDiagnostic struct {
	ElementType string
	Message     string
}

HTMLDiagnostic describes a lossy or unsupported conversion.

type HTMLImageMode added in v0.12.0

type HTMLImageMode string

HTMLImageMode controls image references in rendered HTML.

const (
	HTMLImageDataURI HTMLImageMode = "data"
	HTMLImageURL     HTMLImageMode = "url"
)

type HTMLOptions added in v0.12.0

type HTMLOptions struct {
	Standalone            bool
	Title                 string
	ImageMode             HTMLImageMode
	ImageURL              func(*element.Image) (string, error)
	IncludeHeadersFooters bool
	IncludeCSS            bool // with Standalone, include built-in CSS and section page geometry
	Strict                bool
}

HTMLOptions controls DOCX to HTML rendering.

type HTMLRenderResult added in v0.12.0

type HTMLRenderResult struct {
	HTML        []byte
	Diagnostics []HTMLDiagnostic
}

HTMLRenderResult contains rendered HTML and non-fatal diagnostics.

type HTMLUnsupportedError added in v0.12.0

type HTMLUnsupportedError struct{ Diagnostics []HTMLDiagnostic }

HTMLUnsupportedError reports unsupported elements in strict mode.

func (*HTMLUnsupportedError) Error added in v0.12.0

func (e *HTMLUnsupportedError) Error() string

type ImageFile added in v0.6.0

type ImageFile struct {
	Name string
	MIME string
	Data []byte
}

ImageFile is a media part extracted from word/media/.

type ImageWatermarkOptions added in v0.9.0

type ImageWatermarkOptions struct {
	Washout bool    // Word washout (gain/blacklevel)
	Scale   float64 // size multiplier; 0 leaves the default size
	Opacity float64 // 0–1; 0 omits v:fill opacity
}

ImageWatermarkOptions configures a VML picture watermark (WordPictureWatermark).

type MergeOptions added in v0.8.0

type MergeOptions struct {
	StylePrefix    string
	BookmarkPrefix string
	SectionBreak   string
}

MergeOptions controls how AppendDocument remaps colliding identifiers.

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 PackageDiagnostic added in v0.11.0

type PackageDiagnostic struct {
	Severity string // error, warning
	Code     string
	Part     string
	Message  string
}

PackageDiagnostic describes a recoverable package validation finding.

func ValidatePackage added in v0.11.0

func ValidatePackage(data []byte) []PackageDiagnostic

ValidatePackage validates a DOCX ZIP package without mutating it.

type Paragraph added in v0.6.0

type Paragraph = element.TextRun

Paragraph is a rich-text paragraph used by bookmark and hyperlink APIs.

type PhpWord

type PhpWord = Document

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

type ReadOptions added in v0.10.0

type ReadOptions struct {
	MaxArchiveSize int64 // compressed package bytes
	MaxPartSize    int64 // one uncompressed ZIP member
	MaxTotalSize   int64 // sum of uncompressed ZIP members
	MaxEntries     int   // number of ZIP members
}

ReadOptions controls optional resource limits while reading a package. All limits are per call. Zero preserves the historical unlimited behavior.

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 ShapeOptions added in v0.8.0

type ShapeOptions struct {
	Width     int
	Height    int
	FillColor string
	LineColor string
	LineWidth int
	Text      string
	Font      style.Font
}

ShapeOptions controls DrawingML fill, outline, size (EMU) and text.

type ShapeType added in v0.8.0

type ShapeType string

DrawingML preset geometry names.

const (
	ShapeRect      ShapeType = "rect"
	ShapeRoundRect ShapeType = "roundRect"
	ShapeArrow     ShapeType = "rightArrow"
	ShapeTextBox   ShapeType = "textBox"
)

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 TemplateFilter added in v0.7.0

type TemplateFilter func(in any, args ...string) string

TemplateFilter transforms a placeholder value. args are the : separated arguments from ${var | filter:arg}.

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 NewTemplateProcessorBytesWithOptions added in v0.10.0

func NewTemplateProcessorBytesWithOptions(data []byte, opts ReadOptions) (*TemplateProcessor, error)

NewTemplateProcessorBytesWithOptions opens a template with ZIP read budgets.

func NewTemplateProcessorWithOptions added in v0.10.0

func NewTemplateProcessorWithOptions(filename string, opts ReadOptions) (*TemplateProcessor, error)

NewTemplateProcessorWithOptions opens a disk template with ZIP read budgets.

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 WatermarkOptions added in v0.9.0

type WatermarkOptions struct {
	Angle    float64 // degrees; 0 defaults to -45
	Color    string  // VML fillcolor, e.g. silver or C0C0C0
	FontSize int     // points; 0 uses Word's 1pt + fitshape
	FontName string  // default Calibri
	Opacity  float64 // 0–1; 0 defaults to 0.5. Values > 1 are treated as percent
	Tile     bool    // full-page grid
	Rows     int     // tile rows, default 3
	Cols     int     // tile columns, default 3
}

WatermarkOptions configures a VML text watermark (PowerPlusWaterMarkObject).

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
all_in_one command
Command all_in_one builds all_features_demo.docx, exercising every major GoWord surface: styles, merged tables, StreamWriter, charts, Markdown/HTML import, the template engine, comments, and track changes.
Command all_in_one builds all_features_demo.docx, exercising every major GoWord surface: styles, merged tables, StreamWriter, charts, Markdown/HTML import, the template engine, comments, and track changes.
docx_to_html command
read_limits command
simple command
v0.5.0_demo command
Command v0.5.0_demo builds enterprise_demo.docx: watermarks, document protection, mixed portrait/landscape sections, first/odd/even headers, PAGE/NUMPAGES fields, and an H1–H3 table of contents.
Command v0.5.0_demo builds enterprise_demo.docx: watermarks, document protection, mixed portrait/landscape sections, first/odd/even headers, PAGE/NUMPAGES fields, and an H1–H3 table of contents.
v0.6.0_demo command
Command v0.6.0_demo builds parsing_demo.docx: nested tables, cell styling, bookmarks with internal hyperlinks, then re-opens the package and prints ExtractText / ExtractImages / GetMetadata results.
Command v0.6.0_demo builds parsing_demo.docx: nested tables, cell styling, bookmarks with internal hyperlinks, then re-opens the package and prints ExtractText / ExtractImages / GetMetadata results.
v0.7.0_demo command
Command v0.7.0_demo builds v070_demo.docx (area + combo charts, image) and template_v2.docx (pipe filters and comparison ifs), then streams 100_000 paragraphs through StreamExtractText.
Command v0.7.0_demo builds v070_demo.docx (area + combo charts, image) and template_v2.docx (pipe filters and comparison ifs), then streams 100_000 paragraphs through StreamExtractText.
v0.8.0_demo command
Command v0.8.0_demo builds v080_demo.docx (OMML math, DrawingML shapes, multi-column layout) and v080_merged.docx (document merger).
Command v0.8.0_demo builds v080_demo.docx (OMML math, DrawingML shapes, multi-column layout) and v080_merged.docx (document merger).
v0.9.0_sdt command
Command v0.9.0_sdt builds v090_sdt.docx with four Word content controls (plain text, drop-down, date picker, checkbox) that open in Microsoft Word.
Command v0.9.0_sdt builds v090_sdt.docx with four Word content controls (plain text, drop-down, date picker, checkbox) that open in Microsoft Word.
v0.9.0_table_advanced command
Command v0.9.0_table_advanced builds v090_table_advanced.docx with repeating table headers, unbreakable rows, vertical cell alignment, and vertical text direction.
Command v0.9.0_table_advanced builds v090_table_advanced.docx with repeating table headers, unbreakable rows, vertical cell alignment, and vertical text direction.
v0.9.0_watermark_security command
Command v0.9.0_watermark_security builds a protected document with a tiled diagonal text watermark, an image-watermark companion file, and exception ranges (w:permStart / w:permEnd) that remain editable.
Command v0.9.0_watermark_security builds a protected document with a tiled diagonal text watermark, an image-watermark companion file, and exception ranges (w:permStart / w:permEnd) that remain editable.
word_diag command
Command word_diag writes six single-module .docx files so Microsoft Word can isolate which OpenXML feature refuses to open.
Command word_diag writes six single-module .docx files so Microsoft Word can isolate which OpenXML feature refuses to open.
pkg
tests
matrix command
Command generate_full_feature_docs writes 50–100 randomly combined GoWord feature documents into ./test_output_docs.
Command generate_full_feature_docs writes 50–100 randomly combined GoWord feature documents into ./test_output_docs.

Jump to

Keyboard shortcuts

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