wordingo

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Aug 9, 2026 License: MIT Imports: 17 Imported by: 0

README

WordInGo

WordInGo logo

Pure Go library for creating and editing Word documents — zero external dependencies.

What it is

wordingo lets you build .docx files from scratch, open and edit existing ones, and convert between Word and Markdown. Everything is pure Go — no C bindings, no system calls to Word, no binaries to install. Just go get and you're off.

doc, _ := wordingo.Create()
doc.AddParagraph("Hello, Word!")
doc.Save("output.docx")

Key features

What How
Create & open Blank documents with default styles, or open existing .docx files and edit them
Templates Clone a template's look (colors, fonts, heading styles) into your document
Text & formatting Bold, italic, underline, color, highlights, font family, size — the works
Tables Quick grid from [][]string, or a full builder with borders, shading, merged cells
Images Embed PNG or JPEG photos; set display size in inches; auto DPI detection
Headers & footers Default, first-page, and even-page variants with full paragraph editing
Lists Bulleted, numbered, nested up to 9 levels
Hyperlinks Clickable links with styled, colored text
Page setup Portrait/landscape, Letter/A4/Legal, custom margins and page breaks
Template merge Replace {{placeholders}} in text, table cells, headers, and footers
Edit operations Insert or delete paragraphs by reference, replace text in runs, delete table rows
Table of contents Generate a TOC from the document's own headings, with live field updates in Word
Text extraction Pull plain text from the whole document or specific sections
Markdown export Convert any .docx to GitHub-flavored Markdown
Markdown import Create a Word doc from Markdown — headings, lists, tables, code blocks, images
Inline docs No magic numbers: every unit type (twips, dxa, half-points) follows Word's conventions

Quick start

package main

import (
    "log"
    "github.com/fabiomarini/wordingo"
)

