中文文档 | English
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.
- Zero External Dependencies — 100% Go standard library (
encoding/xml,archive/zip,image,sync).go.modhas no third-partyrequire. - 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, andAddSDTCheckboxemit Word content controls (w:sdt→w:sdtPr→w:sdtContent), including Word 2010w14:checkbox. - Table Mechanics Plus — repeating headers (
w:tblHeaderviaSetHeader/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/SetImageWatermarkFileadd a washout picture watermark. - Region edit exceptions —
Protectstill writesw:documentProtection;AllowEdit("Everyone")on a paragraph, cell, or table wrapsw:permStart/w:permEndso those ranges stay editable. - Office Math (OMML) —
AddMathturns basic LaTeX (\frac{a}{b},x^{2},\sqrt{x_1},\pi) into Word-nativem:oMathPara/m:oMathequations that open in the built-in equation editor. - Document Merger —
AppendDocumentclones source sections and remaps colliding style IDs, bookmark names, and imagerId/ media parts so several.docxtrees 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/StreamExtractImageswalk a.docxZIP with (O(1)) extra memory, emitting paragraphs and pictures as they are read. - Bounded ZIP reads —
ReadOptionslimits archive bytes, uncompressed part size, total declared expansion, and entry count through additiveWithOptionsAPIs; 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.
go get github.com/yunkeweb/go-word@v0.15.0Requires Go 1.21+.
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, optional headers/footers, cached fields, notes and comments, tracked revisions, and read-only content controls. Conversion targets readable HTML; Word pagination and arbitrary DOCX fidelity are not guaranteed. Strict mode checks retained DOM elements, not content omitted during reading.
v0.14.0 content integrity: Cached field results remain visible, dangling note/comment references keep their numbers without broken links, and RevisionMode selects final, original, or markup output. Structured document tags retain their visible value and metadata without generating form submission or script behavior.
v0.15.0 complex objects: DrawingML shapes and text boxes retain safe geometry, fill, outline, rotation, flipping, and inner text as HTML/CSS containers. Charts are rendered as JavaScript-free semantic tables with titles, legends, series, categories, values, and combo-axis metadata. Missing chart caches and unknown drawing structures remain visible through diagnostics and readable fallback output. External image URLs are not downloaded by default.
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.
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.
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.15.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.
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.govalidate_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.
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.
- The reader restores section properties, common header/footer parts, notes, comments, tracked changes, and list numbering during DOCX round trips.
TemplateProcessor.SetValuerecognizes macros split across adjacent Word text runs while retaining run properties.NewWithOptionsisolates default font settings per document, andValidatePackagereports ZIP/XML/relationship/bookmark diagnostics.
See the reader and diagnostics guide.
GNU Lesser General Public License version 3, same family as PHPWord. See LICENSE.