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
- type Alignment
- type BodyElement
- type BodyElementType
- type BodyParagraph
- type BodyTable
- type BorderDef
- type CellBuilder
- func (cb *CellBuilder) MergeDown() *CellBuilder
- func (cb *CellBuilder) MergeRight() *CellBuilder
- func (cb *CellBuilder) SetBold(b bool) *CellBuilder
- func (cb *CellBuilder) SetShading(val, fill string) *CellBuilder
- func (cb *CellBuilder) SetText(text string) *CellBuilder
- func (cb *CellBuilder) SetWidth(w int64, wType string) *CellBuilder
- func (cb *CellBuilder) X() *wml.CT_Tc
- type Document
- func Create() (*Document, error)
- func CreateFromMarkdown(input string) (*Document, error)
- func FromTemplate(path string) (*Document, error)
- func FromTemplateReader(r io.ReaderAt, size int64) (*Document, error)
- func Open(path string) (*Document, error)
- func OpenReader(r io.ReaderAt, size int64) (*Document, error)
- func OpenTemplate(path string) (*Document, error)
- func OpenTemplateReader(r io.ReaderAt, size int64) (*Document, error)
- func (d *Document) AddFooter(variant FooterVariant) *Footer
- func (d *Document) AddHeader(variant HeaderVariant) *Header
- func (d *Document) AddImage(path string) (*Run, error)
- func (d *Document) AddImageBytes(name string, data []byte, ct string) (*Run, error)
- func (d *Document) AddList(ordered bool) *ListBuilder
- func (d *Document) AddListFromSlice(items []string, ordered bool) *ListBuilder
- func (d *Document) AddNumberingDef(numFmt string, start int) *ListBuilder
- func (d *Document) AddPageBreak() *Paragraph
- func (d *Document) AddParagraph(text string) *Paragraph
- func (d *Document) AddTable(data [][]string) (*TableBuilder, error)
- func (d *Document) AddTableBuilder() *TableBuilder
- func (d *Document) Body() []BodyElement
- func (d *Document) Close() error
- func (d *Document) DeleteParagraph(target *Paragraph)
- func (d *Document) ExtractText(opts *ExtractOpts) (string, error)
- func (d *Document) ImportMarkdown(input string)
- func (d *Document) InsertAfter(target *Paragraph, text string) *Paragraph
- func (d *Document) InsertBefore(target *Paragraph, text string) *Paragraph
- func (d *Document) Merge(data map[string]string, opts *MergeOpts)
- func (d *Document) Paragraphs() []*Paragraph
- func (d *Document) Save(path string) error
- func (d *Document) SaveFile(path string) error
- func (d *Document) Section() *Section
- func (d *Document) SetMargins(top, right, bottom, left int64) *Document
- func (d *Document) SetOrientation(o PageOrientation) *Document
- func (d *Document) SetPaperSize(w, h int64) *Document
- func (d *Document) Tables() []*TableBuilder
- func (d *Document) ToMarkdown(opts *ExtractOpts) (string, error)
- func (d *Document) Warnings() []string
- func (d *Document) WriteTo(w io.Writer) (int64, error)
- func (d *Document) X() *opc.Package
- type ExtractOpts
- type Footer
- type FooterVariant
- type Header
- type HeaderVariant
- type ListBuilder
- type MergeOpts
- type PageOrientation
- type ParFormat
- type ParIndent
- type ParSpacing
- type Paragraph
- func (p *Paragraph) AddHyperlink(text, uri string) *Run
- func (p *Paragraph) AddRun(text string) *Run
- func (p *Paragraph) SetAlignment(a Alignment) *Paragraph
- func (p *Paragraph) SetFormatting(f ParFormat) *Paragraph
- func (p *Paragraph) SetIndent(i *ParIndent) *Paragraph
- func (p *Paragraph) SetPageBreakBefore(b bool) *Paragraph
- func (p *Paragraph) SetSpacing(s *ParSpacing) *Paragraph
- func (p *Paragraph) SetStyle(name string) *Paragraph
- func (p *Paragraph) Style() string
- func (p *Paragraph) Text() string
- func (p *Paragraph) X() *wml.CT_P
- type ParagraphContainer
- type RowBuilder
- type Run
- func (r *Run) ReplaceText(old, new string) *Run
- func (r *Run) SetBold(b bool) *Run
- func (r *Run) SetColor(hex string) *Run
- func (r *Run) SetFont(name string) *Run
- func (r *Run) SetFormatting(f RunFormat) *Run
- func (r *Run) SetHighlight(color string) *Run
- func (r *Run) SetImageHeight(inches float64) *Run
- func (r *Run) SetImageWidth(inches float64) *Run
- func (r *Run) SetItalic(b bool) *Run
- func (r *Run) SetSize(pts float64) *Run
- func (r *Run) SetStyle(name string) *Run
- func (r *Run) SetText(s string) *Run
- func (r *Run) SetUnderline(u string) *Run
- func (r *Run) X() *wml.CT_R
- type RunFormat
- type ScopedParts
- type Section
- type TableBorders
- type TableBuilder
- func (tb *TableBuilder) DeleteRow(idx int) error
- func (tb *TableBuilder) Row(idx int) *RowBuilder
- func (tb *TableBuilder) SetBorders(b *TableBorders) *TableBuilder
- func (tb *TableBuilder) SetShading(val, fill string) *TableBuilder
- func (tb *TableBuilder) SetTableStyle(name string) *TableBuilder
- func (tb *TableBuilder) SetWidth(w int64, wType string) *TableBuilder
- func (tb *TableBuilder) X() *wml.CT_Tbl
Constants ¶
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 ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
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
}
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 ¶
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 FromTemplate ¶
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 ¶
FromTemplateReader is the io.ReaderAt variant of FromTemplate.
func Open ¶
Open reads an existing .docx file from path and returns a Document with the body parsed eagerly. Supporting parts remain lazy.
func OpenReader ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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) Body ¶
func (d *Document) Body() []BodyElement
func (*Document) Close ¶
Close releases package and document references. The Document is not usable after Close.
func (*Document) DeleteParagraph ¶
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) ImportMarkdown ¶
func (*Document) InsertAfter ¶
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 ¶
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) Paragraphs ¶
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) Section ¶
Section returns the Section wrapper over the document's section properties. The section is lazily initialised if nil.
func (*Document) SetMargins ¶
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 ¶
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 ¶
Warnings returns non-fatal issues from the package layer and document-level formatting validation.
type ExtractOpts ¶
type ExtractOpts struct {
ScopedParts ScopedParts
Separator string
}
type Footer ¶
type Footer struct {
// contains filtered or unexported fields
}
Footer wraps a WordprocessingML footer part (w:ftr).
func (*Footer) AddParagraph ¶
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 (*Footer) InsertParagraphAt ¶
func (*Footer) Paragraphs ¶
type FooterVariant ¶
type FooterVariant int
FooterVariant specifies the footer type for a section.
const ( )
func (FooterVariant) String ¶
func (v FooterVariant) String() string
type Header ¶
type Header struct {
// contains filtered or unexported fields
}
Header wraps a WordprocessingML header part (w:hdr).
func (*Header) AddParagraph ¶
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 (*Header) InsertParagraphAt ¶
func (*Header) Paragraphs ¶
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 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 Paragraph ¶
type Paragraph struct {
// contains filtered or unexported fields
}
Paragraph wraps a WordprocessingML paragraph (w:p).
func (*Paragraph) AddHyperlink ¶
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) SetAlignment ¶
SetAlignment sets paragraph alignment.
func (*Paragraph) SetFormatting ¶
SetFormatting sets multiple paragraph formatting properties.
func (*Paragraph) SetPageBreakBefore ¶
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 ¶
SetStyle sets the paragraph style reference. Empty string clears the style reference.
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 (*Run) SetFormatting ¶
func (*Run) SetHighlight ¶
func (*Run) SetImageHeight ¶
SetImageHeight sets the image display height in inches. Mutates the DrawingML inline extent on the run.
func (*Run) SetImageWidth ¶
SetImageWidth sets the image display width in inches. Mutates the DrawingML inline extent on the run.
func (*Run) SetUnderline ¶
type ScopedParts ¶
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 ¶
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 ¶
SetPaperSize sets the page dimensions in twips. Convenience constants PaperLetterW/H, PaperA4W/H, and PaperLegalW/H are available.
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.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
01-blank-doc
command
|
|
|
02-text-and-styles
command
|
|
|
03-tables
command
|
|
|
04-images
command
|
|
|
05-headers-footers
command
|
|
|
06-lists
command
|
|
|
07-hyperlinks
command
|
|
|
08-comprehensive
command
|
|
|
09-merge-and-edit
command
|
|
|
10-template-to-document
command
|
|
|
11-text-extraction-markdown
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. |