func main() {
    doc, err := wordingo.Create()
    if err != nil { log.Fatal(err) }
    defer doc.Close()

    doc.AddParagraph("The Art of Go").SetStyle("Title")
    p := doc.AddParagraph("Go is statically typed, compiled, and fast.")
    p.AddRun(" Fast.").SetBold(true).SetColor("2E75B6")

    _, _ = doc.AddTable([][]string{
        {"Language", "Typing"},
        {"Go", "static"},
        {"Python", "dynamic"},
    })

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

What you can do

Create or open a document
doc, _ := wordingo.Create()                 // blank doc — ready to write
defer doc.Close()
doc.Save("output.docx")                      // write to file
doc.WriteTo(w)                              // or any io.Writer

doc2, _ := wordingo.Open("existing.docx")   // open and edit
doc3, _ := wordingo.OpenReader(r, size)     // from io.ReaderAt
Use a template
// Styles from template, write your own content:
doc, _ := wordingo.FromTemplate("corporate-template.docx")

// Keep the template's content and add more:
doc, _ := wordingo.OpenTemplate("letterhead.docx")

FromTemplate copies all the formatting (styles, fonts, colors, numbering) into an empty document — great when you want the look but write everything yourself. OpenTemplate keeps the original paragraphs so you can append or edit.

Write paragraphs and style text
p := doc.AddParagraph("Chapter 1").SetStyle("Heading1")
p.AddRun(" — A thrilling start.")
r := p.AddRun("Bold and blue").SetBold(true).SetColor("2E75B6")
r.ReplaceText("blue", "red")

Paragraph methods: SetAlignment, SetSpacing, SetIndent, SetPageBreakBefore. Run methods: SetBold, SetItalic, SetUnderline, SetFont, SetSize, SetColor, SetHighlight, SetStyle.

Style names

Blank documents include a full set of default styles. Available style IDs include "Title", "Subtitle", "Heading1""Heading9", "Normal", "Quote", "IntenseEmphasis", "IntenseReference", "ListParagraph", and character-style variants.

doc.AddParagraph("Welcome").SetStyle("Title")
p.AddRun("important").SetStyle("IntenseEmphasis")
Create tables
// Quick table from a spreadsheet-style grid:
doc.AddTable([][]string{{"Item", "Price"}, {"Widget", "$5"}})

// Full control:
tbl := doc.AddTableBuilder()
tbl.SetTableStyle("LightGridAccent1")
tbl.SetWidth(8000, "dxa")
tbl.Row(0).Cell(0).SetText("Product").SetBold(true)
tbl.Row(0).Cell(0).MergeRight()             // span 2 columns
if err := tbl.DeleteRow(2); err != nil { /* OOB */ }

Tables are added after all paragraphs (current behavior). Each cell supports text, bold, shading, width, and merging.

Insert images
run, _ := doc.AddImage("photo.png")          // loads from disk
run, _ := doc.AddImageBytes("gradient.png", data, "image/png")
run.SetImageWidth(3.0).SetImageHeight(2.0)    // display size in inches

PNG and JPEG both work. DPI is detected automatically when present in the file; otherwise defaults to 72 DPI with a 3-inch width.

Add headers and footers
h := doc.AddHeader(wordingo.HeaderDefault)
h.AddParagraph("Confidential")
f := doc.AddFooter(wordingo.FooterDefault)
f.AddParagraph("Page ")

Headers come in three variants: default, first-page only, and even-page. Footers have the same options. All support editing paragraphs after creation.

Bulleted and numbered lists
doc.AddListFromSlice([]string{"Red", "Green", "Blue"}, false)   // bulleted
doc.AddListFromSlice([]string{"First", "Second"}, true)         // numbered

lb := doc.AddList(true)
lb.AddItem("Item 1", 0)
lb.AddItem("Sub-item", 1).AddItem("Sub-sub", 2)                 // 9 nesting levels

doc.AddNumberingDef("upperRoman", 1)                            // custom numbering

Lists handle nesting up to 9 levels deep. Custom numbering formats (roman numerals, letters, etc.) are supported.

p := doc.AddParagraph("Visit ")
r := p.AddHyperlink("the docs", "https://go.dev")
r.SetColor("0563C1").SetUnderline("single")

Each hyperlink creates a clickable link in the Word document. The returned run accepts all the usual formatting methods.

Page layout
doc.SetOrientation(wordingo.OrientationLandscape)
doc.SetPaperSize(wordingo.PaperA4W, wordingo.PaperA4H)
doc.SetMargins(1440, 1440, 1440, 1440)          // top, right, bottom, left (in twips)
doc.AddPageBreak()

doc.Section().SetOrientation(wordingo.OrientationLandscape)     // or via Section wrapper

Available paper sizes: PaperLetter, PaperA4, PaperLegal — or set custom dimensions.

Replace placeholders (template merge)
doc.Merge(map[string]string{
    "name":  "Alice",
    "item":  "invoice",
}, nil)                                             // all sections

doc.Merge(map[string]string{"page":"2"}, &wordingo.MergeOpts{
    ScopedParts: wordingo.ScopedParts{Headers: true, Footers: true},
})

Replaces {{name}} and {{item}} wherever they appear — body text, table cells, headers, footers. Works even if placeholders get split across multiple formatting runs. Unused keys surface as warnings.

Insert, delete, and edit content
target := doc.Paragraphs()[2]
doc.InsertBefore(target, "Start here")               // insert above a paragraph
doc.InsertAfter(target,  "End here")                 // insert below
doc.DeleteParagraph(target)                          // remove a paragraph
r.SetText("replacement")
r.ReplaceText("old", "new")
tbl.DeleteRow(1)                                     // remove a table row

// Iterate mixed paragraphs and tables in document order:
for _, el := range doc.Body() {
    switch el.Type {
    case wordingo.ElementParagraph: /* el.Para */
    case wordingo.ElementTable:     /* el.Table */
    }
}
Extract text
text, _ := doc.ExtractText(nil)                       // all content, newline-separated
text, _ := doc.ExtractText(&wordingo.ExtractOpts{
    ScopedParts: wordingo.ScopedParts{Body: true},
    Separator:   " | ",
})

Extract text from the body, tables, headers, and footers — or pick specific sections. Read-only, doesn't modify the document.

Table of contents / summary

Build a table of contents straight from the document's own headings:

// Inspect the outline first, if you like:
for _, h := range doc.Headings() {
    fmt.Printf("%d. %s\n", h.Level, h.Text)   // 1. Introduction
}

// Append a TOC section at the end of the document:
toc, _ := doc.AddTableOfContents(nil)
toc.Title().SetStyle("Title")                 // restyle the heading if you want

// Or place it before a specific paragraph (e.g. right after the title):
doc.InsertTableOfContentsBefore(doc.Paragraphs()[1], &wordingo.TOCOptions{
    Title:  "Contents",
    Levels: 2,
})

The generated section is a real Word TOC field (TOC \o "1-N" \h \z \u): it collects every body paragraph styled Heading1Heading9 (or carrying an explicit outline level). Entries link to bookmarks placed on the headings, and w:updateFields is set in the document settings so Word repopulates the TOC — with live page numbers — the moment the file is opened. Viewers that don't refresh fields still see the generated summary. Set TOCOptions.UpdateOnOpen to false to leave the document settings untouched.

Convert to and from Markdown
md, _ := doc.ToMarkdown(nil)                        // .docx → GitHub-flavored Markdown

doc, _ := wordingo.CreateFromMarkdown("# Hi\n\n- a\n- b\n")   // Markdown → .docx
doc.ImportMarkdown("## Append more\n\nExtra content")         // append to existing doc

Export handles headings, bold, italic, tables, links, images, lists, and code blocks. Import handles all the same — you can round-trip content between Word and Markdown.

Warnings & low-level access
for _, w := range doc.Warnings() { fmt.Println(w) }   // non-critical issues

// Get the underlying XML struct when you need something the public API
// doesn't cover:
pkg := doc.X()              // document internals
ctP  := para.X()            // raw paragraph XML
ctR  := run.X()             // raw run XML

Warnings() flags issues like unknown style names or invalid colors — non-fatal, but useful for catching mistakes. The X() methods give you direct access to the library's internal XML structs, handy for edge cases the high-level API doesn't address.

Examples

Each example is a standalone Go program. Run it from its directory:

cd examples/01-blank-doc && go run main.go
# Example What it shows
1 01-blank-doc Minimum "Hello World" document
2 02-text-and-styles Paragraphs, headings, inline formatting
3 03-tables Tables — quick grid and builder
4 04-images Embedded PNG images
5 05-headers-footers Headers, footers, A4, landscape
6 06-lists Bulleted, ordered, nested lists
7 07-hyperlinks Clickable links
8 08-comprehensive All features in one document
9 09-merge-and-edit Placeholder merge, insert/delete, edit
10 10-template-to-document Using templates
11 11-text-extraction-markdown Text extraction, markdown round-trip
12 12-table-of-contents Table of contents from the document's headings

Design principles

  • Zero dependencies. Only the Go standard library. go.mod has no require lines.
  • Faithful to the spec. Built on the ISO OOXML standard. Everything you don't explicitly touch stays as-is — opening and saving a document changes nothing you didn't ask for.
  • Fidelity first. Templates are copied byte-for-byte, never re-encoded. Your template's styles, fonts, and colors come through exactly as designed.
  • Opens clean in Word. The test is simple: does the output open in Microsoft Word without a repair prompt?
  • Escape hatch when you need it. If the public API doesn't expose some XML attribute, X() gives you direct access. No need to wait for a wrapper.

Installation

go get github.com/fabiomarini/wordingo

Requires Go 1.23+.

Status

v0.1.1 covers: create/open/save, templates, paragraphs and runs, named styles, formatting, tables, images, headers/footers, lists (Word-canonical numbering), hyperlinks, page setup, template merge, edit operations, table of contents from the document's headings, text extraction, and Markdown round-trip.

What's new in v0.1.1:

  • Table of contentsHeadings(), AddTableOfContents(), InsertTableOfContentsBefore() generate a live Word TOC field with navigable entries from the document's own headings
  • Word-faithful lists — numbering definitions now match Word's own output (schema-ordered levels, hybridMultilevel, nsid/tmpl), so bullets and numbers render reliably
  • Deterministic output — re-encoded XML parts are byte-reproducible
  • File lifecycle fixesOpen(path) keeps the source file for lazy part copies until Close(); saving over the open source file is rejected
  • Round-trip fidelity — paragraph-mark run properties and extension namespaces (mc:Ignorable) survive re-encoding

See RELEASE-v0.1.1.md for the full changelog.

License

MIT, copyright 2026 Fabio Marini. See LICENSE.

Contributing

PRs welcome. For larger changes, open an issue first. No external dependencies allowed — stdlib only. Run go test ./... before submitting.

Documentation

Overview

Package wordingo creates and edits WordprocessingML (.docx) documents. It is a pure Go, zero-dependency library built on github.com/fabiomarini/wordingo/internal/opc and internal/{wml,xmlutil}.

Create a blank document:

doc, err := wordingo.Create()
if err != nil { ... }
defer doc.Close()
err = doc.Save("output.docx")

Open an existing document:

doc, err := wordingo.Open("existing.docx")
if err != nil { ... }
defer doc.Close()
for _, p := range doc.Paragraphs() { ... }
err = doc.Save("roundtrip.docx")

Index

Constants

View Source
const (
	PaperLetterW int64 = 12240
	PaperLetterH int64 = 15840
	PaperA4W     int64 = 11906
	PaperA4H     int64 = 16838
	PaperLegalW  int64 = 12240
	PaperLegalH  int64 = 20160
)

Paper size constants in twips.

Variables

View Source
var ErrTOCTargetNotFound = errors.New("wordingo: InsertTableOfContentsBefore: target paragraph not found")

ErrTOCTargetNotFound is returned by InsertTableOfContentsBefore when the target paragraph is not part of the document body.

Functions

This section is empty.

Types

type Alignment

type Alignment int
const (
	AlignmentLeft Alignment = iota
	AlignmentCenter
	AlignmentRight
	AlignmentBoth
)

func (Alignment) String

func (a Alignment) String() string

type BodyElement

type BodyElement struct {
	Type  BodyElementType
	Para  *Paragraph
	Table *TableBuilder
}

type BodyElementType

type BodyElementType int
const (
	ElementParagraph BodyElementType = iota
	ElementTable
)

type BodyParagraph

type BodyParagraph struct {
	P *Paragraph
}

func (BodyParagraph) X

func (bp BodyParagraph) X() *wml.CT_P

type BodyTable

type BodyTable struct {
	T *TableBuilder
}

func (BodyTable) X

func (bt BodyTable) X() *wml.CT_Tbl

type BorderDef

type BorderDef struct {
	Style string
	Size  int64
	Color string
}

BorderDef defines a single border style for tables.

type CellBuilder

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

CellBuilder provides a fluent API for building table cells.

func (*CellBuilder) MergeDown

func (cb *CellBuilder) MergeDown() *CellBuilder

MergeDown sets VMerge to "restart" on this cell (start of vertical merge).

func (*CellBuilder) MergeRight

func (cb *CellBuilder) MergeRight() *CellBuilder

MergeRight sets GridSpan to merge this cell with the cells to the right.

func (*CellBuilder) SetBold

func (cb *CellBuilder) SetBold(b bool) *CellBuilder

SetBold sets bold on the first run of the first paragraph.

func (*CellBuilder) SetShading

func (cb *CellBuilder) SetShading(val, fill string) *CellBuilder

SetShading sets cell-level shading (D-02 per-cell).

func (*CellBuilder) SetText

func (cb *CellBuilder) SetText(text string) *CellBuilder

SetText sets the text content of the first paragraph in the cell.

func (*CellBuilder) SetWidth

func (cb *CellBuilder) SetWidth(w int64, wType string) *CellBuilder

SetWidth sets the cell width.

func (*CellBuilder) X

func (cb *CellBuilder) X() *wml.CT_Tc

X returns the underlying CT_Tc for escape-hatch access.

type Document

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

Document wraps an OPC package during construction. Use Create to create a blank document, Open or OpenReader to open an existing document, then Save or WriteTo to persist. Close releases internal references.

func Create

func Create() (*Document, error)

Create returns a new blank document with default styles (Normal, Heading 1–9, Title), theme, font table, settings, and one section page sized Letter (12240×15840 twips) with 1-inch margins.

func CreateFromMarkdown

func CreateFromMarkdown(input string) (*Document, error)

func FromTemplate

func FromTemplate(path string) (*Document, error)

FromTemplate opens a .docx template from path, clones its style dependency graph (styles, numbering, fontTable, theme, settings), and returns a Document with an empty body (one section, no paragraphs). Style parts are never touched after CloneStyles (D-06). Use when you want template styles but a clean body.

func FromTemplateReader

func FromTemplateReader(r io.ReaderAt, size int64) (*Document, error)

FromTemplateReader is the io.ReaderAt variant of FromTemplate.

func Open

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

Open reads an existing .docx file from path and returns a Document with the body parsed eagerly. Supporting parts remain lazy.

The source file stays open until Document.Close (Save copies unmodified parts lazily from the original archive), so call Close when the document is no longer needed.

func OpenReader

func OpenReader(r io.ReaderAt, size int64) (*Document, error)

OpenReader reads a .docx from r with the given size and returns a Document with the body parsed eagerly. Supporting parts remain lazy.

func OpenTemplate

func OpenTemplate(path string) (*Document, error)

OpenTemplate opens a .docx template from path, clones its style dependency graph, and returns a Document with the template's existing body content preserved (paragraphs and tables). Header and footer references in sectPr are stripped (Pitfall 4 — cloned package has fresh rIds that would dangle). Headers/footers themselves are not cloned in Phase 3 (deferred to Phase 5).

func OpenTemplateReader

func OpenTemplateReader(r io.ReaderAt, size int64) (*Document, error)

OpenTemplateReader is the io.ReaderAt variant of OpenTemplate.

func (*Document) AddFooter

func (d *Document) AddFooter(variant FooterVariant) *Footer

AddFooter creates a footer part with the given variant (default, first, or even), registers it in the OPC package, links it to the section properties via a footerReference element, and returns the Footer.

func (*Document) AddHeader

func (d *Document) AddHeader(variant HeaderVariant) *Header

AddHeader creates a header part with the given variant (default, first, or even), registers it in the OPC package, links it to the section properties via a headerReference element, and returns the Header.

func (*Document) AddImage

func (d *Document) AddImage(path string) (*Run, error)

AddImage reads an image file from path, embeds it as a DrawingML inline image, and returns the run containing the drawing. The image is added to the last paragraph in the document.

func (*Document) AddImageBytes

func (d *Document) AddImageBytes(name string, data []byte, ct string) (*Run, error)

AddImageBytes embeds image data as a DrawingML inline image and returns the run containing the drawing. The image is added to the last paragraph in the document.

name is used as a display name (not a file path). data is the raw image bytes. ct is the MIME content type (e.g. "image/png").

The image is stored as a media part in word/media/imageN.ext with the appropriate relationship and content type override.

func (*Document) AddList

func (d *Document) AddList(ordered bool) *ListBuilder

AddList creates a new ordered or bulleted list with auto-generated numbering definitions and returns a *ListBuilder for adding items. Ordered lists use numFmt=decimal with "%N." level text; bulleted lists use numFmt=bullet. Full 9-level depth is configured on the abstract numbering definition (levels 0-8).

Numbering definitions are merged with any existing numbering.xml content from the package (template numbering is preserved). Auto-generated abstractNumId and numId values are computed by scanning all existing entries to avoid collisions (Pitfall 3).

func (*Document) AddListFromSlice

func (d *Document) AddListFromSlice(items []string, ordered bool) *ListBuilder

AddListFromSlice creates an ordered or bulleted list from a string slice. Each string becomes a level-0 list item. Returns the ListBuilder for further customization.

func (*Document) AddNumberingDef

func (d *Document) AddNumberingDef(numFmt string, start int) *ListBuilder

AddNumberingDef creates a custom numbering definition with the given numFmt and start value applied to all 9 levels. Returns a ListBuilder linked to the new definition. Level text uses "%N." template for each level N+1.

Example: doc.AddNumberingDef("upperRoman", 1) creates Roman-numeral numbering across all 9 levels.

func (*Document) AddPageBreak

func (d *Document) AddPageBreak() *Paragraph

AddPageBreak creates a new empty paragraph with PageBreakBefore set and appends it to the body. This forces the following content onto a new page. Returns the paragraph for further formatting.

func (*Document) AddParagraph

func (d *Document) AddParagraph(text string) *Paragraph

AddParagraph appends a paragraph with optional text and returns it.

func (*Document) AddTable

func (d *Document) AddTable(data [][]string) (*TableBuilder, error)

AddTable creates a simple grid table from string data and appends it to the document. Returns the TableBuilder for further customization. Tables are appended after all paragraphs (v1 limitation per D-24).

func (*Document) AddTableBuilder

func (d *Document) AddTableBuilder() *TableBuilder

AddTableBuilder returns a TableBuilder for building a complex table. The table is appended to the document body. Tables are appended after all paragraphs (v1 limitation per D-24).

func (*Document) AddTableOfContents added in v0.1.1

func (d *Document) AddTableOfContents(opts *TOCOptions) (*TOC, error)

AddTableOfContents appends a table of contents section at the end of the document body. The section consists of a title paragraph carrying a TOC field (` TOC \o "1-N" \h \z \u `) followed by one entry paragraph per body heading up to the configured depth (see TOCOptions). Each entry links to a bookmark placed on its heading, so the generated summary is navigable even before Word refreshes the field.

Unless TOCOptions.UpdateOnOpen is explicitly false, word/settings.xml is patched with w:updateFields so Word repopulates the TOC — with live page numbers — when the document is opened.

func (*Document) Body

func (d *Document) Body() []BodyElement

func (*Document) Close

func (d *Document) Close() error

Close releases package, document, and source-file references. The Document is not usable after Close.

func (*Document) DeleteParagraph

func (d *Document) DeleteParagraph(target *Paragraph)

DeleteParagraph removes target paragraph (identified by pointer identity) from the document body. If target is not found, warns and returns.

func (*Document) ExtractText

func (d *Document) ExtractText(opts *ExtractOpts) (string, error)

func (*Document) Headings added in v0.1.1

func (d *Document) Headings() []Heading

Headings returns the document outline: body paragraphs whose style is Heading1..Heading9, or that carry an explicit outline level. Headings are returned in document order with their level (1..9) and trimmed text. Paragraphs with no heading style or outline level, and headings with no text content, are skipped.

func (*Document) ImportMarkdown

func (d *Document) ImportMarkdown(input string)

func (*Document) InsertAfter

func (d *Document) InsertAfter(target *Paragraph, text string) *Paragraph

InsertAfter inserts a new paragraph with the given text after target (identified by pointer identity). Returns the new paragraph, or nil if target is not found in body paragraphs.

func (*Document) InsertBefore

func (d *Document) InsertBefore(target *Paragraph, text string) *Paragraph

InsertBefore inserts a new paragraph with the given text before target (identified by pointer identity). Returns the new paragraph, or nil if target is not found in body paragraphs.

func (*Document) InsertTableOfContentsBefore added in v0.1.1

func (d *Document) InsertTableOfContentsBefore(target *Paragraph, opts *TOCOptions) (*TOC, error)

InsertTableOfContentsBefore inserts a table of contents section (see AddTableOfContents) immediately before target. Returns ErrTOCTargetNotFound — after emitting a warning — if target is nil or not part of the document body.

func (*Document) Merge

func (d *Document) Merge(data map[string]string, opts *MergeOpts)

func (*Document) Paragraphs

func (d *Document) Paragraphs() []*Paragraph

Paragraphs returns the document's body paragraphs as read-only wrappers over *wml.CT_P. Returns an empty slice if the document body is nil.

func (*Document) Save

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

Save writes the document to a file at path.

func (*Document) SaveFile

func (d *Document) SaveFile(path string) error

SaveFile writes the document to a file at path.

func (*Document) Section

func (d *Document) Section() *Section

Section returns the Section wrapper over the document's section properties. The section is lazily initialised if nil.

func (*Document) SetMargins

func (d *Document) SetMargins(top, right, bottom, left int64) *Document

SetMargins sets the page margins on the document's section (top, right, bottom, left twips) and returns the Document for method chaining.

func (*Document) SetOrientation

func (d *Document) SetOrientation(o PageOrientation) *Document

SetOrientation sets the page orientation on the document's section and returns the Document for method chaining.

func (*Document) SetPaperSize

func (d *Document) SetPaperSize(w, h int64) *Document

SetPaperSize sets the page dimensions on the document's section and returns the Document for method chaining.

func (*Document) Tables

func (d *Document) Tables() []*TableBuilder

Tables returns the document's body tables.

func (*Document) ToMarkdown

func (d *Document) ToMarkdown(opts *ExtractOpts) (string, error)

func (*Document) Warnings

func (d *Document) Warnings() []string

Warnings returns non-fatal issues from the package layer and document-level formatting validation.

func (*Document) WriteTo

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

WriteTo writes the document to w. Returns bytes written.

func (*Document) X

func (d *Document) X() *opc.Package

X returns the underlying OPC package for escape-hatch access to internals (content types, relationships, individual parts).

type ExtractOpts

type ExtractOpts struct {
	ScopedParts ScopedParts
	Separator   string
}
type Footer struct {
	// contains filtered or unexported fields
}

Footer wraps a WordprocessingML footer part (w:ftr).

func (*Footer) AddParagraph

func (f *Footer) AddParagraph(text string) *Paragraph

AddParagraph appends a paragraph with optional text to the footer and returns it. The paragraph is added as a child of the footer element (w:ftr/w:p).

func (*Footer) DeleteParagraphAt

func (f *Footer) DeleteParagraphAt(idx int)

func (*Footer) InsertParagraphAt

func (f *Footer) InsertParagraphAt(idx int, ct *wml.CT_P) *Paragraph

func (*Footer) Paragraphs

func (f *Footer) Paragraphs() []*Paragraph

func (*Footer) X

func (f *Footer) X() *wml.CT_Ftr

X returns the underlying CT_Ftr for escape-hatch access.

type FooterVariant

type FooterVariant int

FooterVariant specifies the footer type for a section.

const (
	FooterDefault FooterVariant = iota
	FooterFirst
	FooterEven
)

func (FooterVariant) String

func (v FooterVariant) String() string
type Header struct {
	// contains filtered or unexported fields
}

Header wraps a WordprocessingML header part (w:hdr).

func (*Header) AddParagraph

func (h *Header) AddParagraph(text string) *Paragraph

AddParagraph appends a paragraph with optional text to the header and returns it. The paragraph is added as a child of the header element (w:hdr/w:p).

func (*Header) DeleteParagraphAt

func (h *Header) DeleteParagraphAt(idx int)

func (*Header) InsertParagraphAt

func (h *Header) InsertParagraphAt(idx int, ct *wml.CT_P) *Paragraph

func (*Header) Paragraphs

func (h *Header) Paragraphs() []*Paragraph

func (*Header) X

func (h *Header) X() *wml.CT_Hdr

X returns the underlying CT_Hdr for escape-hatch access.

type HeaderVariant

type HeaderVariant int

HeaderVariant specifies the header type for a section.

const (
	HeaderDefault HeaderVariant = iota
	HeaderFirst
	HeaderEven
)

func (HeaderVariant) String

func (v HeaderVariant) String() string

type Heading added in v0.1.1

type Heading struct {
	// Level is the heading depth, 1 (Heading1) through 9 (Heading9).
	Level int
	// Text is the trimmed text content of the heading paragraph.
	Text string
	// Style is the paragraph style id (e.g. "Heading1"), or "" when the
	// heading was derived from an explicit outline level.
	Style string
}

Heading describes one heading paragraph of the document outline.

type ListBuilder

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

ListBuilder provides a fluent API for building ordered and bulleted lists.

func (*ListBuilder) AddItem

func (lb *ListBuilder) AddItem(text string, level int) *ListBuilder

AddItem appends a list item at the given nesting level and returns the ListBuilder for chaining. level must be in range 0-8 (full 9-level depth per D-17). The paragraph is linked to the list's numbering definition via NumPr (numId + ilvl).

func (*ListBuilder) X

func (lb *ListBuilder) X() *wml.CT_P

X returns the last paragraph added via AddItem for escape-hatch access.

type MergeOpts

type MergeOpts struct {
	ScopedParts ScopedParts
}

type PageOrientation

type PageOrientation int

PageOrientation specifies page orientation.

const (
	OrientationPortrait PageOrientation = iota
	OrientationLandscape
)

type ParFormat

type ParFormat struct {
	Alignment *Alignment
	Spacing   *ParSpacing
	Indent    *ParIndent
}

type ParIndent

type ParIndent struct {
	Left      int64
	Right     int64
	FirstLine int64
	Hanging   int64
}

type ParSpacing

type ParSpacing struct {
	Before   int64
	After    int64
	Line     int64
	LineRule string
}

type Paragraph

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

Paragraph wraps a WordprocessingML paragraph (w:p).

func (p *Paragraph) AddHyperlink(text, uri string) *Run

AddHyperlink creates a hyperlink on the paragraph with the given display text and target URI. A new relationship is created in word/_rels/document.xml.rels with TargetMode="External" (Pitfall 7). Each call allocates a fresh rId via NextRID() — duplicate URIs are not deduplicated (D-23 agent discretion; each extra rId ~50 bytes).

Returns a *Run that supports chaining formatting methods (SetBold, SetColor, etc.).

para.AddHyperlink("click here", "https://example.com").SetBold(true).SetColor("0563C1")

func (*Paragraph) AddRun

func (p *Paragraph) AddRun(text string) *Run

AddRun appends a run with text to the paragraph and returns it.

func (*Paragraph) SetAlignment

func (p *Paragraph) SetAlignment(a Alignment) *Paragraph

SetAlignment sets paragraph alignment.

func (*Paragraph) SetFormatting

func (p *Paragraph) SetFormatting(f ParFormat) *Paragraph

SetFormatting sets multiple paragraph formatting properties.

func (*Paragraph) SetIndent

func (p *Paragraph) SetIndent(i *ParIndent) *Paragraph

SetIndent sets paragraph indentation.

func (*Paragraph) SetPageBreakBefore

func (p *Paragraph) SetPageBreakBefore(b bool) *Paragraph

SetPageBreakBefore sets or clears the page-break-before property on the paragraph. When enabled, the paragraph always starts on a new page.

func (*Paragraph) SetSpacing

func (p *Paragraph) SetSpacing(s *ParSpacing) *Paragraph

SetSpacing sets paragraph spacing.

func (*Paragraph) SetStyle

func (p *Paragraph) SetStyle(name string) *Paragraph

SetStyle sets the paragraph style reference. Empty string clears the style reference.

func (*Paragraph) Style

func (p *Paragraph) Style() string

Style returns the paragraph style ID, or "" if none.

func (*Paragraph) Text

func (p *Paragraph) Text() string

Text returns all text content concatenated across runs.

func (*Paragraph) X

func (p *Paragraph) X() *wml.CT_P

X returns the underlying CT_P for escape-hatch access.

type ParagraphContainer

type ParagraphContainer interface {
	Paragraphs() []*Paragraph
	InsertParagraphAt(idx int, ct *wml.CT_P) *Paragraph
	DeleteParagraphAt(idx int)
}

ParagraphContainer is the interface for editing paragraphs in a container that owns a paragraph slice (body, header, or footer).

type RowBuilder

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

RowBuilder provides a fluent API for building table rows.

func (*RowBuilder) Cell

func (rb *RowBuilder) Cell(idx int) *CellBuilder

Cell returns the CellBuilder for the cell at index idx. Grows the cell slice if idx is beyond current length.

func (*RowBuilder) SetBorders

func (rb *RowBuilder) SetBorders(b *TableBorders) *RowBuilder

SetBorders sets borders on every cell in this row.

func (*RowBuilder) X

func (rb *RowBuilder) X() *wml.CT_Tr

X returns the underlying CT_Tr for escape-hatch access.

type Run

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

func (*Run) ReplaceText

func (r *Run) ReplaceText(old, new string) *Run

func (*Run) SetBold

func (r *Run) SetBold(b bool) *Run

func (*Run) SetColor

func (r *Run) SetColor(hex string) *Run

func (*Run) SetFont

func (r *Run) SetFont(name string) *Run

func (*Run) SetFormatting

func (r *Run) SetFormatting(f RunFormat) *Run

func (*Run) SetHighlight

func (r *Run) SetHighlight(color string) *Run

func (*Run) SetImageHeight

func (r *Run) SetImageHeight(inches float64) *Run

SetImageHeight sets the image display height in inches. Mutates the DrawingML inline extent on the run.

func (*Run) SetImageWidth

func (r *Run) SetImageWidth(inches float64) *Run

SetImageWidth sets the image display width in inches. Mutates the DrawingML inline extent on the run.

func (*Run) SetItalic

func (r *Run) SetItalic(b bool) *Run

func (*Run) SetSize

func (r *Run) SetSize(pts float64) *Run

func (*Run) SetStyle

func (r *Run) SetStyle(name string) *Run

func (*Run) SetText

func (r *Run) SetText(s string) *Run

func (*Run) SetUnderline

func (r *Run) SetUnderline(u string) *Run

func (*Run) X

func (r *Run) X() *wml.CT_R

type RunFormat

type RunFormat struct {
	Bold      *bool
	Italic    *bool
	Underline *string
	Font      *string
	Size      *float64
	Color     *string
	Highlight *string
}

type ScopedParts

type ScopedParts struct {
	Body    bool
	Tables  bool
	Headers bool
	Footers bool
}

type Section

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

Section wraps a section properties block (w:sectPr). In v1 the document has a single section; the Section type provides a forward- compatible API for multi-section support in a future version.

func (*Section) SetMargins

func (s *Section) SetMargins(top, right, bottom, left int64)

SetMargins sets the page margins in twips (top, right, bottom, left). (1 inch = 1440 twips; 1 cm ≈ 567 twips).

func (*Section) SetOrientation

func (s *Section) SetOrientation(o PageOrientation)

SetOrientation sets the page orientation. Landscape swaps W and H on the current PgSz; Portrait restores the W < H default. The underlying OOXML stores orientation via the W/H ratio rather than a separate attribute (T-05-07 — accepted behavior).

func (*Section) SetPaperSize

func (s *Section) SetPaperSize(w, h int64)

SetPaperSize sets the page dimensions in twips. Convenience constants PaperLetterW/H, PaperA4W/H, and PaperLegalW/H are available.

func (*Section) X

func (s *Section) X() *wml.CT_SectPr

X returns the underlying CT_SectPr for escape-hatch access.

type TOC added in v0.1.1

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

TOC is a handle to a generated table of contents section, returned by AddTableOfContents and InsertTableOfContentsBefore.

func (*TOC) Title added in v0.1.1

func (t *TOC) Title() *Paragraph

Title returns the TOC title paragraph (the field's first paragraph).

type TOCOptions added in v0.1.1

type TOCOptions struct {
	// Title is the heading shown above the TOC. Empty means the
	// default "Table of Contents".
	Title string
	// Levels is the deepest heading level included (1..9). Values
	// outside the range are clamped. Zero means 3.
	Levels int
	// UpdateOnOpen asks Word to refresh all fields — including the
	// TOC — when the document is opened (w:updateFields in
	// word/settings.xml). nil means true; set to false to leave the
	// document settings untouched.
	UpdateOnOpen *bool
}

TOCOptions configures the table of contents generated by AddTableOfContents / InsertTableOfContentsBefore. A nil *TOCOptions is equivalent to all defaults.

type TableBorders

type TableBorders struct {
	Top     *BorderDef
	Bottom  *BorderDef
	Left    *BorderDef
	Right   *BorderDef
	InsideH *BorderDef
	InsideV *BorderDef
}

TableBorders holds table border definitions for use with TableBuilder.

type TableBuilder

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

TableBuilder provides a fluent API for building complex tables.

func (*TableBuilder) DeleteRow

func (tb *TableBuilder) DeleteRow(idx int) error

DeleteRow removes the row at the given index. Returns an error if the index is out of range.

func (*TableBuilder) Row

func (tb *TableBuilder) Row(idx int) *RowBuilder

Row returns the RowBuilder for the row at index idx. Grows the row slice if idx is beyond current length.

func (*TableBuilder) SetBorders

func (tb *TableBuilder) SetBorders(b *TableBorders) *TableBuilder

SetBorders sets table-level borders.

func (*TableBuilder) SetShading

func (tb *TableBuilder) SetShading(val, fill string) *TableBuilder

SetShading sets table-level shading.

func (*TableBuilder) SetTableStyle

func (tb *TableBuilder) SetTableStyle(name string) *TableBuilder

SetTableStyle sets the table style by name (D-03).

func (*TableBuilder) SetWidth

func (tb *TableBuilder) SetWidth(w int64, wType string) *TableBuilder

SetWidth sets the table width (D-04). wType is "dxa", "pct", or "auto".

func (*TableBuilder) X

func (tb *TableBuilder) X() *wml.CT_Tbl

X returns the underlying CT_Tbl for escape-hatch access.

Directories

Path Synopsis
examples
01-blank-doc command
03-tables command
04-images command
06-lists command
07-hyperlinks command
internal
opc
Package opc reads and writes Open Packaging Convention (OPC) packages — the ZIP container layer of .docx files.
Package opc reads and writes Open Packaging Convention (OPC) packages — the ZIP container layer of .docx files.
style
Package style resolves effective paragraph and run properties through the OOXML style inheritance chain, and clones the style dependency graph from a source package into a fresh-empty target.
Package style resolves effective paragraph and run properties through the OOXML style inheritance chain, and clones the style dependency graph from a source package into a fresh-empty target.
wml
Package wml implements the ~60 essential WordprocessingML struct types (CT_*) from ISO/IEC 29500 Part 1, with URI-based struct tags, whitespace-fidelity CT_Text, and RawXML hoarding for unknown children (WML-01..04).
Package wml implements the ~60 essential WordprocessingML struct types (CT_*) from ISO/IEC 29500 Part 1, with URI-based struct tags, whitespace-fidelity CT_Text, and RawXML hoarding for unknown children (WML-01..04).
xmlutil
Package xmlutil extends encoding/xml with OOXML namespace handling: URI↔prefix registry, safe decoder, RawXML token capture, and canonical-prefix encoder.
Package xmlutil extends encoding/xml with OOXML namespace handling: URI↔prefix registry, safe decoder, RawXML token capture, and canonical-prefix encoder.

Jump to

Keyboard shortcuts

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