Documentation
¶
Overview ¶
Package docx provides functionality for reading and writing Word documents.
A Document is not safe for concurrent use. A single Document, and the paragraphs, runs, and tables reached through it, must be confined to one goroutine, or all access must be guarded by external synchronization. In particular Save, SaveBytes, and SaveTo mutate shared state while serializing, so they must not run concurrently with each other or with any mutation of the same Document. Distinct Document values may be used from different goroutines.
Example (Comments) ¶
Example_comments shows the review flow: add a paragraph, comment on it, reply to the comment, resolve the thread, serialize, then reopen from memory and read the author and resolved state back.
package main
import (
"bytes"
"fmt"
"github.com/mgilbir/spine/docx"
)
func main() {
doc := docx.Create()
p := doc.AddParagraphWithText("The quick brown fox.")
c := p.AddComment("Reviewer", "Please rephrase.")
reply := c.Reply("Author", "Done.")
reply.Resolve()
data, err := doc.SaveBytes()
if err != nil {
panic(err)
}
reopened, err := docx.OpenReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
panic(err)
}
defer func() { _ = reopened.Close() }()
for _, got := range reopened.Comments() {
fmt.Printf("%s: %q resolved=%v\n", got.Author(), got.Text(), got.Resolved())
for _, r := range got.Replies() {
fmt.Printf(" reply %s: %q resolved=%v\n", r.Author(), r.Text(), r.Resolved())
}
}
}
Output: Reviewer: "Please rephrase." resolved=true reply Author: "Done." resolved=true
Index ¶
- Constants
- Variables
- func PageSizeA4() (float64, float64)
- func PageSizeLegal() (float64, float64)
- func PageSizeLetter() (float64, float64)
- type ActiveXControl
- type Alignment
- type Anchor
- type Bookmark
- type Border
- type BuildingBlock
- type BuildingBlockDef
- type CellBorders
- type Column
- type Columns
- type Comment
- func (c *Comment) AnchorText() string
- func (c *Comment) Author() string
- func (c *Comment) Date() time.Time
- func (c *Comment) ID() string
- func (c *Comment) Initials() string
- func (c *Comment) Paragraphs() []*Paragraph
- func (c *Comment) Parent() *Comment
- func (c *Comment) Replies() []*Comment
- func (c *Comment) Reply(author, text string) *Comment
- func (c *Comment) Resolve()
- func (c *Comment) Resolved() bool
- func (c *Comment) SetInitials(initials string)
- func (c *Comment) SetResolved(resolved bool)
- func (c *Comment) Text() string
- type ContentControl
- func (c *ContentControl) Alias() string
- func (c *ContentControl) Checked() (checked, ok bool)
- func (c *ContentControl) DataBinding() (xpath, storeItemID, prefixMappings string, ok bool)
- func (c *ContentControl) DateFormat() string
- func (c *ContentControl) ID() string
- func (c *ContentControl) IsInline() bool
- func (c *ContentControl) Options() []ContentControlOption
- func (c *ContentControl) RemoveDataBinding() bool
- func (c *ContentControl) SetAlias(alias string)
- func (c *ContentControl) SetDataBinding(xpath, storeItemID string)
- func (c *ContentControl) SetDataBindingWithPrefixMappings(xpath, storeItemID, prefixMappings string)
- func (c *ContentControl) SetTag(tag string)
- func (c *ContentControl) SetValue(text string)
- func (c *ContentControl) Tag() string
- func (c *ContentControl) Type() ContentControlType
- func (c *ContentControl) Value() string
- type ContentControlOption
- type ContentControlType
- type CustomXMLPart
- type Document
- func (d *Document) AcceptAllRevisions() error
- func (d *Document) ActiveXControls() []ActiveXControl
- func (d *Document) AddBookmarkOnRange(name string, start, end *Run) *Bookmark
- func (d *Document) AddBuildingBlock(def BuildingBlockDef) error
- func (d *Document) AddBulletList() *ListStyle
- func (d *Document) AddChart(c *chart.Chart, widthEMU, heightEMU int64) error
- func (d *Document) AddCommentOnRange(start, end *Run, author, text string) *Comment
- func (d *Document) AddContentControl(tag, value string) *ContentControl
- func (d *Document) AddCustomXMLPart(data []byte) (*CustomXMLPart, error)
- func (d *Document) AddFooter(fType FooterType) *Footer
- func (d *Document) AddHeader(hType HeaderType) *Header
- func (d *Document) AddHeading(text string, level int) *Paragraph
- func (d *Document) AddNumberedList() *ListStyle
- func (d *Document) AddOLEObject(data []byte, progID string, opts OLEEmbedOptions) (*OLEObject, error)
- func (d *Document) AddParagraph() *Paragraph
- func (d *Document) AddParagraphWithText(text string) *Paragraph
- func (d *Document) AddSectionBreak() *Section
- func (d *Document) AddShape(text string, opts TextBoxOptions) *TextBox
- func (d *Document) AddShapeGroup(opts GroupOptions, members ...GroupMember) *TextBox
- func (d *Document) AddSignatureLine(opts SignatureLineOptions) *Paragraph
- func (d *Document) AddSource(s Source) error
- func (d *Document) AddTable(rows, cols int) *Table
- func (d *Document) AddTableOfContents(opts TOCOptions) error
- func (d *Document) AddTextBox(text string, opts TextBoxOptions) *TextBox
- func (d *Document) AddWordArt(text string, opts WordArtOptions) *TextBox
- func (d *Document) Append(other *Document) error
- func (d *Document) Body() string
- func (d *Document) Bookmarks() []*Bookmark
- func (d *Document) BuildingBlocks() []*BuildingBlock
- func (d *Document) Charts() []*chart.Chart
- func (d *Document) ClearEndnoteProperties() bool
- func (d *Document) ClearFootnoteProperties() bool
- func (d *Document) Close() error
- func (d *Document) Comments() []*Comment
- func (d *Document) ContentControls() []*ContentControl
- func (d *Document) CustomProperties() map[string]any
- func (d *Document) CustomXMLParts() []*CustomXMLPart
- func (d *Document) DefaultSection() *Section
- func (d *Document) DefaultTabStop() (float64, bool)
- func (d *Document) DocumentVariable(name string) (string, bool)
- func (d *Document) DocumentVariables() []DocumentVariable
- func (d *Document) EndnoteProperties() (NoteProperties, bool)
- func (d *Document) Endnotes() []*Footnote
- func (d *Document) EvenAndOddHeaders() bool
- func (d *Document) Flavor() string
- func (d *Document) Footer(s *Section, fType FooterType) (*Footer, bool)
- func (d *Document) Footers() []*Footer
- func (d *Document) FootnoteProperties() (NoteProperties, bool)
- func (d *Document) Footnotes() []*Footnote
- func (d *Document) FormFields() []FormField
- func (d *Document) Frameset() *Frameset
- func (d *Document) HasGlossary() bool
- func (d *Document) HasMacros() bool
- func (d *Document) Header(s *Section, hType HeaderType) (*Header, bool)
- func (d *Document) Headers() []*Header
- func (d *Document) Hyperlinks() []*Hyperlink
- func (d *Document) Images() []*InlineImage
- func (d *Document) InkAnnotations() []InkAnnotation
- func (d *Document) ListDefinitions() *NumberingManager
- func (d *Document) MailMerge() *MailMerge
- func (d *Document) MergeFields() []string
- func (d *Document) Model3D() []Model3D
- func (d *Document) Numbering() *NumberingManager
- func (d *Document) OLEObjects() []OLEObject
- func (d *Document) Paragraphs() []*Paragraph
- func (d *Document) Protect(opts DocumentProtectionOptions)
- func (d *Document) Protection() *DocumentProtection
- func (d *Document) RejectAllRevisions() error
- func (d *Document) RemoveCustomProperty(name string) bool
- func (d *Document) RemoveDocumentVariable(name string) bool
- func (d *Document) RemoveSource(tag string) bool
- func (d *Document) RemoveVBAProject()
- func (d *Document) RemoveWatermark() bool
- func (d *Document) ReplaceText(replacements map[string]string)
- func (d *Document) Revisions() []*Revision
- func (d *Document) Save(path string) error
- func (d *Document) SaveBytes() ([]byte, error)
- func (d *Document) SaveEncrypted(path, password string) error
- func (d *Document) SaveEncryptedTo(w io.Writer, password string) error
- func (d *Document) SaveTo(dst io.Writer) error
- func (d *Document) SaveToUnvalidated(dst io.Writer) error
- func (d *Document) Sections() []*Section
- func (d *Document) SetCustomProperty(name string, value any) error
- func (d *Document) SetDefaultTabStop(points float64)
- func (d *Document) SetDocumentVariable(name, value string)
- func (d *Document) SetEndnoteProperties(np NoteProperties)
- func (d *Document) SetEvenAndOddHeaders(on bool)
- func (d *Document) SetFootnoteProperties(np NoteProperties)
- func (d *Document) SetFrameset(def FramesetDef) error
- func (d *Document) SetImageWatermark(imageBytes []byte, opts WatermarkOptions) error
- func (d *Document) SetMailMerge(mm *MailMerge)
- func (d *Document) SetSectionImageWatermark(sec *Section, imageBytes []byte, opts WatermarkOptions) error
- func (d *Document) SetSectionTextWatermark(sec *Section, text string, opts WatermarkOptions) error
- func (d *Document) SetTextWatermark(text string, opts WatermarkOptions) error
- func (d *Document) SetVBAProject(data []byte)
- func (d *Document) SetZoom(percent int)
- func (d *Document) SignatureLines() []SignatureLine
- func (d *Document) Sources() []Source
- func (d *Document) Styles() *StyleManager
- func (d *Document) Tables() []*Table
- func (d *Document) Text() string
- func (d *Document) TextBoxes() []*TextBox
- func (d *Document) Theme() *dml.ThemeEditor
- func (d *Document) Unprotect()
- func (d *Document) VBAProject() []byte
- func (d *Document) Validate() validate.Report
- func (d *Document) Watermark() *Watermark
- func (d *Document) Zoom() (int, bool)
- type DocumentEditMode
- type DocumentGrid
- type DocumentProtection
- type DocumentProtectionOptions
- type DocumentVariable
- type FieldType
- type Footer
- type FooterType
- type Footnote
- type FormField
- type FormFieldOptions
- type FormFieldType
- type Frame
- type FrameDef
- type Frameset
- type FramesetDef
- type GroupMember
- type GroupOptions
- type Header
- type HeaderType
- type Hyperlink
- type InkAnnotation
- type InlineImage
- func (img *InlineImage) AltText() string
- func (img *InlineImage) ContentType() string
- func (img *InlineImage) Data() []byte
- func (img *InlineImage) Floating() bool
- func (img *InlineImage) Height() float64
- func (img *InlineImage) HeightEMU() int64
- func (img *InlineImage) PartName() string
- func (img *InlineImage) SetAltText(text string)
- func (img *InlineImage) SetSize(widthPt, heightPt float64)
- func (img *InlineImage) Width() float64
- func (img *InlineImage) WidthEMU() int64
- type LineNumbering
- type ListDefinition
- func (ld *ListDefinition) AbstractNumID() int
- func (ld *ListDefinition) Level(level int) *ListLevel
- func (ld *ListDefinition) ListStyle() *ListStyle
- func (ld *ListDefinition) RestartedListStyle(level, start int) *ListStyle
- func (ld *ListDefinition) SetLevel(level int, format NumberFormat, lvlText string) *ListLevel
- type ListLevel
- func (l *ListLevel) SetAlignment(align Alignment) *ListLevel
- func (l *ListLevel) SetFont(name string) *ListLevel
- func (l *ListLevel) SetFormat(format NumberFormat) *ListLevel
- func (l *ListLevel) SetHanging(points float64) *ListLevel
- func (l *ListLevel) SetIndent(points float64) *ListLevel
- func (l *ListLevel) SetStart(start int) *ListLevel
- func (l *ListLevel) SetText(text string) *ListLevel
- type ListStyle
- type MailMerge
- type MailMergeDataSource
- type MailMergeFieldMapping
- type Model3D
- type NoteProperties
- type NumberFormat
- type NumberingManager
- type OLEEmbedOptions
- type OLEObject
- type Orientation
- type PageBorders
- type PageMargins
- type PageNumbering
- type Paragraph
- func (p *Paragraph) AddBookmark(name string) *Bookmark
- func (p *Paragraph) AddChart(c *chart.Chart, widthEMU, heightEMU int64) error
- func (p *Paragraph) AddCitation(sourceTag string) *Run
- func (p *Paragraph) AddComment(author, text string) *Comment
- func (p *Paragraph) AddContentControl(tag, value string) *ContentControl
- func (p *Paragraph) AddField(t FieldType) *Run
- func (p *Paragraph) AddFormField(opts FormFieldOptions) *Run
- func (p *Paragraph) AddHyperlink(text, url string) *Hyperlink
- func (p *Paragraph) AddInsertedRun(author, text string) *Run
- func (p *Paragraph) AddInsertedRunWithDate(author, text string, date time.Time) *Run
- func (p *Paragraph) AddInternalHyperlink(text, bookmarkName string) *Hyperlink
- func (p *Paragraph) AddMath(m *omml.OMath) error
- func (p *Paragraph) AddMathPara(mp *omml.OMathPara) error
- func (p *Paragraph) AddMergeField(name string) *Run
- func (p *Paragraph) AddMoveFromRun(author, name, text string)
- func (p *Paragraph) AddMoveFromRunWithDate(author, name, text string, date time.Time)
- func (p *Paragraph) AddMoveToRun(author, name, text string)
- func (p *Paragraph) AddMoveToRunWithDate(author, name, text string, date time.Time)
- func (p *Paragraph) AddOLEObject(data []byte, progID string, opts OLEEmbedOptions) (*OLEObject, error)
- func (p *Paragraph) AddRun() *Run
- func (p *Paragraph) AddShape(text string, opts TextBoxOptions) *TextBox
- func (p *Paragraph) AddShapeGroup(opts GroupOptions, members ...GroupMember) *TextBox
- func (p *Paragraph) AddSignatureLine(opts SignatureLineOptions) *Run
- func (p *Paragraph) AddTabStop(stop TabStop)
- func (p *Paragraph) AddText(text string) *Run
- func (p *Paragraph) AddTextBox(text string, opts TextBoxOptions) *TextBox
- func (p *Paragraph) AddWordArt(text string, opts WordArtOptions) *TextBox
- func (p *Paragraph) Alignment() Alignment
- func (p *Paragraph) AlignmentOK() (Alignment, bool)
- func (p *Paragraph) Borders() (ParagraphBorders, bool)
- func (p *Paragraph) Clear()
- func (p *Paragraph) ClearBorders()
- func (p *Paragraph) ClearShading()
- func (p *Paragraph) ClearTabStops()
- func (p *Paragraph) Hyperlinks() []*Hyperlink
- func (p *Paragraph) MathParas() ([]*omml.OMathPara, error)
- func (p *Paragraph) MathZones() ([]*omml.OMath, error)
- func (p *Paragraph) RemoveListStyle()
- func (p *Paragraph) Runs() []*Run
- func (p *Paragraph) SetAlignment(align Alignment)
- func (p *Paragraph) SetBorders(b ParagraphBorders)
- func (p *Paragraph) SetIndentFirstLine(points float64)
- func (p *Paragraph) SetIndentHanging(points float64)
- func (p *Paragraph) SetIndentLeft(points float64)
- func (p *Paragraph) SetIndentRight(points float64)
- func (p *Paragraph) SetKeepTogether(keep bool)
- func (p *Paragraph) SetKeepWithNext(keep bool)
- func (p *Paragraph) SetLineSpacing(multiplier float64)
- func (p *Paragraph) SetLineSpacingExact(points float64)
- func (p *Paragraph) SetListStyle(list *ListStyle, level int)
- func (p *Paragraph) SetPageBreakBefore(brk bool)
- func (p *Paragraph) SetShading(hexColor string)
- func (p *Paragraph) SetSpaceAfter(points float64)
- func (p *Paragraph) SetSpaceBefore(points float64)
- func (p *Paragraph) SetStyle(style string)
- func (p *Paragraph) SetText(text string)
- func (p *Paragraph) Shading() string
- func (p *Paragraph) SpaceAfter() float64
- func (p *Paragraph) SpaceBefore() float64
- func (p *Paragraph) Style() string
- func (p *Paragraph) Tabs() []TabStop
- func (p *Paragraph) Text() string
- type ParagraphBorders
- type Revision
- type RevisionType
- type Run
- func (r *Run) AddBreak()
- func (r *Run) AddComment(author, text string) *Comment
- func (r *Run) AddEndnote(text string) *Footnote
- func (r *Run) AddFloatingImage(path string, anchor Anchor) (*InlineImage, error)
- func (r *Run) AddFloatingImageFromBytes(data []byte, contentType string, anchor Anchor) (*InlineImage, error)
- func (r *Run) AddFloatingSVGImage(svgData, fallbackData []byte, fallbackContentType string, anchor Anchor) (*InlineImage, error)
- func (r *Run) AddFootnote(text string) *Footnote
- func (r *Run) AddImage(path string) (*InlineImage, error)
- func (r *Run) AddImageFromBytes(data []byte, contentType string) (*InlineImage, error)
- func (r *Run) AddSVGImage(svgData, fallbackData []byte, fallbackContentType string) (*InlineImage, error)
- func (r *Run) AddSymbol(font, char string)
- func (r *Run) AddTab()
- func (r *Run) Bold() bool
- func (r *Run) Caps() bool
- func (r *Run) CharacterSpacing() float64
- func (r *Run) Clear()
- func (r *Run) ClearBold()
- func (r *Run) ClearCaps()
- func (r *Run) ClearItalic()
- func (r *Run) ClearSmallCaps()
- func (r *Run) ClearStrike()
- func (r *Run) Color() string
- func (r *Run) Font() string
- func (r *Run) FontSize() float64
- func (r *Run) Highlight() string
- func (r *Run) Hyperlink() *Hyperlink
- func (r *Run) Italic() bool
- func (r *Run) Kerning() float64
- func (r *Run) MarkDeleted(author string) *Run
- func (r *Run) MarkDeletedWithDate(author string, date time.Time) *Run
- func (r *Run) MarkInserted(author string) *Run
- func (r *Run) MarkInsertedWithDate(author string, date time.Time) *Run
- func (r *Run) Position() float64
- func (r *Run) SetBold(bold bool)
- func (r *Run) SetCaps(caps bool)
- func (r *Run) SetCharacterSpacing(points float64)
- func (r *Run) SetColor(color string)
- func (r *Run) SetFont(name string)
- func (r *Run) SetFontSize(size float64)
- func (r *Run) SetHighlight(color string)
- func (r *Run) SetItalic(italic bool)
- func (r *Run) SetKerning(points float64)
- func (r *Run) SetPosition(points float64)
- func (r *Run) SetSmallCaps(smallCaps bool)
- func (r *Run) SetStrike(strike bool)
- func (r *Run) SetStyle(id string)
- func (r *Run) SetSubscript(on bool)
- func (r *Run) SetSuperscript(on bool)
- func (r *Run) SetText(text string)
- func (r *Run) SetUnderline(underline bool)
- func (r *Run) SetUnderlineColor(color string)
- func (r *Run) SetUnderlineStyle(style UnderlineStyle)
- func (r *Run) SetVerticalAlign(align enum.VerticalAlignRun)
- func (r *Run) SmallCaps() bool
- func (r *Run) Strike() bool
- func (r *Run) Style() string
- func (r *Run) Subscript() bool
- func (r *Run) Superscript() bool
- func (r *Run) Text() string
- func (r *Run) Underline() bool
- func (r *Run) UnderlineColor() string
- func (r *Run) UnderlineStyle() UnderlineStyle
- func (r *Run) VerticalAlign() enum.VerticalAlignRun
- type Section
- func (s *Section) ClearColumns()
- func (s *Section) ClearDocumentGrid()
- func (s *Section) ClearEndnoteProperties()
- func (s *Section) ClearFootnoteProperties()
- func (s *Section) ClearLineNumbering()
- func (s *Section) ClearPageBorders()
- func (s *Section) ClearPageNumbering()
- func (s *Section) ClearPaperSource()
- func (s *Section) Columns() (Columns, bool)
- func (s *Section) DocumentGrid() (DocumentGrid, bool)
- func (s *Section) EndnoteProperties() (NoteProperties, bool)
- func (s *Section) FootnoteProperties() (NoteProperties, bool)
- func (s *Section) LineNumbering() (LineNumbering, bool)
- func (s *Section) Margins() PageMargins
- func (s *Section) MarginsOK() (PageMargins, bool)
- func (s *Section) Orientation() Orientation
- func (s *Section) PageBorders() (PageBorders, bool)
- func (s *Section) PageNumbering() (PageNumbering, bool)
- func (s *Section) PageSize() (width, height float64)
- func (s *Section) PaperSource() (first, other int, ok bool)
- func (s *Section) SectionType() string
- func (s *Section) SetColumns(cols Columns)
- func (s *Section) SetDocumentGrid(dg DocumentGrid)
- func (s *Section) SetEndnoteProperties(np NoteProperties)
- func (s *Section) SetFootnoteProperties(np NoteProperties)
- func (s *Section) SetLineNumbering(ln LineNumbering)
- func (s *Section) SetMargins(m PageMargins)
- func (s *Section) SetOrientation(orient Orientation)
- func (s *Section) SetPageBorders(b PageBorders)
- func (s *Section) SetPageNumbering(pn PageNumbering)
- func (s *Section) SetPageSize(width, height float64)
- func (s *Section) SetPaperSource(first, other int)
- func (s *Section) SetSectionType(typ string)
- func (s *Section) SetTitlePage(on bool)
- func (s *Section) SetVerticalAlignment(align string)
- func (s *Section) TitlePage() bool
- func (s *Section) VerticalAlignment() string
- type ShapeType
- type SignatureLine
- type SignatureLineOptions
- type Source
- type Style
- func (s *Style) BasedOn() string
- func (s *Style) ID() string
- func (s *Style) Name() string
- func (s *Style) SetAlignment(align Alignment) *Style
- func (s *Style) SetBasedOn(id string) *Style
- func (s *Style) SetBold(on bool) *Style
- func (s *Style) SetColor(color string) *Style
- func (s *Style) SetFont(name string) *Style
- func (s *Style) SetFontSize(points float64) *Style
- func (s *Style) SetIndentFirstLine(points float64) *Style
- func (s *Style) SetIndentHanging(points float64) *Style
- func (s *Style) SetIndentLeft(points float64) *Style
- func (s *Style) SetItalic(on bool) *Style
- func (s *Style) SetLineSpacing(multiplier float64) *Style
- func (s *Style) SetLink(id string) *Style
- func (s *Style) SetName(name string) *Style
- func (s *Style) SetNext(id string) *Style
- func (s *Style) SetQuickFormat(on bool) *Style
- func (s *Style) SetSpaceAfter(points float64) *Style
- func (s *Style) SetSpaceBefore(points float64) *Style
- func (s *Style) SetType(styleType StyleType) *Style
- func (s *Style) SetUIPriority(priority int) *Style
- func (s *Style) Type() StyleType
- type StyleManager
- type StyleType
- type TOCOptions
- type TabAlignment
- type TabLeader
- type TabStop
- type Table
- func (t *Table) AddRow() *TableRow
- func (t *Table) Alignment() Alignment
- func (t *Table) Borders() (TableBorders, bool)
- func (t *Table) Indent() (float64, bool)
- func (t *Table) Layout() TableLayout
- func (t *Table) Rows() []*TableRow
- func (t *Table) SetAlignment(align Alignment)
- func (t *Table) SetBorders(b TableBorders)
- func (t *Table) SetCellMargins(top, right, bottom, left float64)
- func (t *Table) SetIndent(points float64)
- func (t *Table) SetLayout(layout TableLayout)
- func (t *Table) SetStyle(style string)
- func (t *Table) SetTableLook(look TableLook)
- func (t *Table) SetWidth(points float64)
- func (t *Table) Shading() string
- func (t *Table) Style() string
- func (t *Table) TableLook() (TableLook, bool)
- func (t *Table) Width() (float64, bool)
- type TableBorders
- type TableCell
- func (tc *TableCell) AddParagraph() *Paragraph
- func (tc *TableCell) Borders() (CellBorders, bool)
- func (tc *TableCell) ClearVerticalMerge()
- func (tc *TableCell) GridSpan() int
- func (tc *TableCell) Paragraphs() []*Paragraph
- func (tc *TableCell) SetBorders(b CellBorders)
- func (tc *TableCell) SetGridSpan(span int)
- func (tc *TableCell) SetShading(hexColor string)
- func (tc *TableCell) SetVerticalAlignment(align string)
- func (tc *TableCell) SetVerticalMerge(m VerticalMerge)
- func (tc *TableCell) SetWidth(points float64)
- func (tc *TableCell) Shading() string
- func (tc *TableCell) Text() string
- func (tc *TableCell) VerticalAlignment() string
- func (tc *TableCell) VerticalMerge() VerticalMerge
- func (tc *TableCell) Width() (float64, bool)
- type TableLayout
- type TableLook
- type TableRow
- type TextBox
- type TextBoxOptions
- type UnderlineStyle
- type VerticalMerge
- type WarpPreset
- type Watermark
- type WatermarkOptions
- type WatermarkType
- type WordArtOptions
Examples ¶
Constants ¶
const ( SourceBook = "Book" SourceJournalArticle = "JournalArticle" SourceArticleInPeriodical = "ArticleInAPeriodical" SourceReport = "Report" SourceWebSite = "InternetSite" SourceDocumentFromWebSite = "DocumentFromInternetSite" )
Common bibliography source types (b:SourceType values). Any other string is accepted and passed through verbatim, so callers can emit further types.
const ( MailMergeFormLetters = "formLetters" MailMergeEmail = "email" MailMergeEnvelopes = "envelopes" MailMergeFax = "fax" MailMergeCatalog = "catalog" )
Mail-merge main-document types (w:mailMerge/w:mainDocumentType), the ECMA-376 ST_MailMergeDocType values. Any other value is passed through verbatim, so these are conveniences rather than an exhaustive set.
const ( SectionTypeNextPage = "nextPage" SectionTypeNextColumn = "nextColumn" SectionTypeContinuous = "continuous" SectionTypeEvenPage = "evenPage" SectionTypeOddPage = "oddPage" )
Section type values (w:type/@w:val) for Section.SetSectionType. An empty string leaves the section type unset, which Word treats as "nextPage".
const ( PageNumberDecimal = "decimal" PageNumberUpperRoman = "upperRoman" PageNumberLowerRoman = "lowerRoman" PageNumberUpperLetter = "upperLetter" PageNumberLowerLetter = "lowerLetter" )
Page number format values (w:pgNumType/@w:fmt) for PageNumbering.Format.
Variables ¶
var ( // ErrNotDOCX indicates the file is not a valid Word document. ErrNotDOCX = errors.New("docx: not a valid Word document") // ErrRevisionStale is returned by Revision.Accept and Revision.Reject when // the revision's content is no longer where it was enumerated — typically // because an earlier Accept or Reject rebuilt the container it lived in, as // Document.Revisions' godoc warns. The document is left unchanged; re-read // Revisions and retry. ErrRevisionStale = errors.New("docx: revision no longer resolvable") )
var ErrNilDocument = errors.New("docx: source document is nil")
ErrNilDocument is returned when Append is given a nil source document.
Functions ¶
func PageSizeA4 ¶
PageSizeA4 returns A4 size (210 x 297 mm) in points.
func PageSizeLegal ¶
PageSizeLegal returns US Legal size (8.5 x 14 inches) in points.
func PageSizeLetter ¶
PageSizeLetter returns US Letter size (8.5 x 11 inches) in points.
Types ¶
type ActiveXControl ¶
type ActiveXControl struct {
// Name is the OPC part name of the control's ax:ocx XML part.
Name string
// ContentType is that part's content type (application/vnd.ms-office.activeX+xml).
ContentType string
// Data is the ax:ocx XML, carried verbatim.
Data []byte
// ClassID is the control server's COM class id (e.g.
// "{8BD21D40-EC42-11CE-9E0D-00AA006002F3}"), best-effort from the part root.
ClassID string
// Persistence names how the control state is stored (e.g. "persistPropertyBag").
Persistence string
// BinaryName is the OPC part name of the control's persistence binary
// (activeXN.bin), or "" when the control declares none.
BinaryName string
// BinaryData is the persistence binary, carried verbatim.
BinaryData []byte
}
ActiveXControl is an ActiveX control embedded in a document: the ax:ocx control part (word/activeX/activeXN.xml) plus its persistence binary (activeXN.bin). spine reads, enumerates, and preserves these parts verbatim; authoring the ActiveX persistence binary is out of scope.
type Anchor ¶
type Anchor struct {
// RelativeToPage anchors X/Y to the page origin instead of the column
// (horizontal) and paragraph (vertical).
RelativeToPage bool
// X and Y are the offsets from the anchor origin, in points.
X, Y float64
// BehindText places the image behind the text (e.g. a watermark) instead
// of in front of it.
BehindText bool
}
Anchor positions a floating image relative to the page or the surrounding text. The zero value anchors relative to the column/paragraph at offset (0,0), in front of the text.
type Bookmark ¶
type Bookmark struct {
// contains filtered or unexported fields
}
Bookmark is a named location or span in a document. A bookmark brackets a range of content with a w:bookmarkStart / w:bookmarkEnd pair sharing a w:id; internal hyperlinks (AddInternalHyperlink) target it by name.
type Border ¶
type Border struct {
Style string // "single", "double", "dotted", "dashed", "thick", "none"
Width float64 // points (mapped to eighths-of-a-point internally)
Color string // hex color (e.g., "000000")
}
Border represents a border definition for tables and cells.
type BuildingBlock ¶
type BuildingBlock struct {
// contains filtered or unexported fields
}
BuildingBlock is one entry of the glossary document (a w:docPart) — a reusable content fragment such as an AutoText entry, a cover page, or a header/footer gallery item. BuildingBlocks reads the existing entries; AddBuildingBlock authors new ones (regenerating, or newly creating, the glossary part on save). A glossary part that this session never touches is preserved verbatim.
func (*BuildingBlock) Category ¶
func (b *BuildingBlock) Category() string
Category returns the building block's category name (w:category/w:name), e.g. "General".
func (*BuildingBlock) Description ¶
func (b *BuildingBlock) Description() string
Description returns the building block's description (w:docPartPr/w:description), or "" when unset.
func (*BuildingBlock) GUID ¶
func (b *BuildingBlock) GUID() string
GUID returns the building block's identifier (w:docPartPr/w:guid) in "{GUID}" form, or "" when unset.
func (*BuildingBlock) Gallery ¶
func (b *BuildingBlock) Gallery() string
Gallery returns the building block's gallery (w:category/w:gallery), e.g. "AutoText", "coverPg", or "placeholder".
func (*BuildingBlock) Name ¶
func (b *BuildingBlock) Name() string
Name returns the building block's name (w:docPartPr/w:name), the identifier Word shows in its galleries.
func (*BuildingBlock) Types ¶
func (b *BuildingBlock) Types() []string
Types returns the building block's declared types (w:docPartPr/w:types), e.g. "bbPlcHdr" for a placeholder or "autoTxt" for an AutoText entry.
type BuildingBlockDef ¶
type BuildingBlockDef struct {
Name string
Gallery string
Category string
Types []string
Style string
Description string
GUID string
}
BuildingBlockDef describes a building block (a glossary w:docPart) to author with Document.AddBuildingBlock. It mirrors the fields the read-side BuildingBlock accessors expose; the value type is separate because BuildingBlock keeps its fields behind accessors.
Name is the building-block identifier Word shows in its galleries (required). Gallery and Category place the block in Word's building-block organizer (e.g. Gallery "AutoText"/"placeholder", Category "General"). Types are w:type values (e.g. "bbPlcHdr"). Style is an optional style-id reference. GUID is the block's identifier in "{GUID}" form; a fresh one is generated when empty.
The authored block's body is a single empty paragraph: this API models a building block's metadata, not its reusable body content. An existing glossary part's docParts (and their bodies) are preserved verbatim; the new docPart is appended.
type CellBorders ¶
type CellBorders struct {
Top, Bottom, Left, Right *Border
}
CellBorders defines borders for a table cell.
type Column ¶
Column describes a single explicit text column (w:col). Width and Spacing are in points; Spacing is the gap following the column.
type Columns ¶
Columns describes a section's multi-column layout (w:cols). When EqualWidth is true (the default), Count equal columns are laid out with Spacing between them and the Cols slice is ignored. When EqualWidth is false, the Cols slice gives each column's explicit width and trailing spacing.
type Comment ¶
type Comment struct {
// contains filtered or unexported fields
}
Comment is a comment attached to a document. The read accessors work on any comment-bearing document; the threading accessors (Parent, Replies, Resolved) and AnchorText additionally rely on the Microsoft commentsExtended part and the document range markers that modern Word writes.
The core method set — ID, Author, Text, Date, Resolved, Replies, Parent, and the AddComment/Reply/Resolve writers — is shared verbatim with the xlsx and pptx comment APIs so the three formats are symmetric. Initials, Paragraphs, AnchorText, and range-precise anchoring are docx-specific additions.
func (*Comment) AnchorText ¶
AnchorText returns the document text bracketed by this comment's range markers (docx-specific). It is "" for a point anchor with no spanned text and for a comment whose range cannot be resolved in the document.
func (*Comment) Date ¶
Date returns the comment timestamp, or the zero time if it is absent or unparseable.
func (*Comment) Paragraphs ¶
Paragraphs returns the comment body paragraphs (docx-specific).
func (*Comment) Parent ¶
Parent returns the comment this one replies to, or nil for a top-level comment (or when the document carries no threading information).
func (*Comment) Reply ¶
Reply adds a threaded reply to this comment, anchored at the same range and linked to it through commentsExtended.
func (*Comment) Resolved ¶
Resolved reports whether the comment's thread is marked done in commentsExtended. Comments in a document without that part are never resolved.
func (*Comment) SetInitials ¶
SetInitials overrides the author initials on the comment (docx-specific).
func (*Comment) SetResolved ¶
SetResolved sets whether the comment's thread is marked done. Word resolves a thread as a whole, so the state is applied to every comment in the thread (the root and all of its replies), regardless of which one this handle points at.
type ContentControl ¶
type ContentControl struct {
// contains filtered or unexported fields
}
ContentControl is a structured document tag (w:sdt) — Word's content control. It wraps either a block-level control (w:sdt in the body, spanning whole paragraphs or tables) or an inline control (w:sdtRun, within a paragraph). Exactly one of the underlying representations is set.
func (*ContentControl) Alias ¶
func (c *ContentControl) Alias() string
Alias returns the control's friendly name (w:alias), or "" when unset.
func (*ContentControl) Checked ¶
func (c *ContentControl) Checked() (checked, ok bool)
Checked reports the state of a Word 2010 checkbox control. The second return value is false when the control is not a checkbox or has no checked child.
func (*ContentControl) DataBinding ¶
func (c *ContentControl) DataBinding() (xpath, storeItemID, prefixMappings string, ok bool)
DataBinding returns the content control's data binding (xpath, storeItemID, prefixMappings) and whether one is present.
func (*ContentControl) DateFormat ¶
func (c *ContentControl) DateFormat() string
DateFormat returns the display format of a date control (w:dateFormat), or "" for other kinds.
func (*ContentControl) ID ¶
func (c *ContentControl) ID() string
ID returns the control's w:id value, or "" when unset.
func (*ContentControl) IsInline ¶
func (c *ContentControl) IsInline() bool
IsInline reports whether the control is an inline (run-level) control rather than a block-level one.
func (*ContentControl) Options ¶
func (c *ContentControl) Options() []ContentControlOption
Options returns the selectable items of a drop-down or combo-box control, or nil for other kinds.
func (*ContentControl) RemoveDataBinding ¶
func (c *ContentControl) RemoveDataBinding() bool
RemoveDataBinding removes the content control's data binding, reporting whether one was present.
func (*ContentControl) SetAlias ¶
func (c *ContentControl) SetAlias(alias string)
SetAlias sets the control's friendly name (w:alias). Passing "" removes it.
func (*ContentControl) SetDataBinding ¶
func (c *ContentControl) SetDataBinding(xpath, storeItemID string)
SetDataBinding binds the content control to a node of a custom-XML data part. xpath is an XPath expression selecting the node; storeItemID is the datastore item id of the target part (the "{GUID}" from CustomXMLPart.ItemID). An existing binding is replaced. Word keeps the control's displayed value in sync with the bound node.
func (*ContentControl) SetDataBindingWithPrefixMappings ¶
func (c *ContentControl) SetDataBindingWithPrefixMappings(xpath, storeItemID, prefixMappings string)
SetDataBindingWithPrefixMappings is SetDataBinding with an explicit w:prefixMappings string declaring the namespace prefixes used by xpath (e.g. `xmlns:ns0='http://example.com/data'`).
func (*ContentControl) SetTag ¶
func (c *ContentControl) SetTag(tag string)
SetTag sets the control's tag (w:tag). Passing "" removes it.
func (*ContentControl) SetValue ¶
func (c *ContentControl) SetValue(text string)
SetValue replaces the control's content with a single run of text. Existing content (and its run formatting) is discarded.
func (*ContentControl) Tag ¶
func (c *ContentControl) Tag() string
Tag returns the control's programmatic tag (w:tag), or "" when unset.
func (*ContentControl) Type ¶
func (c *ContentControl) Type() ContentControlType
Type returns the control's kind. It reports ContentControlUnspecified for a plain rich-text container with no explicit control-type child.
func (*ContentControl) Value ¶
func (c *ContentControl) Value() string
Value returns the control's current text (the concatenated text of its content runs).
type ContentControlOption ¶
type ContentControlOption struct {
// DisplayText is the label shown to the user.
DisplayText string
// Value is the underlying stored value.
Value string
}
ContentControlOption is one selectable item of a drop-down or combo-box content control.
type ContentControlType ¶
type ContentControlType string
ContentControlType identifies the control kind of a content control (structured document tag). The empty value reports a plain container with no explicit control-type child (a rich-text SDT).
const ( // ContentControlUnspecified is a container SDT with no control-type child. ContentControlUnspecified ContentControlType = "" // ContentControlRichText is a rich-text control (w:richText). ContentControlRichText ContentControlType = "richText" // ContentControlText is a plain-text control (w:text). ContentControlText ContentControlType = "text" // ContentControlDropDownList is a drop-down list control (w:dropDownList). ContentControlDropDownList ContentControlType = "dropDownList" // ContentControlComboBox is a combo-box control (w:comboBox). ContentControlComboBox ContentControlType = "comboBox" // ContentControlCheckbox is a Word 2010 checkbox control (w14:checkbox). ContentControlCheckbox ContentControlType = "checkbox" // ContentControlDate is a date-picker control (w:date). ContentControlDate ContentControlType = "date" // ContentControlPicture is a picture control (w:picture). ContentControlPicture ContentControlType = "picture" )
type CustomXMLPart ¶
type CustomXMLPart struct {
// contains filtered or unexported fields
}
CustomXMLPart is a custom-XML data part of the document — a customXml/itemN.xml part holding structured XML that content controls can bind to. The zero value is not used; obtain instances from Document.CustomXMLParts or Document.AddCustomXMLPart.
func (*CustomXMLPart) Data ¶
func (c *CustomXMLPart) Data() []byte
Data returns the raw XML bytes of the custom-XML data part.
func (*CustomXMLPart) ItemID ¶
func (c *CustomXMLPart) ItemID() string
ItemID returns the datastore item id (storeItemID) declared by the part's itemProps, in the "{GUID}" form a content control's data binding references, or "" when the part has no properties.
func (*CustomXMLPart) PartName ¶
func (c *CustomXMLPart) PartName() string
PartName returns the package part name of the data part (e.g. "/customXml/item1.xml").
func (*CustomXMLPart) SchemaRefs ¶
func (c *CustomXMLPart) SchemaRefs() []string
SchemaRefs returns the schema URIs the part's itemProps associates with the data (ds:schemaRef), or nil when none are declared.
type Document ¶
type Document struct {
// Properties contains the document properties.
Properties opc.CoreProperties
// contains filtered or unexported fields
}
Document represents a Word document.
func Create ¶
func Create() *Document
Create creates a new, empty document.
Example ¶
ExampleCreate mirrors the README quick start for Word: a heading, a plain paragraph, and a formatted run, serialized with SaveBytes and reopened from memory to count the paragraphs — no files touched.
package main
import (
"bytes"
"fmt"
"github.com/mgilbir/spine/docx"
)
func main() {
doc := docx.Create()
doc.Properties.Title = "My Document"
doc.AddHeading("Welcome", 1)
doc.AddParagraphWithText("This is a simple document created with Spine.")
p := doc.AddParagraph()
bold := p.AddRun()
bold.SetText("Bold text")
bold.SetBold(true)
data, err := doc.SaveBytes()
if err != nil {
panic(err)
}
reopened, err := docx.OpenReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
panic(err)
}
defer func() { _ = reopened.Close() }()
fmt.Println("paragraphs:", len(reopened.Paragraphs()))
}
Output: paragraphs: 3
func Open ¶
func Open(path string, opts ...opc.ReaderOption) (*Document, error)
Open opens a Word document from a file path. The whole package is read into memory, so the returned Document retains no OS file handle.
Options configure the underlying package reader: opc.WithPassword opens a password-encrypted document, and the opc.WithMax* options adjust the bounds that guard against decompression bombs.
It returns ErrNotDOCX when the package is not WordprocessingML, opc.ErrStrictOOXML for an ISO-Strict package, and opc.ErrEncrypted when the input is password-encrypted and no opc.WithPassword was given. Each is matchable with errors.Is.
func OpenReader ¶
OpenReader opens a Word document from an in-memory reader. The package is read up front, so r need not remain valid after Open returns. It takes the same options and returns the same sentinels as Open (ErrNotDOCX, opc.ErrStrictOOXML, opc.ErrEncrypted), matchable with errors.Is.
func (*Document) AcceptAllRevisions ¶
AcceptAllRevisions accepts every editable revision in the document body and in every header and footer: insertions become normal text, deletions are removed, run/paragraph property changes keep their new properties, and tracked moves are resolved (the source content is dropped, the destination kept as normal text; the w:moveFrom/w:moveTo range markers are preserved in place).
Read-only revision types are left untouched: table, row and cell property changes, row and cell insertions and deletions, cell merges, and section property changes — including the w:sectPrChange on a mid-document section break. Those are reported by Revisions but never transformed here, so a document AcceptAllRevisions has processed can still enumerate revisions.
It returns an error only if a future transform reports one; today it always succeeds.
func (*Document) ActiveXControls ¶
func (d *Document) ActiveXControls() []ActiveXControl
ActiveXControls returns the document's ActiveX controls, ordered by part name for determinism. Controls are located by their ax:ocx content type (or the word/activeX/ path) across all preserved parts; each control's persistence binary is resolved through the control part's relationships, falling back to the sibling .bin part. Extraction is read-only and leaves every part byte-for-byte unchanged on a subsequent save.
func (*Document) AddBookmarkOnRange ¶
AddBookmarkOnRange brackets the content from the start run to the end run (inclusive) with a bookmark of the given name. The runs may live in the same paragraph or in different paragraphs. Returns nil if either run is not a direct child run of its paragraph (e.g. a run nested inside a hyperlink) or sits in a paragraph the bookmark walk does not reach, leaving the document unchanged so no bookmarkStart is placed without a matching bookmarkEnd. Endpoints given in reverse document order are swapped rather than emitted inverted (C404).
func (*Document) AddBuildingBlock ¶
func (d *Document) AddBuildingBlock(def BuildingBlockDef) error
AddBuildingBlock appends a building block to the document's glossary, creating the glossary part (word/glossary/document.xml), its document relationship, and its content-type override when the document has none. A block with no Name is rejected: Word identifies a building block by its name. The block is assigned a fresh GUID when GUID is empty.
An existing glossary part round-trips byte-for-byte until the first AddBuildingBlock call; from then on the new docPart is spliced in before the closing </w:docParts> so every existing docPart (and its body) is preserved verbatim.
The block created here is metadata only: it registers the name, gallery, category, types, style and description, and its body is a single empty paragraph. There is no way to give a new block reusable content — the name "building block" notwithstanding — so it appears in Word's gallery and inserts nothing. Blocks that came with the opened package keep their bodies.
func (*Document) AddBulletList ¶
AddBulletList creates a new bullet list definition and returns a ListStyle that can be applied to paragraphs.
func (*Document) AddChart ¶
AddChart appends a paragraph containing an inline chart to the document body and returns nothing but an error. It is the ergonomic primary: build a chart with the shared chart package (chart.NewColumn(), SetTitle, SetCategories, AddSeries, ...), then hand it here with the display size in EMUs (914400 per inch). The chart's data is embedded as an editable workbook so Office can open and edit it — docx charts have no host worksheet.
func (*Document) AddCommentOnRange ¶
AddCommentOnRange attaches a comment spanning from the start run to the end run (inclusive). The runs may live in the same paragraph or in different paragraphs; the range markers are placed around them and the reference mark after the end run.
It returns nil if either run is not a direct child run of its paragraph (e.g. a run nested inside a hyperlink) or sits outside the body, adding no comment so comments.xml gains no orphan entry with no anchor. Endpoints given in reverse document order are swapped rather than emitted inverted (C404).
func (*Document) AddContentControl ¶
func (d *Document) AddContentControl(tag, value string) *ContentControl
AddContentControl appends a block-level rich-text content control to the document body, carrying the given tag and holding value as its content. The returned handle can further adjust the tag, alias, or value.
The new control carries no w:id. That is legal — the attribute is optional — but Word assigns one when it saves the document, so a round trip through Word will show the added attribute as a diff.
func (*Document) AddCustomXMLPart ¶
func (d *Document) AddCustomXMLPart(data []byte) (*CustomXMLPart, error)
AddCustomXMLPart adds a custom-XML data part carrying data, generating its itemProps (with a fresh datastore item id) and wiring the package relationships. The returned part's ItemID is the storeItemID to pass to ContentControl.SetDataBinding. The data must be a well-formed XML document; its root-element namespace, when present, is recorded as a schema reference.
func (*Document) AddFooter ¶
func (d *Document) AddFooter(fType FooterType) *Footer
AddFooter adds a footer of the specified type to the document.
func (*Document) AddHeader ¶
func (d *Document) AddHeader(hType HeaderType) *Header
AddHeader adds a header of the specified type to the document's final (default) section.
func (*Document) AddHeading ¶
AddHeading adds a heading paragraph with the specified level. The level is clamped to the valid 1-9 range so out-of-range values cannot produce a nonsensical style name (e.g. level 10 previously yielded "Heading:").
func (*Document) AddNumberedList ¶
AddNumberedList creates a new numbered list definition and returns a ListStyle that can be applied to paragraphs.
func (*Document) AddOLEObject ¶
func (d *Document) AddOLEObject(data []byte, progID string, opts OLEEmbedOptions) (*OLEObject, error)
AddOLEObject embeds an OLE object in a new run at the end of the document body and returns a handle to the stored part. It is a convenience wrapper over Paragraph.AddOLEObject.
func (*Document) AddParagraph ¶
AddParagraph adds a new paragraph to the document body.
func (*Document) AddParagraphWithText ¶
AddParagraphWithText adds a new paragraph with the specified text.
func (*Document) AddSectionBreak ¶
AddSectionBreak adds a section break by setting section properties on the last block-level paragraph and creating a new final section. When the body's last block is not a paragraph (e.g. the document ends with a table), a new paragraph is appended after it to carry the section properties — attaching them to an earlier paragraph would move the section boundary.
The new final section is a copy of the section it splits off from, which is what Word's own "insert section break" does: page size, margins, columns and the header/footer references carry across, so content after the break keeps the document's furniture. Leaving it empty reverted everything after the break to Word's defaults — an A4 landscape document with headers continued as unfurnished Letter portrait pages (C488). Adjust the returned Section to make the new section differ.
func (*Document) AddShape ¶
func (d *Document) AddShape(text string, opts TextBoxOptions) *TextBox
AddShape appends a paragraph containing a basic shape to the document body.
func (*Document) AddShapeGroup ¶
func (d *Document) AddShapeGroup(opts GroupOptions, members ...GroupMember) *TextBox
AddShapeGroup appends a paragraph containing a shape group to the document body and returns the group handle. It is a convenience wrapper over Paragraph.AddShapeGroup.
func (*Document) AddSignatureLine ¶
func (d *Document) AddSignatureLine(opts SignatureLineOptions) *Paragraph
AddSignatureLine appends a paragraph containing a signature line to the document body and returns the paragraph. It is a convenience wrapper over Paragraph.AddSignatureLine.
func (*Document) AddSource ¶
AddSource adds a bibliography source to the document, creating the bibliography part (word/bibliography/sources.xml) on first use. A source with no Tag is rejected: CITATION fields reference a source by its tag, so an untagged source could never be cited. Adding a source whose tag already exists replaces the existing entry, so re-adding an edited source updates it in place. The source is assigned a fresh b:Guid.
func (*Document) AddTable ¶
AddTable creates a new table with the specified number of rows and columns.
func (*Document) AddTableOfContents ¶
func (d *Document) AddTableOfContents(opts TOCOptions) error
AddTableOfContents appends a table of contents built from the document's heading styles (see AddHeading), wrapped in a structured document tag so Word offers its "Update Table" affordance.
The TOC is a Word field: its entries are computed by Word, not by this library. The field is marked dirty so Word recalculates it when the document is opened (depending on settings, Word may prompt before updating); until then the placeholder paragraph is shown.
func (*Document) AddTextBox ¶
func (d *Document) AddTextBox(text string, opts TextBoxOptions) *TextBox
AddTextBox appends a paragraph containing a text box to the document body and returns the box handle. It is a convenience wrapper over Paragraph.AddTextBox.
func (*Document) AddWordArt ¶
func (d *Document) AddWordArt(text string, opts WordArtOptions) *TextBox
AddWordArt appends a paragraph containing a WordArt shape to the document body and returns the box handle. It is a convenience wrapper over Paragraph.AddWordArt.
func (*Document) Append ¶
Append appends the body content (paragraphs, tables, and block-level structured document tags) of other to this document. Images and other media referenced by the copied content are brought over as new package parts with remapped relationship ids; style and numbering definitions are copied, and their ids are remapped when they collide with differing definitions already in this document, with every reference in the copied content rewritten to match.
Footnotes, endnotes, and comments referenced by the copied content are merged too: the source definitions are imported with fresh ids disjoint from this document's, and the copied reference marks are rewritten to point at them, so an appended footnote keeps its own text rather than aliasing onto a destination note that happens to share its id. Comment threading metadata (commentsExtended, people) is not merged.
The final (body-level) section properties of other are not copied, so the appended content joins this document's last section. Section breaks inside other that survive the append (paragraph-level section properties) keep their header/footer references: the referenced header and footer parts — and any images they embed — are carried over as new package parts with remapped relationship ids. Header/footer references belonging to other's dropped final section are not carried. Theme reconciliation is deferred.
func (*Document) Bookmarks ¶
Bookmarks returns every bookmark in the document, in document order (by the position of each start marker): the body first, then each header and each footer in part-name order. Word's built-in _GoBack bookmark and other markers are all included.
func (*Document) BuildingBlocks ¶
func (d *Document) BuildingBlocks() []*BuildingBlock
BuildingBlocks returns the document's building blocks (glossary docParts) in document order, including blocks added this session with AddBuildingBlock, or nil when the document has neither a glossary part nor any pending block. The existing docParts are preserved verbatim on save; the session-added ones are appended (mirroring where writeGlossaryPart splices them, before the closing </w:docParts>), so read-your-writes holds within a session.
func (*Document) Charts ¶
Charts returns every chart in the document, in document order, parsed into chart.Chart definitions. Charts are found by scanning the drawings in every paragraph — the body and every header and footer, descending into tables and including runs nested in hyperlinks and tracked changes — for a c:chart reference, resolving its relationship to the chart part (in the paragraph's owning part scope), and parsing that part. Charts whose part cannot be resolved or parsed are skipped.
func (*Document) ClearEndnoteProperties ¶
ClearEndnoteProperties removes the document-level w:endnotePr element and reports whether it was present.
func (*Document) ClearFootnoteProperties ¶
ClearFootnoteProperties removes the document-level w:footnotePr element and reports whether it was present.
func (*Document) Close ¶
Close releases resources held by a document opened from a file. Open and OpenReader read the whole package into memory up front and retain no OS file handle, so Close is effectively a no-op. Calling Save (or any Save* method) after Close is valid: the in-memory model and preserved parts remain intact.
func (*Document) Comments ¶
Comments returns the document's top-level comments (thread roots), in the order they appear in the comments part. Replies are reached through Comment.Replies() rather than appearing in this list, matching the xlsx and pptx comment APIs.
Comments can be added, replied to and resolved, but not removed: there is no RemoveComment, as there is no RemoveFootnote, RemoveStyle or RemoveContentControl (Document.RemoveSource, for a bibliography source, is the lone deletion in the docx feature set). Marking a thread resolved with SetResolved is the closest available operation.
func (*Document) ContentControls ¶
func (d *Document) ContentControls() []*ContentControl
ContentControls returns every content control in the document body in document order: block-level and inline controls, controls nested inside other controls, and controls inside tables (nested tables included), hyperlinks and tracked-change blocks.
The walk covers the body only. Controls in headers, footers and the glossary (building-block) part are not reported.
Read coverage is broader than write coverage: Type, Options, DateFormat and Checked read a control's kind-specific properties, but only Tag, Alias and Value can be written. There is no SetChecked for a checkbox, no way to add or select a drop-down item, and no w:dataBinding authoring — so a control and a CustomXMLParts item cannot be bound together through this API even though both are exposed. A parsed control keeps whichever of those it already carries: the properties the model does not type are preserved verbatim.
func (*Document) CustomProperties ¶
CustomProperties returns the document's custom (user-defined) properties as a name→value map, or nil when the document has none. Values are one of string, int64, float64, bool, or time.Time. The returned map is a copy; mutate the properties through SetCustomProperty and RemoveCustomProperty.
func (*Document) CustomXMLParts ¶
func (d *Document) CustomXMLParts() []*CustomXMLPart
CustomXMLParts returns the document's custom-XML data parts (customXml/itemN.xml) in part-name order, including parts added this session. Each part exposes its raw data, its datastore item id (the storeItemID a content control binds to), and any declared schema references.
func (*Document) DefaultSection ¶
DefaultSection returns the document's default (last) section. If no section properties exist, they are created with default values.
func (*Document) DefaultTabStop ¶
DefaultTabStop returns the document's default tab-stop interval in points (w:defaultTabStop) and whether the setting is present. Word's built-in default is 36 points (720 twips) when the element is absent.
func (*Document) DocumentVariable ¶
DocumentVariable returns the value of the named document variable and whether it is defined.
func (*Document) DocumentVariables ¶
func (d *Document) DocumentVariables() []DocumentVariable
DocumentVariables returns the document variables (w:docVars/w:docVar) in document order, or nil when none are defined.
func (*Document) EndnoteProperties ¶
func (d *Document) EndnoteProperties() (NoteProperties, bool)
EndnoteProperties returns the document-level endnote numbering properties (w:settings/w:endnotePr) and whether the element is present.
func (*Document) Endnotes ¶
Endnotes returns the document's endnotes in document (part) order, excluding the mandatory separator and continuationSeparator notes.
func (*Document) EvenAndOddHeaders ¶
EvenAndOddHeaders reports whether the document declares distinct even-page headers and footers (w:evenAndOddHeaders).
func (*Document) Flavor ¶
Flavor returns the main part's content type: one of the WordprocessingML flavors (opc.ContentTypeDocument, opc.ContentTypeDocumentTemplateMain, or a macro-enabled variant). An opened file reports the flavor it was opened with — a template (.dotx) stays a template across a save — and a created document reports opc.ContentTypeDocument. There is no conversion API: retyping a file to another flavor is out of scope.
func (*Document) Footer ¶ added in v0.2.0
func (d *Document) Footer(s *Section, fType FooterType) (*Footer, bool)
Footer returns the section's footer of the given type and whether the section declares one.
func (*Document) Footers ¶ added in v0.2.0
Footers returns an editable handle for every footer part in the document, ordered by part name.
func (*Document) FootnoteProperties ¶
func (d *Document) FootnoteProperties() (NoteProperties, bool)
FootnoteProperties returns the document-level footnote numbering properties (w:settings/w:footnotePr) and whether the element is present. Only the numbering fields are reported; separator references are preserved but not exposed.
func (*Document) Footnotes ¶
Footnotes returns the document's footnotes in document (part) order, excluding the mandatory separator and continuationSeparator notes.
Notes can be added but not removed: there is no RemoveFootnote or RemoveEndnote, so a note anchored by content that is later replaced stays in footnotes.xml with nothing referencing it.
func (*Document) FormFields ¶
FormFields returns the legacy form fields present anywhere in the document body (including inside tables, content controls, hyperlinks and tracked changes) and in every header and footer, in document order. Each field is reconstructed from its w:fldChar begin/separate/end run sequence and the w:ffData definition carried on the begin field character.
The field state machine runs over each part as a whole, so a field whose begin and end runs sit in different paragraphs is still read as one field.
func (*Document) Frameset ¶
Frameset returns the document's top-level frameset (the window split defined in the web-settings part), or nil when the document is not a frameset document. A frameset authored this session with SetFrameset is reflected here (it takes precedence, mirroring how the save replaces the existing frameset subtree), so read-your-writes holds within a session.
func (*Document) HasGlossary ¶
HasGlossary reports whether the document carries a glossary (building blocks) part.
func (*Document) HasMacros ¶
HasMacros reports whether the document carries a VBA project (vbaProject.bin), accounting for a project injected or removed in this session.
func (*Document) Header ¶ added in v0.2.0
func (d *Document) Header(s *Section, hType HeaderType) (*Header, bool)
Header returns the section's header of the given type and whether the section declares one. It resolves the section's own headerReference, so a section that inherits its header from an earlier one reports false.
func (*Document) Headers ¶ added in v0.2.0
Headers returns an editable handle for every header part in the document, ordered by part name. Until this existed a header's content was reachable only obliquely — through Document.Hyperlinks, Document.Images or ReplaceText — and there was no way to add a paragraph to a header that came from the opened file, which left several header-side mutators unreachable. Use Section.Header to find the header of a specific type instead.
func (*Document) Hyperlinks ¶
Hyperlinks returns every hyperlink in the document, in document order, including hyperlinks nested in tables and structured document tags, and those in headers and footers (table-nested ones included).
func (*Document) Images ¶
func (d *Document) Images() []*InlineImage
Images returns every image in the document — inline and floating/anchored — in document order, including images nested in tables, headers, and footers.
func (*Document) InkAnnotations ¶
func (d *Document) InkAnnotations() []InkAnnotation
InkAnnotations returns the document's ink annotations, located through the customXml relationships (in every part's scope) whose target is an InkML part. The result is ordered by (owner, relationship id) for determinism; a part referenced more than once is reported once per referencing relationship.
func (*Document) ListDefinitions ¶
func (d *Document) ListDefinitions() *NumberingManager
ListDefinitions is an alias for Numbering, spelling the manager in terms of the list definitions it builds.
func (*Document) MailMerge ¶
MailMerge returns the document's mail-merge configuration (w:mailMerge in the settings part), or nil when the document is not a mail-merge main document.
func (*Document) MergeFields ¶
MergeFields returns the distinct MERGEFIELD field names present in the document, in first-appearance order. Both simple fields (w:fldSimple) and complex fields (w:fldChar/w:instrText run sequences) are scanned, in paragraphs anywhere in the body and in every header and footer, including paragraphs nested inside tables and content nested inside content controls, hyperlinks and tracked changes. This matches FormFields, which also covers headers and footers, and which uses the same descent.
The complex-field state machine runs over each part as a whole rather than per paragraph, so a field whose begin, instruction and end runs are split across paragraphs — legal per ECMA-376 §17.16.18 and common for IF fields — is still read as one field. Headers and footers are walked in part-name order, so the result is deterministic.
func (*Document) Model3D ¶
Model3D returns the document's embedded 3D models, located through relationships (in every part's scope) whose type names a 3D model or whose target part is typed as a glTF-binary model. The result is ordered by (owner, relationship id) for determinism.
func (*Document) Numbering ¶
func (d *Document) Numbering() *NumberingManager
Numbering returns the manager for the document's numbering definitions, creating the numbering model if the document has none.
func (*Document) OLEObjects ¶
OLEObjects returns the document's embedded OLE objects. Objects are located through the package's oleObject relationships; any remaining /word/embeddings/*.bin parts typed as OLE objects are included as a fallback. The result is ordered by part name for determinism. Extraction is read-only and leaves every part byte-for-byte unchanged on a subsequent save.
func (*Document) Paragraphs ¶
Paragraphs returns all paragraphs in the document body in document order, including paragraphs wrapped in body-level structured document tags.
func (*Document) Protect ¶
func (d *Document) Protect(opts DocumentProtectionOptions)
Protect turns on document protection with the given options, replacing any existing w:documentProtection (and, when ReadOnlyRecommended is set, w:writeProtection) in settings.xml. It works on both created and opened documents; a save regenerates the settings part with the new protection.
Word document protection is a UI guard, not encryption. Even with a password it is trivially removed; do not use it to protect confidential data.
func (*Document) Protection ¶
func (d *Document) Protection() *DocumentProtection
Protection returns the document's edit-enforcement state, or nil when the settings declare neither w:documentProtection nor w:writeProtection.
func (*Document) RejectAllRevisions ¶
RejectAllRevisions rejects every editable revision in the document body: insertions are removed, deletions restored as normal text, and run/paragraph property changes reverted to their recorded old properties. Read-only revision types are left untouched. It returns an error only if a future transform reports one; today it always succeeds.
func (*Document) RemoveCustomProperty ¶
RemoveCustomProperty removes the named custom property, reporting whether it existed.
func (*Document) RemoveDocumentVariable ¶
RemoveDocumentVariable deletes the named document variable and reports whether it was present.
func (*Document) RemoveSource ¶
RemoveSource removes the bibliography source with the given tag, reporting whether one was found and removed.
func (*Document) RemoveVBAProject ¶
func (d *Document) RemoveVBAProject()
RemoveVBAProject removes the document's VBA project part, dropping its content-type override and main-part relationship and flipping the main part back to the regular (non-macro) flavor. It is a no-op on a document that carries no macros.
func (*Document) RemoveWatermark ¶
RemoveWatermark removes any watermark from the document's header furniture. It reports whether a watermark was found and removed.
func (*Document) ReplaceText ¶
ReplaceText performs text replacement across the whole document: every body paragraph (including those nested in tables and structured document tags) and every header and footer. Keys in the replacements map are matched exactly as provided — to replace "{{name}}" with "John", pass map[string]string{"{{name}}": "John"}.
A match may span multiple w:r runs: Word often splits a single logical string across several runs (spell-check state, rsids), so the paragraph's run text is concatenated before matching and the replacement is spliced back in. The replacement inherits the formatting of the first run that contained part of the match; runs before and after the match keep their own formatting. A key is not matched across a line break, tab, field, drawing, or other non-text run, nor across a hyperlink or field boundary — those delimit distinct content.
This mirrors pptx.Presentation.ReplaceText. Empty keys are ignored, and a document with no matching text round-trips byte-for-byte.
func (*Document) Revisions ¶
Revisions returns every tracked change in the document body and in every header and footer part, in document order, descending into tables, hyperlinks, fields, and structured document tags. Insertions, deletions, run/paragraph property changes, and tracked moves (w:moveFrom/w:moveTo) are editable (Accept/Reject transform the document); table, row, cell, and section revisions are reported read-only. Header and footer revisions follow the body revisions, ordered by part name.
Structural revisions are enumerated through the same block descent that allocates their ids, so a table revision inside a block-level content control is reported (it used to be allocated an id it never surfaced), and a w:sectPrChange on a paragraph-level w:sectPr — any mid-document section break edited under track changes — is reported alongside the body-level one (C495).
The returned Revision values reference live document structures. Accept or Reject on one, and any editing between enumerating and applying, can invalidate others in the slice; re-read Revisions after a batch of edits.
func (*Document) Save ¶
Save writes the document to a file. Like SaveTo, it enforces the pre-save validation gate and the round-trip contract documented there.
func (*Document) SaveBytes ¶
SaveBytes writes the document to an in-memory buffer through SaveTo (same validation gate and round-trip contract).
func (*Document) SaveEncrypted ¶
SaveEncrypted saves the document to a file, encrypted with the supplied password using Office's agile encryption (AES-256, SHA-512). The password must not be empty. The resulting file opens in Word with the password, and here with Open and opc.WithPassword.
func (*Document) SaveEncryptedTo ¶
SaveEncryptedTo saves the document to an arbitrary writer, encrypted with the supplied password. It first serializes the document to plain package bytes (running the same validation as SaveTo), then wraps them in an encrypted CFB container.
func (*Document) SaveTo ¶
SaveTo saves the document to an arbitrary writer.
It first runs Validate and refuses to write — returning the Report as an error — when any error-severity finding is present, so a structurally corrupt package is never produced. SaveToUnvalidated bypasses this gate.
Round-trip contract: for a document opened with Open/OpenReader, parts the session never touched are written back byte-for-byte — including a body that was never accessed, which is never even parsed — while touched parts are regenerated from the model. A document built with Create is generated entirely from the model.
When the session changed the document's content, the save records the time in Properties.Modified (docProps/core.xml's dcterms:modified) — and only then, so that saving an unchanged document twice produces identical bytes. Reading the document, however much of it, is not a change. Assigning Properties.Modified yourself takes precedence over the stamp.
func (*Document) SaveToUnvalidated ¶
SaveToUnvalidated saves the document without running the pre-save validation pass. Prefer SaveTo; use this only when a finding is known to be advisory for the caller's use case.
func (*Document) Sections ¶
Sections returns every section in the document in document order: one for each section break (a paragraph carrying w:pPr/w:sectPr) followed by the final body-level section. Unlike DefaultSection, it does not fabricate a body section when none exists; a well-formed document always ends with one.
func (*Document) SetCustomProperty ¶
SetCustomProperty adds or replaces a custom document property. The value must be a string, int/int32/int64, float32/float64, bool, or time.Time (integers are stored as int64 and 32-bit floats as float64). Setting a property on a document that has none creates the docProps/custom.xml part on save.
func (*Document) SetDefaultTabStop ¶
SetDefaultTabStop sets the document's default tab-stop interval in points (w:defaultTabStop), creating the settings part if necessary.
func (*Document) SetDocumentVariable ¶
SetDocumentVariable sets the named document variable, replacing an existing value or appending a new variable, and creating the settings part if necessary.
func (*Document) SetEndnoteProperties ¶
func (d *Document) SetEndnoteProperties(np NoteProperties)
SetEndnoteProperties sets the document-level endnote numbering properties (w:settings/w:endnotePr), creating the settings part if necessary. Separator references are preserved (see SetFootnoteProperties).
func (*Document) SetEvenAndOddHeaders ¶
SetEvenAndOddHeaders enables or disables distinct even-page headers and footers (w:evenAndOddHeaders). Enabling creates the settings part if necessary; disabling removes the flag.
func (*Document) SetFootnoteProperties ¶
func (d *Document) SetFootnoteProperties(np NoteProperties)
SetFootnoteProperties sets the document-level footnote numbering properties (w:settings/w:footnotePr), creating the settings part if necessary. Any separator footnote references (w:footnote children) already present are preserved; the numbering children are regenerated.
func (*Document) SetFrameset ¶
func (d *Document) SetFrameset(def FramesetDef) error
SetFrameset authors the document's web-layout frameset, writing it to the web-settings part (word/webSettings.xml) on save. When the document has no web-settings part one is created, along with its document relationship and content-type override; when it already has one, the existing frameset subtree is replaced (or a frameset is inserted) while every other setting in the part is preserved verbatim. Each frame's SourceTarget becomes an external frame relationship in the web-settings part's .rels.
An unmodified web-settings part round-trips byte-for-byte until the first SetFrameset call.
func (*Document) SetImageWatermark ¶
func (d *Document) SetImageWatermark(imageBytes []byte, opts WatermarkOptions) error
SetImageWatermark stamps a washed-out image watermark across the document's header furniture (see SetTextWatermark for the header selection). The image content type and dimensions are read from imageBytes; PNG, JPEG and GIF are supported. Calling it again replaces the existing watermark.
func (*Document) SetMailMerge ¶
SetMailMerge writes the document's mail-merge configuration (w:mailMerge), creating the settings part if necessary. A nil configuration removes the element, turning the document back into a plain document. Regenerating the element is a modification: the settings part is rewritten on save.
func (*Document) SetSectionImageWatermark ¶
func (d *Document) SetSectionImageWatermark(sec *Section, imageBytes []byte, opts WatermarkOptions) error
SetSectionImageWatermark stamps a washed-out image watermark across the headers of a specific section (see SetSectionTextWatermark for the header selection). Calling it again replaces the section's existing watermark.
func (*Document) SetSectionTextWatermark ¶
func (d *Document) SetSectionTextWatermark(sec *Section, text string, opts WatermarkOptions) error
SetSectionTextWatermark stamps a WordArt text watermark across the headers of a specific section (as returned by Document.Sections or DefaultSection), rather than the document's final section. This allows distinct watermarks per section. The default header of the section is created when absent; existing first-page and even-page headers of the section are covered too. Calling it again replaces the section's existing watermark.
func (*Document) SetTextWatermark ¶
func (d *Document) SetTextWatermark(text string, opts WatermarkOptions) error
SetTextWatermark stamps a WordArt text watermark across the document's header furniture. The watermark is inserted into the default header (created when the document has none) and into any first-page and even-page headers already referenced by the default section, so it shows on every page. Calling it again replaces the existing watermark.
func (*Document) SetVBAProject ¶
SetVBAProject injects or replaces the document's VBA project with the given vbaProject.bin bytes, wiring the content-type override and the main-part relationship and flipping the main part to the macro-enabled flavor (.docm / .dotm) when it is not already macro-enabled. The bytes are stored as-is and written verbatim on save.
Security: the bytes are executable VBA carried opaquely. Injecting a project extracted from another document transplants that document's macros and their trust; only inject bytes from a source you trust.
func (*Document) SetZoom ¶
SetZoom sets the document's view magnification to the given percentage (w:zoom w:percent), creating the settings part if necessary.
func (*Document) SignatureLines ¶
func (d *Document) SignatureLines() []SignatureLine
SignatureLines returns the visible signature lines in the document body, in document order. It reads back the placeholders created by AddSignatureLine (and the equivalent shapes Word writes), reporting the suggested-signer fields; it does not report whether any line has actually been signed.
func (*Document) Sources ¶
Sources returns the bibliography sources stored in the document (word/bibliography/sources.xml), in document order. It returns nil when the document has no bibliography part.
func (*Document) Styles ¶
func (d *Document) Styles() *StyleManager
Styles returns the manager for the document's style definitions. It lazily materializes the styles model — a created document (or one opened without a styles part) gets Word's compact defaults (Normal plus Heading1-9) so that styles added here sit alongside the built-ins that AddHeading references.
func (*Document) Text ¶
Text returns every piece of body text in the document as a single plain string, with no markup, suitable for search, indexing, or LLM ingestion.
The text is assembled deterministically in this order:
- the document body, in document order: paragraphs (including the text of runs nested in hyperlinks, simple fields, tracked insertions, and inline content controls), tables, and block-level content controls;
- each header and each footer (ordered by part name);
- footnotes, then endnotes;
- text boxes (from the body and from headers/footers).
Paragraphs are separated by "\n". Within a table, cells are separated by a tab ("\t") and rows by "\n"; a cell's own paragraphs are joined by a single space so each table row stays on one line. Tracked deletions and math (oMath) text are not included, mirroring the per-element accessors.
One divergence: a table nested inside a block-level content control has its text included, in document order, but as one line per cell paragraph rather than as tab-separated rows — the content control's content is reached as a flat paragraph sequence. Extract such a table through Document.Tables if you need its row and cell structure.
func (*Document) TextBoxes ¶
TextBoxes returns every text box in the document, in document order, including boxes nested in tables, headers, and footers. Both modern DrawingML (wps) text boxes and legacy VML (w:pict/v:textbox) text boxes are returned; each handle exposes the box's text and geometry. Shapes without a text body are not returned.
func (*Document) Theme ¶
func (d *Document) Theme() *dml.ThemeEditor
Theme returns a read/write handle to the document's theme part (word/theme/theme1.xml), the shared DrawingML a:theme model exposed by dml.ThemeEditor. Color-scheme and font-scheme edits made through the handle are written back to the theme part on save; an untouched theme round-trips byte-for-byte from its preserved source bytes.
It returns nil when the document has no theme part — matching pptx's behavior for programmatically created files, whose default theme part is not modeled.
func (*Document) Unprotect ¶
func (d *Document) Unprotect()
Unprotect removes document protection (both w:documentProtection and w:writeProtection), if any.
func (*Document) VBAProject ¶
VBAProject returns the raw bytes of the document's VBA project part (vbaProject.bin), or nil if the document carries no macros. The bytes are the opaque MS-OVBA/CFB blob exactly as stored; spine does not parse them.
func (*Document) Validate ¶
Validate walks the in-memory document model and reports structural problems without saving or re-parsing. Save and SaveTo run it first and refuse to write when any error-severity finding is present; use SaveToUnvalidated to bypass the gate.
The checks are sound (no false positives on Word-accepted packages).
type DocumentEditMode ¶
type DocumentEditMode string
DocumentEditMode is the kind of editing a reader may still perform while document protection is enforced. It is the value of the w:edit attribute of w:documentProtection (ECMA-376 §17.15.1.29).
const ( // EditReadOnly allows no editing at all. EditReadOnly DocumentEditMode = "readOnly" // EditComments allows only adding comments. EditComments DocumentEditMode = "comments" // EditTrackedChanges allows editing but forces tracked changes on. EditTrackedChanges DocumentEditMode = "trackedChanges" // EditForms allows editing only form fields. EditForms DocumentEditMode = "forms" )
type DocumentGrid ¶
type DocumentGrid struct {
// Type selects the grid mode: "default", "lines", "linesAndChars", or
// "snapToChars". Empty leaves the attribute unset.
Type string
// LinePitch is the grid line pitch in twips; CharSpace is the character
// pitch adjustment. Both are raw grid units, not points.
LinePitch int
CharSpace int
}
DocumentGrid describes a section's document grid (w:docGrid), which governs the character/line grid used for East Asian layout.
type DocumentProtection ¶
type DocumentProtection struct {
// contains filtered or unexported fields
}
DocumentProtection is a read-only view of a document's edit-enforcement settings (w:documentProtection, plus w:writeProtection when present). It is the read counterpart of Document.Protect/Unprotect.
Like Excel's sheet and workbook protection, Word's document protection is a UI guard, not encryption: the document is not protected cryptographically and any tool can clear it. HasPassword only reports that a (weak legacy or hashed) password guard is present; the password itself is never exposed.
func (*DocumentProtection) Edit ¶
func (p *DocumentProtection) Edit() DocumentEditMode
Edit reports which editing mode the protection permits (w:edit).
func (*DocumentProtection) Enforced ¶
func (p *DocumentProtection) Enforced() bool
Enforced reports whether the restriction is actually enforced (w:enforcement="1"). A document may declare a restriction while leaving it unenforced.
func (*DocumentProtection) HasPassword ¶
func (p *DocumentProtection) HasPassword() bool
HasPassword reports whether a password guard is present on the document protection (either the legacy hash or a modern hashValue). The password is never exposed.
It is a presence check, not a verification, and the two directions are not symmetric: it returns true after this library's own Protect with a Password, but that guard is the legacy 16-bit obfuscation hash written with no crypt provider attributes (see DocumentProtectionOptions.Password), which Word may not accept as one of its own — its UI may let a user through with an empty password. Treat a true here as "the file declares a password", never as "this document is protected against editing".
func (*DocumentProtection) ReadOnlyRecommended ¶
func (p *DocumentProtection) ReadOnlyRecommended() bool
ReadOnlyRecommended reports whether the document advertises a read-only recommendation (w:writeProtection w:recommended="1").
func (*DocumentProtection) RestrictFormatting ¶
func (p *DocumentProtection) RestrictFormatting() bool
RestrictFormatting reports whether formatting is restricted to a selection of styles (w:formatting="1").
type DocumentProtectionOptions ¶
type DocumentProtectionOptions struct {
// Edit selects which editing the reader may still perform. The zero value
// ("") is treated as EditReadOnly.
Edit DocumentEditMode
// Password, when non-empty, is guarded with Word's legacy 16-bit password
// hash (see the note below). This is obfuscation, not security — it is
// trivially removed and must not be relied on to protect confidential data.
//
// Note on the hash: OOXML's w:documentProtection has no dedicated 16-bit
// password attribute, so Word 2007+ stores a SHA-based verifier in
// w:hash/w:salt with w:cryptAlgorithmSid and friends. This library instead
// writes the simple legacy 16-bit obfuscation hash shared with xlsx
// (crypto.LegacyPasswordHash), base64-encoded into w:hash with no crypt
// provider attributes. The choice keeps a single, well-understood algorithm
// across formats; it is deliberately weak and Word may not treat it as one
// of its own passwords, but the enforcement flag still guards the UI and the
// file stays schema-valid.
Password string
// RestrictFormatting sets w:formatting="1" so that only a selection of
// styles may be applied while protection is enforced.
RestrictFormatting bool
// ReadOnlyRecommended additionally writes w:writeProtection with
// w:recommended="1", advising editors to open the document read-only.
ReadOnlyRecommended bool
}
DocumentProtectionOptions configures Document.Protect. The zero value enforces a read-only restriction on the whole document, mirroring Excel's Sheet.Protect default of locking everything.
type DocumentVariable ¶
DocumentVariable is a single document variable (w:docVar): a name paired with a string value. Document variables are hidden name/value storage used by fields (DOCVARIABLE) and macros.
type FieldType ¶
type FieldType string
FieldType is a Word field instruction for Paragraph.AddField. The predefined constants cover standard document furniture; any other value is passed through verbatim as the field instruction, so callers can emit further field types (e.g. "DATE \\@ \"yyyy-MM-dd\"") without new API.
type Footer ¶
type Footer struct {
// contains filtered or unexported fields
}
Footer represents a document footer.
func (*Footer) AddParagraph ¶
AddParagraph adds a paragraph to the footer (see Header.AddParagraph).
func (*Footer) AddParagraphWithText ¶
AddParagraphWithText adds a paragraph with text to the footer.
func (*Footer) Paragraphs ¶ added in v0.2.0
Paragraphs returns the footer's paragraphs in document order, descending into tables and block-level structured document tags.
type Footnote ¶
type Footnote struct {
// contains filtered or unexported fields
}
Footnote is a footnote or endnote. The ID/Text/Paragraphs accessors work on both note kinds; Document.Footnotes and Document.Endnotes return the two families separately, and Run.AddFootnote / Run.AddEndnote anchor them.
func (*Footnote) ID ¶
ID returns the note's w:id (the value a footnoteReference/endnoteReference points at).
func (*Footnote) Paragraphs ¶
Paragraphs returns the note body paragraphs.
type FormField ¶
type FormField struct {
// Name is the field's bookmark name (w:ffData/w:name/@w:val), used by macros
// and REF fields to address the field. It may be empty.
Name string
// Type is the field kind: text, checkbox, or dropdown.
Type FormFieldType
// Value is the field's current result: the displayed text for a text field,
// "true"/"false" for a checkbox, or the selected entry for a dropdown.
Value string
// Checked reports a checkbox field's state; always false for other kinds.
Checked bool
// Entries lists a dropdown field's choices in order; nil for other kinds.
Entries []string
// Selected is a dropdown field's selected index into Entries; 0 otherwise.
Selected int
// HelpText and StatusText are the optional help/status strings (w:helpText,
// w:statusText); empty when the field declares none.
HelpText string
StatusText string
}
FormField is a legacy Word form field extracted from a document. It pairs the field's w:ffData definition (name, kind, options) with the current result the field displays. Extraction is read-only and leaves the underlying runs byte-for-byte unchanged on a subsequent save.
type FormFieldOptions ¶
type FormFieldOptions struct {
// Type selects the field kind; the empty value means FormFieldText.
Type FormFieldType
// Name is the field's bookmark name (w:ffData/w:name). Optional.
Name string
// HelpText and StatusText populate the optional w:helpText/w:statusText
// (help-key and status-bar prompts). Optional.
HelpText string
StatusText string
// DefaultText is a text field's initial value (w:textInput/w:default) and
// the result shown until the user edits the field.
DefaultText string
// MaxLength caps a text field's length (w:textInput/w:maxLength); 0 means no
// limit.
MaxLength int
// Checked sets a checkbox field's initial state.
Checked bool
// Entries lists a dropdown field's choices in order (w:ddList/w:listEntry).
Entries []string
// Selected is the dropdown's selected index into Entries.
Selected int
}
FormFieldOptions configures a legacy form field created with AddFormField. The zero value is a nameless, enabled text field.
type FormFieldType ¶
type FormFieldType string
FormFieldType classifies a legacy Word form field (the kind inserted from the Developer > Legacy Tools palette), encoded as a complex field whose begin w:fldChar carries a w:ffData definition.
const ( // FormFieldText is a text-input form field (w:textInput, FORMTEXT). FormFieldText FormFieldType = "text" // FormFieldCheckBox is a checkbox form field (w:checkBox, FORMCHECKBOX). FormFieldCheckBox FormFieldType = "checkbox" // FormFieldDropDown is a drop-down list form field (w:ddList, FORMDROPDOWN). FormFieldDropDown FormFieldType = "dropdown" )
type Frame ¶
type Frame struct {
// contains filtered or unexported fields
}
Frame is a single leaf frame (w:frame) of a frameset, displaying the document its source relationship points to.
func (*Frame) Scrollbar ¶
Scrollbar returns the frame's scrollbar setting (w:scrollbar val): "on", "off", or "auto", or "" when unset.
func (*Frame) SourceID ¶
SourceID returns the relationship id (r:id) of the frame's source document (w:sourceFileName), or "" when unset.
func (*Frame) SourceTarget ¶
SourceTarget returns the resolved relationship target of the frame's source document (the URL or part the frame displays), or "" when the relationship cannot be resolved.
type FrameDef ¶
FrameDef describes one leaf frame (a w:frame) of a frameset. Name and Title label the frame; Size is its size (w:sz); Scrollbar is "on", "off", or "auto". SourceTarget is the document the frame displays: SetFrameset creates an external frame relationship to it (a w:sourceFileName r:id), matching how a web-layout frameset references its HTML sources.
type Frameset ¶
type Frameset struct {
// contains filtered or unexported fields
}
Frameset is a web-layout frameset (w:frameset): a recursive split of the window into rows or columns of frames and nested framesets. Frameset reads the existing tree; SetFrameset authors one (regenerating, or newly creating, the web-settings part on save). A web-settings part that this session never touches is preserved verbatim.
func (*Frameset) Frames ¶
Frames returns the leaf frames directly under this frameset, in document order.
func (*Frameset) Layout ¶
Layout returns the split direction (w:frameLayout val): "rows", "cols", or "none", or "" when unset.
type FramesetDef ¶
type FramesetDef struct {
Size string
Layout string
Title string
Framesets []FramesetDef
Frames []FrameDef
}
FramesetDef describes a frameset (a w:frameset) to author with Document.SetFrameset: a window split into rows or columns of nested framesets and leaf frames. Layout is the split direction ("rows", "cols", or "none"); Size is the child-size specification (w:sz, e.g. "*,240"); Title labels the split. Framesets are nested splits; Frames are the leaf frames under this split.
type GroupMember ¶
type GroupMember struct {
// Text is the member's caption; empty for a plain shape. A member with text
// carries a real w:txbxContent body.
Text string
// Shape selects the preset geometry; empty means ShapeRectangle.
Shape ShapeType
// XEMU and YEMU offset the member from the group's top-left corner.
XEMU int64
YEMU int64
// WidthEMU and HeightEMU are the member size in EMU; zero uses the text box
// default (2in x 1in).
WidthEMU int64
HeightEMU int64
// FillColor / NoFill and BorderColor / BorderWidthEMU / NoBorder mirror
// TextBoxOptions: fill and outline styling for the member.
FillColor string
NoFill bool
BorderColor string
BorderWidthEMU int64
NoBorder bool
}
GroupMember describes one shape inside a shape group. Its position is given in the group's child coordinate space (the same EMU space as the group extent), so XEMU/YEMU place the member relative to the group's top-left corner.
type GroupOptions ¶
type GroupOptions struct {
// WidthEMU and HeightEMU are the group extent in EMU (914400 per inch). When
// zero the extent is computed from the members' bounding box.
WidthEMU int64
HeightEMU int64
// Floating anchors the group (positioned relative to the page or paragraph)
// instead of placing it inline in the text flow.
Floating bool
// Anchor positions the group when Floating is set (same semantics as images).
Anchor Anchor
}
GroupOptions configures a shape group created with AddShapeGroup. The zero value produces an inline group whose extent is the bounding box of its members.
type Header ¶
type Header struct {
// contains filtered or unexported fields
}
Header represents a document header.
func (*Header) AddParagraph ¶
AddParagraph adds a paragraph to the header. On a header that came from the opened package this flags the part for regeneration, so the new paragraph is written instead of being masked by the preserved original bytes.
func (*Header) AddParagraphWithText ¶
AddParagraphWithText adds a paragraph with text to the header.
func (*Header) Paragraphs ¶ added in v0.2.0
Paragraphs returns the header's paragraphs in document order, descending into tables and block-level structured document tags. Editing one writes back to the header part on save.
type HeaderType ¶
type HeaderType int
HeaderType identifies the type of header.
const ( HeaderDefault HeaderType = iota HeaderFirst HeaderEven )
type Hyperlink ¶
type Hyperlink struct {
// contains filtered or unexported fields
}
Hyperlink is a hyperlink in a document. Its READ accessors mirror the xlsx and pptx hyperlink APIs so the three formats are symmetric: URL for an external target, Anchor for an internal one (a bookmark name in docx), and Tooltip for the screen-tip; only the anchoring differs by format. Retargeting is not part of that shared surface — none of the three formats has a SetURL or SetAnchor, so a link's destination is fixed once it is created and SetTooltip is the only mutator here.
func (*Hyperlink) Anchor ¶
Anchor returns the hyperlink's internal target — a bookmark name — or "" when the hyperlink is external.
func (*Hyperlink) Runs ¶
Runs returns the runs wrapped by this hyperlink (docx-specific). Each run's Hyperlink() resolves back to this hyperlink, so the display formatting inside a link is reachable — Paragraph.Runs() returns only top-level runs.
func (*Hyperlink) SetTooltip ¶
SetTooltip sets the hyperlink's screen-tip.
func (*Hyperlink) Text ¶
Text returns the hyperlink's display text (docx-specific), concatenated from its child runs.
type InkAnnotation ¶
type InkAnnotation struct {
// PartName is the OPC part name of the InkML part (e.g. "/word/ink/ink1.xml").
PartName string
// ContentType is the part's content type (opc.ContentTypeInk).
ContentType string
// Data is the raw InkML, carried verbatim.
Data []byte
// RelID is the relationship id (the w:contentPart r:id) that references the
// ink part.
RelID string
// Owner is the OPC part name of the part that references the ink (e.g. the
// main document part or a header/footer).
Owner string
}
InkAnnotation is an ink (pen-stroke) annotation extracted from a document. Ink is stored as an InkML content part (application/inkml+xml) referenced by a w:contentPart element through a customXml relationship. The Data bytes are the InkML exactly as stored; spine does not parse the stroke geometry.
Extraction is read-only and leaves every part byte-for-byte unchanged on a subsequent save. Authoring new ink strokes is not yet supported.
type InlineImage ¶
type InlineImage struct {
// contains filtered or unexported fields
}
InlineImage represents an image in a document. Despite the historical name it covers both inline images (in the text flow) and floating/anchored ones (positioned relative to the page); floating is set when the image was added with AddFloatingImage*.
func (*InlineImage) AltText ¶
func (img *InlineImage) AltText() string
AltText returns the image's alternative-text description (the drawing's docPr descr), or "" if it has none.
func (*InlineImage) ContentType ¶
func (img *InlineImage) ContentType() string
ContentType returns the image's MIME content type (e.g. image/png), or "" if it cannot be resolved.
func (*InlineImage) Data ¶
func (img *InlineImage) Data() []byte
Data returns the image's raw bytes, or nil if they cannot be resolved.
func (*InlineImage) Floating ¶
func (img *InlineImage) Floating() bool
Floating reports whether the image is floating/anchored (positioned relative to the page or paragraph) rather than inline in the text flow.
func (*InlineImage) Height ¶
func (img *InlineImage) Height() float64
Height returns the image's display height in points.
func (*InlineImage) HeightEMU ¶
func (img *InlineImage) HeightEMU() int64
HeightEMU returns the image's display height in EMUs.
func (*InlineImage) PartName ¶
func (img *InlineImage) PartName() string
PartName returns the package part name of the image's binary (e.g. /word/media/image1.png), or "" if the relationship cannot be resolved.
func (*InlineImage) SetAltText ¶
func (img *InlineImage) SetAltText(text string)
SetAltText sets the alt text description for the image. For an image read back from an opened document only the drawing's docPr descr attribute is rewritten; the rest of the drawing is left verbatim.
func (*InlineImage) SetSize ¶
func (img *InlineImage) SetSize(widthPt, heightPt float64)
SetSize sets the image size in points. For an image read back from an opened document the wp:extent and the picture's a:xfrm/a:ext are resized in place; everything else in the drawing — its position, wrap, rotation and effects — is left exactly as the producer wrote it.
func (*InlineImage) Width ¶
func (img *InlineImage) Width() float64
Width returns the image's display width in points.
func (*InlineImage) WidthEMU ¶
func (img *InlineImage) WidthEMU() int64
WidthEMU returns the image's display width in EMUs, the OOXML-native unit shared with the xlsx and pptx image readers.
type LineNumbering ¶
type LineNumbering struct {
// CountBy is the increment between numbered lines (every CountBy-th line is
// labeled). Zero means unset (Word treats it as every line).
CountBy int
// Start is the first line number.
Start int
// Distance is the gap between the numbers and the text, in points.
Distance float64
// Restart selects when the count resets: "newPage", "newSection", or
// "continuous". Empty leaves the attribute unset.
Restart string
}
LineNumbering describes a section's line-numbering settings (w:lnNumType).
type ListDefinition ¶
type ListDefinition struct {
// contains filtered or unexported fields
}
ListDefinition is a builder for a custom multi-level numbering definition (a w:abstractNum). Configure its levels, then obtain a ListStyle with ListStyle to apply the definition to paragraphs via Paragraph.SetListStyle.
A definition describes how a list *looks*; the counters live on the numbering instances built from it (ListStyle and RestartedListStyle), which is what makes "restart this list at 1" a matter of allocating a second instance rather than editing the definition.
The builder covers the level properties Word's list dialog exposes (format, level text, start value, font, indent, hanging indent, justification). Level properties the model carries but does not surface here — w:lvlRestart, w:isLgl, w:suff, w:pStyle, w:numStyleLink — are not settable; a definition parsed from an opened package keeps them, since existing definitions are preserved verbatim and never rewritten from this model.
func (*ListDefinition) AbstractNumID ¶
func (ld *ListDefinition) AbstractNumID() int
AbstractNumID returns the definition's abstract numbering id (w:abstractNumId).
func (*ListDefinition) Level ¶
func (ld *ListDefinition) Level(level int) *ListLevel
Level returns the builder for the given level (0-based), creating it with sensible defaults (decimal format, "%n." level text, start 1, and the standard 0.5"-per-level indent with a 0.25" hang) on first access. Levels are kept in ascending order regardless of the order they are first touched.
func (*ListDefinition) ListStyle ¶
func (ld *ListDefinition) ListStyle() *ListStyle
ListStyle registers a numbering instance (w:num) pointing at this definition and returns a ListStyle applicable to paragraphs via Paragraph.SetListStyle. Repeated calls return the same instance.
func (*ListDefinition) RestartedListStyle ¶ added in v0.2.0
func (ld *ListDefinition) RestartedListStyle(level, start int) *ListStyle
RestartedListStyle registers a *second* numbering instance for this definition whose counter for the given level restarts at start (w:num/w:lvlOverride/w:startOverride), and returns a ListStyle for it.
This is how "restart this list at 1" is expressed in WordprocessingML: the abstract definition is shared, but each numbering instance counts independently, and a startOverride resets the instance's counter. Apply the definition's ListStyle to the paragraphs before the restart point and the one returned here to the paragraphs after it:
def := doc.Numbering().AddDefinition() def.SetLevel(0, docx.NumberFormatDecimal, "%1.") first, second := def.ListStyle(), def.RestartedListStyle(0, 1) doc.AddParagraph().SetListStyle(first, 0) // 1. doc.AddParagraph().SetListStyle(first, 0) // 2. doc.AddParagraph().SetListStyle(second, 0) // 1. again
Each call registers a new instance, so a list restarted several times calls it once per restart.
func (*ListDefinition) SetLevel ¶
func (ld *ListDefinition) SetLevel(level int, format NumberFormat, lvlText string) *ListLevel
SetLevel is a shorthand that configures a level's format and level text in one call and returns the level builder for any further tuning.
type ListLevel ¶
type ListLevel struct {
// contains filtered or unexported fields
}
ListLevel is a builder over a single level of a ListDefinition.
func (*ListLevel) SetAlignment ¶
SetAlignment sets how the level text is justified within the indent (w:lvlJc).
func (*ListLevel) SetFont ¶
SetFont sets the font used to render the level text (w:rPr/w:rFonts), used for bullet glyphs such as Symbol or Wingdings.
func (*ListLevel) SetFormat ¶
func (l *ListLevel) SetFormat(format NumberFormat) *ListLevel
SetFormat sets the level's numbering format (w:numFmt), e.g. decimal or bullet.
func (*ListLevel) SetHanging ¶
SetHanging sets the level's hanging indent in points (w:pPr/w:ind@hanging).
func (*ListLevel) SetIndent ¶
SetIndent sets the level's left indentation in points (w:pPr/w:ind@left).
type ListStyle ¶
type ListStyle struct {
// contains filtered or unexported fields
}
ListStyle represents a numbering instance (w:num) that can be applied to paragraphs with Paragraph.SetListStyle. Two paragraphs sharing a ListStyle share one counter; two instances of the same definition count independently, which is what ListDefinition.RestartedListStyle exploits to restart a list.
func (*ListStyle) RestartAt ¶ added in v0.2.0
RestartAt makes this numbering instance restart its counter for the given level at start (w:lvlOverride/w:startOverride). Calling it again for the same level replaces the override; passing a level with no existing override adds one.
It applies only to an instance this session created (AddBulletList, AddNumberedList, ListDefinition.ListStyle / RestartedListStyle). An instance that came from an opened package is round-tripped as raw XML and is not editable here; to restart such a list, build a definition of your own. Restarting an instance that paragraphs already use restarts the whole list, so to restart a list *part-way* through, use ListDefinition.RestartedListStyle and apply it from the restart point on.
type MailMerge ¶
type MailMerge struct {
// MainDocumentType is the kind of merge document
// (w:mainDocumentType), e.g. MailMergeFormLetters or MailMergeEmail.
MainDocumentType string
// DataType is the data-source kind (w:dataType), e.g. "textFile",
// "database", "native", or "spreadsheet".
DataType string
// ConnectString is the data-source connection string (w:connectString).
ConnectString string
// Query is the data-source query (w:query).
Query string
// LinkToQuery indicates the query is stored in an external ODC file
// (w:linkToQuery).
LinkToQuery bool
// ViewMergedData shows merged data instead of field codes
// (w:viewMergedData).
ViewMergedData bool
// Destination is the merge output target (w:destination), e.g.
// "newDocument", "printer", "email", or "fax".
Destination string
// DataSourceRef is the relationship ID (r:id) of the merge data source
// (w:dataSource) when it is an external part.
DataSourceRef string
// HeaderSourceRef is the relationship ID (r:id) of the header data source
// (w:headerSource).
HeaderSourceRef string
// DataSource holds the Office Data Source Object connection (w:odso): the
// source path and the mapping of data-source columns to merge field names.
DataSource *MailMergeDataSource
}
MailMerge describes a document's mail-merge configuration, stored in the settings part (w:mailMerge). Obtain the current configuration from Document.MailMerge and write one back with Document.SetMailMerge.
type MailMergeDataSource ¶
type MailMergeDataSource struct {
// SourceRef is the relationship ID (r:id) of the data-source part (w:src).
SourceRef string
// Table is the table or sheet within the data source (w:table).
Table string
// UDLConnectString is the Universal Data Link connection string (w:udl).
UDLConnectString string
// ConnectionType is the connection kind (w:type), e.g. "database",
// "addressBook", "textFile", or "spreadsheet".
ConnectionType string
// FirstRowHeader indicates the first data row holds column headers (w:fHdr).
FirstRowHeader bool
// ColumnDelimiter is the delimiter character code for a delimited-text
// source (w:colDelim). Zero means unset.
ColumnDelimiter int
// FieldMappings maps data-source columns to standard merge field names.
FieldMappings []MailMergeFieldMapping
}
MailMergeDataSource is the Office Data Source Object (w:odso) inside a mail-merge configuration: where the recipient records live and how the data-source columns map to standard merge field names.
type MailMergeFieldMapping ¶
type MailMergeFieldMapping struct {
// Name is the data-source column name (w:name).
Name string
// MappedName is the standard field this column maps to (w:mappedName).
MappedName string
// Column is the zero-based column index (w:column).
Column int
// Type classifies the mapping (w:type), e.g. "dbColumn" or "null".
Type string
// LanguageID is the LCID for the mapping (w:lid).
LanguageID string
}
MailMergeFieldMapping maps a data-source column to a mail-merge field name (w:fieldMapData).
type Model3D ¶
type Model3D struct {
// PartName is the OPC part name of the 3D model (e.g. "/word/media/model1.glb").
PartName string
// ContentType is the part's content type (usually opc.ContentTypeModel3D).
ContentType string
// Data is the raw glTF-binary model, carried verbatim.
Data []byte
// RelID is the relationship id (the model3D r:embed) that references the
// model part.
RelID string
// Owner is the OPC part name of the part that references the model (e.g. the
// main document part or a header/footer).
Owner string
}
Model3D is an embedded 3D model extracted from a document: an opaque binary glTF asset (typically /word/media/*.glb) referenced by an am3d:model3D element. The Data bytes are the model exactly as stored; spine does not parse the model geometry.
Extraction is read-only and leaves every part byte-for-byte unchanged on a subsequent save. Embedding a new 3D model is not yet supported.
type NoteProperties ¶
type NoteProperties struct {
// Position selects where the notes are placed. For footnotes: "pageBottom",
// "beneathText", "sectEnd", or "docEnd". For endnotes: "sectEnd" or "docEnd".
// Empty leaves the element unset.
Position string
// NumberFormat is the w:numFmt value (e.g. "decimal", "lowerRoman",
// "chicago"). Empty leaves it unset.
NumberFormat string
// NumberStart is the first note number (w:numStart); nil leaves it unset.
NumberStart *int
// Restart selects when the count resets (w:numRestart): "continuous",
// "eachSect", or "eachPage". Empty leaves it unset.
Restart string
}
NoteProperties describes the numbering of footnotes or endnotes for a section (w:footnotePr / w:endnotePr).
type NumberFormat ¶
type NumberFormat string
NumberFormat enumerates the numbering formats a list level can use (the w:numFmt value of a numbering level). The set covers the common formats; any other OOXML value can be passed as NumberFormat("…").
const ( // NumberFormatDecimal numbers levels 1, 2, 3, … NumberFormatDecimal NumberFormat = "decimal" // NumberFormatBullet renders a static bullet glyph (the level text) instead // of a counter. NumberFormatBullet NumberFormat = "bullet" // NumberFormatLowerRoman numbers levels i, ii, iii, … NumberFormatLowerRoman NumberFormat = "lowerRoman" // NumberFormatUpperRoman numbers levels I, II, III, … NumberFormatUpperRoman NumberFormat = "upperRoman" // NumberFormatLowerLetter numbers levels a, b, c, … NumberFormatLowerLetter NumberFormat = "lowerLetter" // NumberFormatUpperLetter numbers levels A, B, C, … NumberFormatUpperLetter NumberFormat = "upperLetter" // NumberFormatOrdinal numbers levels 1st, 2nd, 3rd, … NumberFormatOrdinal NumberFormat = "ordinal" // NumberFormatCardinalText spells the number: one, two, three, … NumberFormatCardinalText NumberFormat = "cardinalText" // NumberFormatOrdinalText spells the ordinal: first, second, third, … NumberFormatOrdinalText NumberFormat = "ordinalText" // NumberFormatNone renders no counter. NumberFormatNone NumberFormat = "none" )
type NumberingManager ¶
type NumberingManager struct {
// contains filtered or unexported fields
}
NumberingManager provides create access to custom list/numbering definitions (word/numbering.xml). Obtain one with Document.Numbering (or the ListDefinitions alias).
Definitions added here layer on top of any numbering the document already carried: existing definitions are preserved verbatim (so an unmodified part round-trips byte-for-byte), and new abstract/instance definitions are appended in schema position.
func (*NumberingManager) AddDefinition ¶
func (nm *NumberingManager) AddDefinition() *ListDefinition
AddDefinition creates a new, empty abstract numbering definition and returns a builder for it. The definition is registered immediately; configuring its levels through the returned builder mutates it in place.
type OLEEmbedOptions ¶
type OLEEmbedOptions struct {
// WidthEMU and HeightEMU are the display size in EMU (914400 per inch). When
// zero a default of 1in x 1in is used.
WidthEMU int64
HeightEMU int64
// Icon is the presentation image shown in place of the object (PNG, EMF, or
// WMF bytes). When empty a 1x1 transparent PNG placeholder is embedded.
Icon []byte
// IconContentType is the content type of Icon (e.g. opc.ContentTypePNG,
// opc.ContentTypeEMF). Required when Icon is set; ignored otherwise.
IconContentType string
// DisplayAsIcon marks the object with DrawAspect="Icon" (shown as a small
// program icon) instead of DrawAspect="Content".
DisplayAsIcon bool
}
OLEEmbedOptions configures an embedded OLE object created with AddOLEObject. The zero value embeds the object displayed at 1in x 1in with a transparent placeholder icon, shown as content (not iconized).
type OLEObject ¶
type OLEObject struct {
// Name is the OPC part name of the embedded object (e.g.
// "/word/embeddings/oleObject1.bin").
Name string
// ContentType is the part's content type. Embedded objects are usually
// typed opc.ContentTypeOLEObject, but a specific server may use its own
// (e.g. a binary Excel worksheet).
ContentType string
// Data is the raw embedded object, carried verbatim.
Data []byte
// ProgID is the OLE server programmatic identifier declared by the
// referencing element (e.g. "Excel.Sheet.12"), or "" when the document
// does not declare one in a form spine recognizes.
ProgID string
}
OLEObject is an embedded OLE object extracted from a document: an opaque binary part (typically /word/embeddings/oleObjectN.bin) plus the metadata needed to identify it. The Data bytes are the object exactly as stored; spine does not parse the embedded OLE/CFB stream.
type Orientation ¶
type Orientation int
Orientation represents page orientation.
const ( OrientationPortrait Orientation = iota OrientationLandscape )
type PageBorders ¶
type PageBorders struct {
// OffsetFrom selects the reference edge for border offsets: "page" measures
// from the page edge, "text" from the text. Empty leaves the attribute unset.
OffsetFrom string
Top, Left, Bottom, Right *Border
}
PageBorders describes a section's page borders (w:pgBorders). Each side is nil when that edge has no border.
type PageMargins ¶
type PageMargins struct {
Top, Bottom, Left, Right float64
}
PageMargins represents the page margins in points.
type PageNumbering ¶
PageNumbering describes the section's page-number format and starting value (w:pgNumType). Format is one of the PageNumber* values (or "" for unset), and Start is the first page number for the section (nil when unset).
type Paragraph ¶
type Paragraph struct {
// contains filtered or unexported fields
}
Paragraph represents a paragraph in a Word document.
func (*Paragraph) AddBookmark ¶
AddBookmark brackets the whole paragraph with a bookmark of the given name, allocating the next free numeric id. An internal hyperlink can target it by name.
func (*Paragraph) AddChart ¶
AddChart inserts an inline chart into a new run at the end of the paragraph, in the text flow like an inline image. The chart's data is written to an embedded workbook (word/embeddings/…xlsx) that the chart part references, so Office can edit the values.
The chart is copied, so the caller's *chart.Chart is left untouched and one chart value can be added to several documents (or to a workbook) without the last host's sheet name leaking into the others.
func (*Paragraph) AddCitation ¶
AddCitation appends an in-text citation to the paragraph: a CITATION field (w:fldSimple) referencing the bibliography source with the given tag, together with a cached-result run Word replaces when it formats the citation from the active bibliography style. The returned Run holds the placeholder result; format it to style the rendered citation.
The source need not exist yet — a citation may precede its AddSource call — but when it does exist the placeholder is built from its author and year (e.g. "(Smith, 2020)"); otherwise the tag is shown.
doc.AddSource(docx.Source{Tag: "Smi20", Author: "Smith, John", Title: "A Book", Year: "2020"})
p := doc.AddParagraph()
p.AddText("As shown ")
p.AddCitation("Smi20")
func (*Paragraph) AddComment ¶
AddComment attaches a comment authored by author with the given body text, anchored over the whole paragraph's content. The returned handle can be used to reply, resolve, or set initials.
Comments belong to the main document story: Word does not display a comment anchored in a header or footer, and the reply/anchor machinery here resolves anchors over the body only, so a comment added to a header paragraph is written but never reachable through Reply or AnchorText.
func (*Paragraph) AddContentControl ¶
func (p *Paragraph) AddContentControl(tag, value string) *ContentControl
AddContentControl appends an inline rich-text content control to the paragraph, carrying the given tag and holding value as its content.
func (*Paragraph) AddField ¶
AddField appends a simple field (w:fldSimple) with the given instruction to the paragraph, together with a cached-result run that Word replaces when it recalculates fields (page fields recalculate automatically on repagination). The returned Run holds the cached result; format it to style the field's rendered text:
p := footer.AddParagraph()
p.AddText("Page ")
p.AddField(docx.FieldPage)
p.AddText(" of ")
p.AddField(docx.FieldNumPages)
func (*Paragraph) AddFormField ¶
func (p *Paragraph) AddFormField(opts FormFieldOptions) *Run
AddFormField appends a legacy Word form field to the paragraph and returns the run that holds the field's displayed result (format it to style the field). The field is emitted as the standard begin/separate/end w:fldChar run sequence with a w:ffData definition on the begin character, so Word treats it as a fillable form field and Document.FormFields() reports it after a save/open round trip.
func (*Paragraph) AddHyperlink ¶
AddHyperlink appends a hyperlinked run displaying text and pointing at the external URL. It allocates a w:hyperlink wrapping the run with an r:id that resolves to an External relationship (RelTypeHyperlink) in the part's relationships.
func (*Paragraph) AddInsertedRun ¶
AddInsertedRun appends a tracked insertion to the paragraph: a run carrying text wrapped in a w:ins element attributed to author, dated to the current time (UTC). The returned Run wraps the inserted run, so the caller can format it further (bold, color, ...). The insertion is enumerated by Document.Revisions and transformed by Accept/Reject: accepting keeps the text as a normal run, rejecting removes it. For deterministic output (tests), use AddInsertedRunWithDate.
func (*Paragraph) AddInsertedRunWithDate ¶
AddInsertedRunWithDate is AddInsertedRun with an explicit revision timestamp, recorded in the w:date attribute (converted to UTC). Passing a fixed date makes the emitted markup deterministic.
func (*Paragraph) AddInternalHyperlink ¶
AddInternalHyperlink appends a hyperlinked run displaying text and pointing at an in-document bookmark (w:anchor). No relationship is created; compose it with AddBookmark to link to a bookmark added in the same session.
func (*Paragraph) AddMath ¶
AddMath appends a math zone (m:oMath) to the paragraph. The typed model is marshaled once, up front, and stored in the same raw-captured form the parser produces, so the document's byte-fidelity machinery is untouched; the document marshaler declares the math namespace on the root when math is present.
func (*Paragraph) AddMathPara ¶
AddMathPara appends a math paragraph (m:oMathPara) to the paragraph (see AddMath).
func (*Paragraph) AddMergeField ¶
AddMergeField appends a MERGEFIELD simple field (w:fldSimple) that inserts the named data-source column when the document is merged, together with a placeholder result run showing «name» until Word performs the merge. The returned Run holds the placeholder result; format it to style the merged value. A name containing whitespace is quoted in the field instruction so it parses as a single field argument, matching what Word writes.
p := doc.AddParagraph()
p.AddText("Dear ")
p.AddMergeField("FirstName")
p.AddText(",")
func (*Paragraph) AddMoveFromRun ¶
AddMoveFromRun appends the source half of a tracked move to the paragraph: a run carrying text wrapped in w:moveFrom and bracketed by move range markers carrying name, all attributed to author and dated to the current time (UTC). Author the matching destination with AddMoveToRun using the same name. The move reads back through Document.Revisions (as RevisionMoveFrom) and is transformed by Accept/Reject. Use AddMoveFromRunWithDate for a fixed timestamp.
func (*Paragraph) AddMoveFromRunWithDate ¶
AddMoveFromRunWithDate is AddMoveFromRun with an explicit revision timestamp (recorded in UTC), for deterministic output.
func (*Paragraph) AddMoveToRun ¶
AddMoveToRun appends the destination half of a tracked move to the paragraph: a run carrying text wrapped in w:moveTo and bracketed by move range markers carrying name, attributed to author and dated to the current time (UTC). Pair it with AddMoveFromRun using the same name. The move reads back through Document.Revisions (as RevisionMoveTo) and is transformed by Accept/Reject. Use AddMoveToRunWithDate for a fixed timestamp.
func (*Paragraph) AddMoveToRunWithDate ¶
AddMoveToRunWithDate is AddMoveToRun with an explicit revision timestamp (recorded in UTC), for deterministic output.
func (*Paragraph) AddOLEObject ¶
func (p *Paragraph) AddOLEObject(data []byte, progID string, opts OLEEmbedOptions) (*OLEObject, error)
AddOLEObject embeds an OLE object as a package part and inserts a w:object reference (a VML v:shape presentation image plus an o:OLEObject descriptor) into a new run at the end of the paragraph. data is the object stream (an OLE/CFB compound file) stored verbatim as /word/embeddings/oleObjectN.bin; progID names the server (e.g. "Excel.Sheet.12"). A presentation icon is embedded as an image part and referenced by the shape. The embedded object is reported by Document.OLEObjects() after a save/open round trip.
func (*Paragraph) AddShape ¶
func (p *Paragraph) AddShape(text string, opts TextBoxOptions) *TextBox
AddShape inserts a basic DrawingML shape (rectangle, ellipse, rounded rectangle, or line — see opts.Shape) into a new run at the end of the paragraph, with optional text. It shares the text box drawing path; pass an empty text for a shape with no caption.
func (*Paragraph) AddShapeGroup ¶
func (p *Paragraph) AddShapeGroup(opts GroupOptions, members ...GroupMember) *TextBox
AddShapeGroup inserts a DrawingML shape group (a wpg:wgp holding several wps shapes/text boxes) into a new run at the end of the paragraph. Each member is positioned in the group's child coordinate space. The group needs no extra parts or relationships, so it round-trips like a text box. The returned handle reports the group extent and the members' joined text.
func (*Paragraph) AddSignatureLine ¶
func (p *Paragraph) AddSignatureLine(opts SignatureLineOptions) *Run
AddSignatureLine appends an inline signature line to the paragraph: a VML shape carrying an o:signatureline element (the "Microsoft Office Signature Line" object). It creates the visible placeholder only; signing it is the separate package-signing feature (opc.SignPackage). The returned Run holds the shape.
func (*Paragraph) AddTabStop ¶
AddTabStop appends a tab stop at the given position (in points) with the given alignment and leader. A zero Alignment defaults to a left tab; a zero (or TabLeaderNone) Leader draws no leader.
func (*Paragraph) AddText ¶
AddText appends a new run containing text to the paragraph and returns it. It is shorthand for AddRun followed by SetText.
func (*Paragraph) AddTextBox ¶
func (p *Paragraph) AddTextBox(text string, opts TextBoxOptions) *TextBox
AddTextBox inserts a DrawingML text box into a new run at the end of the paragraph. The box carries the given text (split into one paragraph per line) and honors the size, geometry, fill, and border in opts. Inline by default; set opts.Floating to anchor it. The box needs no extra parts or relationships, so it round-trips through save/open like an image drawing.
func (*Paragraph) AddWordArt ¶
func (p *Paragraph) AddWordArt(text string, opts WordArtOptions) *TextBox
AddWordArt inserts a WordArt shape into a new run at the end of the paragraph. A WordArt shape is a DrawingML (wps) text effect: a borderless, fill-less shape whose text carries a solid fill and an optional preset text warp (opts.Warp). Inline by default; set opts.Floating to anchor it. The shape needs no extra parts or relationships, so it round-trips like a text box, and its text is reported by Document.TextBoxes().
func (*Paragraph) Alignment ¶
Alignment returns the paragraph alignment, or AlignmentLeft when the paragraph declares none — which conflates "unset, so inherited from the style" with an explicit left alignment. Use AlignmentOK to tell them apart.
func (*Paragraph) AlignmentOK ¶ added in v0.2.0
AlignmentOK returns the paragraph's own alignment (w:jc) and whether it declares one. It is the ok-bool form the newer getters use; Alignment keeps the older single-value shape. An unrecognized w:jc value (there are a dozen beyond the four this package models — distribute, thaiDistribute, ...) reports AlignmentLeft with ok true: the paragraph does declare an alignment, it is just not one this API can name.
func (*Paragraph) Borders ¶
func (p *Paragraph) Borders() (ParagraphBorders, bool)
Borders returns the paragraph's borders (w:pBdr) and whether the element is present.
func (*Paragraph) Clear ¶
func (p *Paragraph) Clear()
Clear removes all runs from the paragraph, including their entries in the recorded child order, so a later AddRun does not resolve a stale reference to the new run and duplicate it. Hyperlinks and other non-run children are kept — use SetText to replace everything.
Relationships referenced only by the removed runs are reclaimed (C407).
func (*Paragraph) ClearBorders ¶
func (p *Paragraph) ClearBorders()
ClearBorders removes the paragraph's w:pBdr element.
func (*Paragraph) ClearShading ¶
func (p *Paragraph) ClearShading()
ClearShading removes the paragraph's w:shd element.
func (*Paragraph) ClearTabStops ¶
func (p *Paragraph) ClearTabStops()
ClearTabStops removes all explicit tab stops from the paragraph.
func (*Paragraph) Hyperlinks ¶
Hyperlinks returns the hyperlinks directly in this paragraph, in document order.
func (*Paragraph) MathParas ¶
MathParas returns the paragraph's math paragraphs (m:oMathPara children, Word's container for display equations), parsed on demand into typed common/omml models (see MathZones).
func (*Paragraph) MathZones ¶
MathZones returns the paragraph's math zones (m:oMath children), parsed on demand into typed common/omml models from the raw-captured bytes the document model stores. The returned values are snapshots: mutating them does not change the document — write math back with AddMath. Display equations wrapped in a math paragraph (m:oMathPara) are returned by MathParas instead.
func (*Paragraph) RemoveListStyle ¶
func (p *Paragraph) RemoveListStyle()
RemoveListStyle removes any list style from the paragraph.
func (*Paragraph) SetAlignment ¶
SetAlignment sets the paragraph alignment.
func (*Paragraph) SetBorders ¶
func (p *Paragraph) SetBorders(b ParagraphBorders)
SetBorders sets the paragraph's borders (w:pBdr), replacing any existing element.
func (*Paragraph) SetIndentFirstLine ¶
SetIndentFirstLine sets the first-line indent in points.
func (*Paragraph) SetIndentHanging ¶
SetIndentHanging sets the hanging indent in points.
func (*Paragraph) SetIndentLeft ¶
SetIndentLeft sets the left indentation in points.
func (*Paragraph) SetIndentRight ¶
SetIndentRight sets the right indentation in points.
func (*Paragraph) SetKeepTogether ¶
SetKeepTogether sets whether the paragraph lines should be kept together on one page.
func (*Paragraph) SetKeepWithNext ¶
SetKeepWithNext sets whether the paragraph should be kept with the next paragraph.
func (*Paragraph) SetLineSpacing ¶
SetLineSpacing sets proportional line spacing. 1.0 = single, 1.5, 2.0, etc. Internally this uses lineRule="auto" with the value in 240ths of a line.
func (*Paragraph) SetLineSpacingExact ¶
SetLineSpacingExact sets exact line spacing in points.
func (*Paragraph) SetListStyle ¶
SetListStyle applies a list style to the paragraph at the given level (0-based).
func (*Paragraph) SetPageBreakBefore ¶
SetPageBreakBefore sets whether a page break should occur before the paragraph.
func (*Paragraph) SetShading ¶
SetShading sets the paragraph's background fill to the given hex color (w:pPr/w:shd with w:val="clear"). Passing "" removes the shading.
func (*Paragraph) SetSpaceAfter ¶
SetSpaceAfter sets the spacing after the paragraph in points.
func (*Paragraph) SetSpaceBefore ¶
SetSpaceBefore sets the spacing before the paragraph in points.
func (*Paragraph) SetText ¶
SetText sets the text content, replacing ALL content children — runs, hyperlinks, structured document tags, tracked changes, fields, and raw-preserved inline elements — so no stale text (e.g. hyperlink display text) survives next to the new content. Paragraph properties are kept.
Relationships that only the removed content referenced (a hyperlink's External rel, an image's r:embed, and any media part added in this session that nothing else points at) are reclaimed, so repeatedly filling a template no longer accretes dead relationships (C407).
func (*Paragraph) Shading ¶
Shading returns the paragraph's background fill color (w:pPr/w:shd@w:fill), or "" when unset.
func (*Paragraph) SpaceAfter ¶
SpaceAfter returns the spacing after the paragraph in points.
func (*Paragraph) SpaceBefore ¶
SpaceBefore returns the spacing before the paragraph in points.
type ParagraphBorders ¶
type ParagraphBorders struct {
Top, Left, Bottom, Right, Between, Bar *Border
}
ParagraphBorders describes the borders drawn around a paragraph (w:pBdr). Each side is nil when that edge has no border. Between is the border drawn between consecutive paragraphs that share the same border settings, and Bar is the border to the left of the text.
type Revision ¶
type Revision struct {
// contains filtered or unexported fields
}
Revision is a single tracked change in a document: an insertion, deletion, or property change made with Word's Track Changes turned on. Read its metadata with Author, Date, Type, and Text; apply or discard it with Accept or Reject.
Revisions are enumerated over the main document body and the header and footer parts, including content nested in tables, hyperlinks, fields, and structured document tags. Tracked moves (w:moveFrom/w:moveTo) are enumerated and transformed; their range markers (w:moveFromRangeStart, ...) are preserved but left in place across accept/reject.
func (*Revision) Accept ¶
Accept applies the revision to the document, transforming its content: an insertion becomes normal text, a deletion is removed, and a property change keeps its new properties (dropping the change record). It returns an error for a read-only revision type (see Editable), and ErrRevisionStale when the revision's content is no longer where it was enumerated.
func (*Revision) Author ¶
Author returns the author recorded on the revision (w:author), or an empty string when none was recorded.
func (*Revision) Date ¶
Date returns the timestamp recorded on the revision (w:date, an ISO-8601 string), or an empty string when none was recorded.
func (*Revision) Editable ¶
Editable reports whether Accept and Reject can transform this revision. Read-only revision types (section/table/row/cell property changes, cell merges, row/cell insertions and deletions) return false.
func (*Revision) MoveName ¶
MoveName returns the paired move name recorded on the enclosing range marker for a tracked-move revision (RevisionMoveFrom/RevisionMoveTo), linking the source and destination halves. It is empty for other revision types and when the name could not be resolved.
func (*Revision) Reject ¶
Reject discards the revision, transforming its content: an insertion is removed, a deletion is restored as normal text, and a property change reverts to the recorded old properties (dropping the change record). It returns an error for a read-only revision type (see Editable), and ErrRevisionStale when the revision's content is no longer where it was enumerated.
type RevisionType ¶
type RevisionType string
RevisionType names the kind of a tracked change (a Word revision).
const ( // RevisionInsertion is inserted content (w:ins). Accept keeps it as normal // text; Reject removes it. RevisionInsertion RevisionType = "insertion" // RevisionDeletion is deleted content (w:del/w:delText). Accept removes it; // Reject restores it as normal text. RevisionDeletion RevisionType = "deletion" // RevisionRunFormat is a run-property change (w:rPrChange). Accept keeps the // new formatting; Reject reverts to the recorded old formatting. RevisionRunFormat RevisionType = "runFormat" // RevisionParagraphFormat is a paragraph-property change (w:pPrChange). // Accept keeps the new properties; Reject reverts to the recorded old ones. RevisionParagraphFormat RevisionType = "paragraphFormat" // RevisionMoveFrom is the source half of a tracked move (w:moveFrom): the // content in the location text was moved away from. Accept drops it (the // text left this location); Reject restores it as normal text. RevisionMoveFrom RevisionType = "moveFrom" // RevisionMoveTo is the destination half of a tracked move (w:moveTo): the // content in the location text was moved to. Accept keeps it as normal text // (the text arrived here); Reject removes it. RevisionMoveTo RevisionType = "moveTo" // RevisionSectionFormat is a section-property change (w:sectPrChange). RevisionSectionFormat RevisionType = "sectionFormat" // RevisionTableFormat is a table-property change (w:tblPrChange). RevisionTableFormat RevisionType = "tableFormat" // RevisionRowFormat is a table-row-property change (w:trPrChange). RevisionRowFormat RevisionType = "rowFormat" // RevisionCellFormat is a table-cell-property change (w:tcPrChange). RevisionCellFormat RevisionType = "cellFormat" // RevisionRowInsertion is an inserted table row (w:trPr/w:ins). RevisionRowInsertion RevisionType = "rowInsertion" // RevisionRowDeletion is a deleted table row (w:trPr/w:del). RevisionRowDeletion RevisionType = "rowDeletion" // RevisionCellInsertion is an inserted table cell (w:tcPr/w:cellIns). RevisionCellInsertion RevisionType = "cellInsertion" // RevisionCellDeletion is a deleted table cell (w:tcPr/w:cellDel). RevisionCellDeletion RevisionType = "cellDeletion" // RevisionCellMerge is a cell-merge revision (w:tcPr/w:cellMerge). RevisionCellMerge RevisionType = "cellMerge" )
type Run ¶
type Run struct {
// contains filtered or unexported fields
}
Run represents a run of text with consistent formatting.
func (*Run) AddComment ¶
AddComment attaches a comment anchored over this single run (docx-specific range-precise form). It returns nil, adding no comment, if the run is not a direct child run of its paragraph (for example one from Hyperlink.Runs): range markers cannot be spliced around such a run, and creating the comment anyway left comments.xml carrying an entry with no document anchor that Word never displays (C403 — the same guarantee AddCommentOnRange already made).
func (*Run) AddEndnote ¶
AddEndnote inserts an endnote reference in the run stream right after this run and appends the note to word/endnotes.xml, creating that part if absent (see AddFootnote).
func (*Run) AddFloatingImage ¶
func (r *Run) AddFloatingImage(path string, anchor Anchor) (*InlineImage, error)
AddFloatingImage adds a floating (page/paragraph-anchored) image from a file path, positioned by anchor. SVG is supported with a transparent fallback. The file's bytes are validated as for AddImage.
func (*Run) AddFloatingImageFromBytes ¶
func (r *Run) AddFloatingImageFromBytes(data []byte, contentType string, anchor Anchor) (*InlineImage, error)
AddFloatingImageFromBytes adds a floating image from raw bytes, positioned by anchor (e.g. a cover-page logo or a behind-text watermark). The bytes are validated as for AddImageFromBytes.
func (*Run) AddFloatingSVGImage ¶
func (r *Run) AddFloatingSVGImage(svgData, fallbackData []byte, fallbackContentType string, anchor Anchor) (*InlineImage, error)
AddFloatingSVGImage adds a floating SVG image with a caller-supplied raster fallback, positioned by anchor.
func (*Run) AddFootnote ¶
AddFootnote inserts a footnote reference in the run stream right after this run and appends the note (with the given body text) to word/footnotes.xml, creating that part — with its relationship, content-type override, and the mandatory separator notes — if the document did not already have it.
func (*Run) AddImage ¶
func (r *Run) AddImage(path string) (*InlineImage, error)
AddImage adds an inline image from a file path to the run. SVG files are supported and embedded with a transparent raster fallback (use AddSVGImage to supply your own fallback).
The file's bytes must actually be a PNG, JPEG, GIF or SVG: an unreadable or mislabelled file is rejected here rather than written into the package as a media part no reader can render (C441).
func (*Run) AddImageFromBytes ¶
func (r *Run) AddImageFromBytes(data []byte, contentType string) (*InlineImage, error)
AddImageFromBytes adds an inline image from raw bytes to the run. Pass an "image/svg+xml" content type to embed an SVG (with a transparent raster fallback).
The bytes must actually be an image of the declared kind's family (PNG, JPEG or GIF for a raster content type, an <svg> document for the SVG one); unrecognizable data is rejected here rather than saved as a corrupt media part (C441).
func (*Run) AddSVGImage ¶
func (r *Run) AddSVGImage(svgData, fallbackData []byte, fallbackContentType string) (*InlineImage, error)
AddSVGImage adds an inline SVG image from bytes with a caller-supplied raster fallback (shown by viewers that cannot render SVG). Use AddImageFromBytes with an "image/svg+xml" content type for the transparent-fallback shorthand.
func (*Run) AddSymbol ¶
AddSymbol appends a symbol glyph (w:sym) to the run: a single character drawn from a specific symbol font, addressed by the font name and the character's code point as a hex string (e.g. font "Wingdings", char "F0E0"). The 0xF000 offset Word uses for symbol fonts is part of the stored value and is not added here.
func (*Run) CharacterSpacing ¶
CharacterSpacing returns the additional character spacing in points (w:spacing). Positive values expand, negative values condense. Returns 0 when unset.
func (*Run) Clear ¶
func (r *Run) Clear()
Clear removes all content from the run. Relationships referenced only by the removed content — a drawing's r:embed, an OLE object's r:id — are reclaimed, along with any media part added in this session that nothing else points at (C407).
func (*Run) ClearBold ¶
func (r *Run) ClearBold()
ClearBold removes the run's explicit bold setting so it inherits from the paragraph/style.
func (*Run) ClearCaps ¶
func (r *Run) ClearCaps()
ClearCaps removes the run's explicit all-capitals setting so it inherits.
func (*Run) ClearItalic ¶
func (r *Run) ClearItalic()
ClearItalic removes the run's explicit italic setting so it inherits.
func (*Run) ClearSmallCaps ¶
func (r *Run) ClearSmallCaps()
ClearSmallCaps removes the run's explicit small-capitals setting so it inherits from the style.
func (*Run) ClearStrike ¶
func (r *Run) ClearStrike()
ClearStrike removes the run's explicit strikethrough setting so it inherits.
func (*Run) Highlight ¶
Highlight returns the run's highlight color name (w:highlight, a named ST_HighlightColor value such as "yellow"), or an empty string when none.
func (*Run) Hyperlink ¶
Hyperlink returns the hyperlink wrapping this run, or nil when the run is not inside a hyperlink. Runs() alone cannot reach hyperlinked text; this exposes the URL that was otherwise invisible.
func (*Run) Kerning ¶
Kerning returns the minimum font size in points at which kerning is applied (w:kern). Returns 0 when unset.
func (*Run) MarkDeleted ¶
MarkDeleted wraps an existing run in a tracked deletion (w:del) attributed to author, dated to the current time (UTC), converting the run's text (w:t) to deletion text (w:delText). The run must be a top-level run of its paragraph; on a run that is not a direct paragraph child (for example one from Hyperlink.Runs) the call is a no-op that leaves the run unchanged — its text is not converted to w:delText, so no schema-invalid w:delText is emitted outside a w:del. It returns the run so calls can be chained. The result reads back through Document.Revisions and is transformed by Accept/Reject: accepting removes the text, rejecting restores it as a normal run. Use MarkDeletedWithDate for a fixed timestamp.
func (*Run) MarkDeletedWithDate ¶
MarkDeletedWithDate is MarkDeleted with an explicit revision timestamp (recorded in UTC), for deterministic output.
func (*Run) MarkInserted ¶
MarkInserted wraps an existing run in a tracked insertion (w:ins) attributed to author, dated to the current time (UTC). The run must be a top-level run of its paragraph (as returned by Paragraph.Runs or Paragraph.AddRun); on a run that is not a direct paragraph child (for example one from Hyperlink.Runs) the call is a no-op that leaves the run unchanged. It returns the run so calls can be chained. The result reads back through Document.Revisions and is transformed by Accept/Reject. Use MarkInsertedWithDate for a fixed timestamp.
func (*Run) MarkInsertedWithDate ¶
MarkInsertedWithDate is MarkInserted with an explicit revision timestamp (recorded in UTC), for deterministic output.
func (*Run) Position ¶
Position returns the run's vertical text position in points (w:position). Positive values raise the text, negative values lower it. Returns 0 when unset.
func (*Run) SetBold ¶
SetBold sets the run's bold state explicitly. Unlike a plain toggle, SetBold(false) emits an explicit "off" (w:b w:val="false") so text that inherits bold from its style is actually un-bolded; use ClearBold to inherit the style's value instead.
func (*Run) SetCaps ¶
SetCaps sets the run's all-capitals state explicitly. SetCaps(false) emits an explicit "off"; use ClearCaps to inherit from the style.
func (*Run) SetCharacterSpacing ¶
SetCharacterSpacing sets the additional character spacing in points (w:spacing). Positive values expand the spacing, negative values condense it.
func (*Run) SetFontSize ¶
SetFontSize sets the font size in points.
func (*Run) SetHighlight ¶
SetHighlight sets the run's highlight to a named color (e.g. "yellow", "green", "cyan"). Passing an empty string or "none" removes the highlight.
func (*Run) SetItalic ¶
SetItalic sets the run's italic state explicitly. SetItalic(false) emits an explicit "off"; use ClearItalic to inherit from the style.
func (*Run) SetKerning ¶
SetKerning sets the minimum font size in points at which the run's characters are kerned (w:kern). A value of 0 disables kerning.
func (*Run) SetPosition ¶
SetPosition sets the run's vertical text position in points (w:position). Positive values raise the text above the baseline, negative values lower it.
func (*Run) SetSmallCaps ¶
SetSmallCaps sets the run's small-capitals state explicitly. SetSmallCaps(false) emits an explicit "off"; use ClearSmallCaps to inherit.
func (*Run) SetStrike ¶
SetStrike sets the run's strikethrough state explicitly. SetStrike(false) emits an explicit "off"; use ClearStrike to inherit from the style.
func (*Run) SetStyle ¶
SetStyle applies the character style with the given id to the run (w:rStyle), complementing the paragraph and style-definition APIs. Passing "" removes the character style so the run inherits from its paragraph style.
func (*Run) SetSubscript ¶
SetSubscript sets the run as subscript (on) or baseline (off).
func (*Run) SetSuperscript ¶
SetSuperscript sets the run as superscript (on) or baseline (off).
func (*Run) SetUnderline ¶
SetUnderline sets whether the run is underlined.
func (*Run) SetUnderlineColor ¶
SetUnderlineColor sets the run's underline color as a hex string (e.g. "FF0000"). It creates a single underline if the run has none yet, so the color has a line to apply to.
func (*Run) SetUnderlineStyle ¶
func (r *Run) SetUnderlineStyle(style UnderlineStyle)
SetUnderlineStyle sets the run's underline line style (e.g. UnderlineDouble, UnderlineWavy). It is the richer counterpart to SetUnderline(bool): the plain boolean setter is preserved. Any underline color already set is kept.
func (*Run) SetVerticalAlign ¶
func (r *Run) SetVerticalAlign(align enum.VerticalAlignRun)
SetVerticalAlign sets the run as superscript, subscript, or baseline (w:vertAlign). Passing an empty string clears the setting so the run inherits its vertical alignment.
func (*Run) Style ¶
Style returns the run's character style id (w:rStyle), or "" when the run applies no character style.
func (*Run) Superscript ¶
Superscript reports whether the run is rendered as superscript.
func (*Run) UnderlineColor ¶
UnderlineColor returns the run's underline color as a hex string (w:u@color), or an empty string when none is set.
func (*Run) UnderlineStyle ¶
func (r *Run) UnderlineStyle() UnderlineStyle
UnderlineStyle returns the run's underline line style (the w:u@val token), or an empty string when the run sets no underline.
func (*Run) VerticalAlign ¶
func (r *Run) VerticalAlign() enum.VerticalAlignRun
VerticalAlign returns the run's vertical alignment (baseline, superscript, or subscript), or an empty string when the run sets none.
type Section ¶
type Section struct {
// contains filtered or unexported fields
}
Section represents a document section with page layout properties.
func (*Section) ClearColumns ¶
func (s *Section) ClearColumns()
ClearColumns removes the section's w:cols element (reverting to a single column).
func (*Section) ClearDocumentGrid ¶
func (s *Section) ClearDocumentGrid()
ClearDocumentGrid removes the section's w:docGrid element.
func (*Section) ClearEndnoteProperties ¶
func (s *Section) ClearEndnoteProperties()
ClearEndnoteProperties removes the section's w:endnotePr element.
func (*Section) ClearFootnoteProperties ¶
func (s *Section) ClearFootnoteProperties()
ClearFootnoteProperties removes the section's w:footnotePr element.
func (*Section) ClearLineNumbering ¶
func (s *Section) ClearLineNumbering()
ClearLineNumbering removes the section's w:lnNumType element.
func (*Section) ClearPageBorders ¶
func (s *Section) ClearPageBorders()
ClearPageBorders removes the section's w:pgBorders element.
func (*Section) ClearPageNumbering ¶
func (s *Section) ClearPageNumbering()
ClearPageNumbering removes the section's w:pgNumType element.
func (*Section) ClearPaperSource ¶
func (s *Section) ClearPaperSource()
ClearPaperSource removes the section's w:paperSrc element.
func (*Section) Columns ¶
Columns returns the section's multi-column layout and whether a w:cols element is present. A section with no w:cols is a single-column section.
func (*Section) DocumentGrid ¶
func (s *Section) DocumentGrid() (DocumentGrid, bool)
DocumentGrid returns the section's document grid and whether a w:docGrid element is present.
func (*Section) EndnoteProperties ¶
func (s *Section) EndnoteProperties() (NoteProperties, bool)
EndnoteProperties returns the section's endnote numbering properties (w:endnotePr) and whether the element is present.
func (*Section) FootnoteProperties ¶
func (s *Section) FootnoteProperties() (NoteProperties, bool)
FootnoteProperties returns the section's footnote numbering properties (w:footnotePr) and whether the element is present.
func (*Section) LineNumbering ¶
func (s *Section) LineNumbering() (LineNumbering, bool)
LineNumbering returns the section's line-numbering settings and whether a w:lnNumType element is present.
func (*Section) Margins ¶
func (s *Section) Margins() PageMargins
Margins returns the page margins in points, or the zero PageMargins when the section declares none. Use MarginsOK to tell "no w:pgMar" apart from a section whose margins really are zero.
func (*Section) MarginsOK ¶ added in v0.2.0
func (s *Section) MarginsOK() (PageMargins, bool)
MarginsOK returns the page margins in points and whether the section declares them (w:pgMar). It is the ok-bool form the other Section getters use; Margins keeps the older single-value shape.
func (*Section) Orientation ¶
func (s *Section) Orientation() Orientation
Orientation returns the page orientation.
func (*Section) PageBorders ¶
func (s *Section) PageBorders() (PageBorders, bool)
PageBorders returns the section's page borders and whether a w:pgBorders element is present.
func (*Section) PageNumbering ¶
func (s *Section) PageNumbering() (PageNumbering, bool)
PageNumbering returns the section's page-numbering settings and whether a w:pgNumType element is present.
func (*Section) PaperSource ¶
PaperSource returns the printer paper-source bin numbers for the first page and the other pages (w:paperSrc), and whether the element is present.
func (*Section) SectionType ¶
SectionType returns the section's start type (w:type): one of the SectionType* values, or "" when unset (Word treats unset as nextPage).
func (*Section) SetColumns ¶
SetColumns sets the section's multi-column layout, replacing any existing w:cols element. Count defaults to 1 when non-positive; equal-width columns carry Spacing between them, while explicit-width columns are emitted from the Cols slice with EqualWidth="0".
func (*Section) SetDocumentGrid ¶
func (s *Section) SetDocumentGrid(dg DocumentGrid)
SetDocumentGrid sets the section's document grid, replacing any existing w:docGrid element. A zero LinePitch/CharSpace is omitted.
func (*Section) SetEndnoteProperties ¶
func (s *Section) SetEndnoteProperties(np NoteProperties)
SetEndnoteProperties sets the section's endnote numbering properties (w:endnotePr), replacing any existing element.
func (*Section) SetFootnoteProperties ¶
func (s *Section) SetFootnoteProperties(np NoteProperties)
SetFootnoteProperties sets the section's footnote numbering properties (w:footnotePr), replacing any existing element.
func (*Section) SetLineNumbering ¶
func (s *Section) SetLineNumbering(ln LineNumbering)
SetLineNumbering sets the section's line-numbering settings, replacing any existing w:lnNumType element. Zero-valued CountBy/Start/Distance are omitted.
func (*Section) SetMargins ¶
func (s *Section) SetMargins(m PageMargins)
SetMargins sets the page margins in points. All six values are written, including zeros: PageMargins is a complete description of the section's margins, so a zero Header distance (a header flush to the top of the page) must be expressible. Header and Footer used to be written only when positive, which made zero mean "leave whatever was there" for those two fields alone and unlike the other four (C493). Read the current values with MarginsOK, change what you need, and set the struct back to adjust one field.
func (*Section) SetOrientation ¶
func (s *Section) SetOrientation(orient Orientation)
SetOrientation sets the page orientation and swaps dimensions if needed.
func (*Section) SetPageBorders ¶
func (s *Section) SetPageBorders(b PageBorders)
SetPageBorders sets the section's page borders, replacing any existing w:pgBorders element.
func (*Section) SetPageNumbering ¶
func (s *Section) SetPageNumbering(pn PageNumbering)
SetPageNumbering sets the section's page-number format and starting value, creating the w:pgNumType element if absent. A zero PageNumbering (empty Format and nil Start) still emits an empty w:pgNumType; use ClearPageNumbering to remove it.
func (*Section) SetPageSize ¶
SetPageSize sets the page width and height in points.
func (*Section) SetPaperSource ¶
SetPaperSource sets the printer paper-source bin numbers for the first page and the other pages (w:paperSrc), replacing any existing element.
func (*Section) SetSectionType ¶
SetSectionType sets the section's start type. Passing "" removes the w:type element, restoring Word's default (nextPage).
func (*Section) SetTitlePage ¶
SetTitlePage enables or disables the distinct first-page header/footer. When disabled, the w:titlePg element is removed.
func (*Section) SetVerticalAlignment ¶
SetVerticalAlignment sets the section's vertical text alignment (w:vAlign). Valid values are "top", "center", "both", and "bottom"; passing "" removes the element.
func (*Section) TitlePage ¶
TitlePage reports whether the section has a distinct first-page header/footer (w:titlePg).
func (*Section) VerticalAlignment ¶
VerticalAlignment returns the section's vertical text alignment (w:vAlign): one of "top", "center", "both" (justified), or "bottom", or "" when unset.
type ShapeType ¶
type ShapeType string
ShapeType names a preset shape geometry (an OOXML a:prstGeom prst value). The four values below cover the common cases used by text boxes and basic shapes; the geometry is emitted verbatim as the prst attribute, so any other preset name can be passed through as well.
const ( // ShapeRectangle is a plain rectangle (the default text box geometry). ShapeRectangle ShapeType = "rect" // ShapeRoundRectangle is a rounded rectangle. ShapeRoundRectangle ShapeType = "roundRect" // ShapeEllipse is an ellipse/oval. ShapeEllipse ShapeType = "ellipse" // ShapeLine is a straight line connector geometry. ShapeLine ShapeType = "line" )
type SignatureLine ¶
type SignatureLine struct {
// ID is the signature line's GUID (the o:signatureline id attribute).
ID string
// Signer, Title, Email, and Instructions mirror the suggested-signer fields
// set when the line was created.
Signer string
Title string
Email string
Instructions string
}
SignatureLine is a visible signature line read back from a document (Document.SignatureLines).
type SignatureLineOptions ¶
type SignatureLineOptions struct {
// Signer is the suggested signer's name shown under the line.
Signer string
// Title is the suggested signer's title (e.g. "Director").
Title string
// Email is the suggested signer's email address.
Email string
// Instructions are shown to the signer in Word's signing dialog.
Instructions string
}
SignatureLineOptions configures a visible signature line (the "Microsoft Office Signature Line" placeholder inserted through Insert > Signature Line). It is the in-document request for a signature, distinct from actually signing the package (see opc.SignPackage): the placeholder shows the suggested signer's name, title, and email, and prompts a reader to sign.
type Source ¶
type Source struct {
Tag string
Type string
Author string
Title string
Year string
City string
Publisher string
}
Source describes a bibliography source (a b:Source entry). It is the value type accepted by Document.AddSource and returned by Document.Sources.
Tag is the citation key CITATION fields reference (Paragraph.AddCitation). Type is a b:SourceType value (see the Source* constants); it defaults to "Book" when empty. Author is a display author: a single "Last, First" name, several such names separated by ";", or a corporate/organization name.
type Style ¶
type Style struct {
// contains filtered or unexported fields
}
Style is a builder over a single style definition (w:style). Its setters return the receiver so calls chain; each one marks the styles part modified.
func (*Style) BasedOn ¶ added in v0.2.0
BasedOn returns the id of the style this one inherits from (w:basedOn), or "" when it inherits from nothing.
func (*Style) SetAlignment ¶
SetAlignment sets the paragraph alignment for this style (w:pPr/w:jc). It applies to paragraph and table styles.
func (*Style) SetBasedOn ¶
SetBasedOn sets the parent style (w:basedOn) this style inherits from.
A value that would make the style inherit from itself — directly, or through a chain that leads back to it — is refused: the style keeps its previous parent and the styles part is not marked modified. Word repairs or misrenders a cyclic basedOn chain, and nothing downstream of the setter would have caught it (Validate checked dangling references, not cycles). Use BasedOnCycle to test a value before setting it, or Document.Validate to find a cycle a merge introduced (C501).
func (*Style) SetColor ¶
SetColor sets the text color as a hex string, e.g. "FF0000" (w:rPr/w:color).
func (*Style) SetFont ¶
SetFont sets the style's font family (w:rPr/w:rFonts), for both the ASCII and high-ANSI ranges.
func (*Style) SetFontSize ¶
SetFontSize sets the font size in points (w:rPr/w:sz, stored in half-points).
func (*Style) SetIndentFirstLine ¶
SetIndentFirstLine sets a positive first-line indent in points; it clears any hanging indent, since the two are mutually exclusive in w:ind.
func (*Style) SetIndentHanging ¶
SetIndentHanging sets a hanging indent in points; it clears any first-line indent, since the two are mutually exclusive in w:ind.
func (*Style) SetIndentLeft ¶
SetIndentLeft sets the left indentation in points (w:pPr/w:ind).
func (*Style) SetLineSpacing ¶
SetLineSpacing sets proportional line spacing (1.0 = single, 1.5, 2.0, …), stored as lineRule="auto" in 240ths of a line.
func (*Style) SetLink ¶
SetLink links a paragraph style to its companion character style (w:link), forming a linked style pair.
func (*Style) SetNext ¶
SetNext sets the style (w:next) applied to the following paragraph when the user presses Enter at the end of a paragraph carrying this style.
func (*Style) SetQuickFormat ¶
SetQuickFormat toggles whether the style appears in the application's gallery of recommended styles (w:qFormat).
func (*Style) SetSpaceAfter ¶
SetSpaceAfter sets the spacing after paragraphs in points (w:pPr/w:spacing).
func (*Style) SetSpaceBefore ¶
SetSpaceBefore sets the spacing before paragraphs in points (w:pPr/w:spacing).
func (*Style) SetUIPriority ¶
SetUIPriority sets the sort order (w:uiPriority) the application uses when listing styles.
type StyleManager ¶
type StyleManager struct {
// contains filtered or unexported fields
}
StyleManager provides create and modify access to a document's style definitions (word/styles.xml). Obtain one with Document.Styles.
Reading through the manager (Style, List) never marks the styles part modified; only the mutating methods on the manager and on the returned Style builders do, so an unmodified document still round-trips byte-for-byte.
func (*StyleManager) AddCharacterStyle ¶
func (m *StyleManager) AddCharacterStyle(id, name string) *Style
AddCharacterStyle creates a new character (run) style; see AddParagraphStyle.
func (*StyleManager) AddParagraphStyle ¶
func (m *StyleManager) AddParagraphStyle(id, name string) *Style
AddParagraphStyle creates a new paragraph style with the given style id and display name and returns a builder for it. If a style with the id already exists it is returned as-is (its type and name left untouched) so the method is idempotent.
func (*StyleManager) AddStyle ¶
func (m *StyleManager) AddStyle(styleType StyleType, id, name string) *Style
AddStyle creates a new style of the given type with the given id and display name and returns a builder.
It is idempotent on the style id: an existing style with that id is returned unchanged, whatever its type. Requesting a character style whose id is already taken by a paragraph style therefore hands back the paragraph style — the caller's styleType and name are silently ignored rather than converting or replacing the definition, since either would change how existing paragraphs render. Check Style.Type on the returned builder when the type matters, or pick an unused id.
There is no RemoveStyle: no part of the docx feature API deletes, so a replace-style edit accretes definitions rather than replacing them.
func (*StyleManager) List ¶
func (m *StyleManager) List() []*Style
List returns a builder for every style defined in the document, in document order.
func (*StyleManager) Style ¶
func (m *StyleManager) Style(id string) *Style
Style returns the style with the given id, or nil if none exists. Fetching a style does not mark the part modified; mutating the returned builder does.
type StyleType ¶
type StyleType string
StyleType enumerates the WordprocessingML style categories (the w:type attribute of a w:style element).
const ( // StyleTypeParagraph is a paragraph style, applied via Paragraph.SetStyle. StyleTypeParagraph StyleType = "paragraph" // StyleTypeCharacter is a character (run) style. StyleTypeCharacter StyleType = "character" // StyleTypeTable is a table style. StyleTypeTable StyleType = "table" // StyleTypeNumbering is a numbering style. StyleTypeNumbering StyleType = "numbering" )
type TOCOptions ¶
type TOCOptions struct {
// MinLevel is the first heading (outline) level included, 1-9.
// Zero means 1.
MinLevel int
// MaxLevel is the last heading (outline) level included, 1-9.
// Zero means 3.
MaxLevel int
}
TOCOptions configures AddTableOfContents. The zero value builds a TOC over heading levels 1-3.
type TabAlignment ¶
type TabAlignment string
TabAlignment names the alignment of a paragraph tab stop (w:tab@val, ST_TabJc). The string values are the WordprocessingML tokens.
const ( TabAlignLeft TabAlignment = "left" TabAlignCenter TabAlignment = "center" TabAlignRight TabAlignment = "right" TabAlignDecimal TabAlignment = "decimal" TabAlignBar TabAlignment = "bar" TabAlignClear TabAlignment = "clear" )
type TabLeader ¶
type TabLeader string
TabLeader names the leader character drawn in the space a tab stop spans (w:tab@leader, ST_TabTlc). The string values are the WordprocessingML tokens.
type TabStop ¶
type TabStop struct {
// Position is the tab stop position in points, measured from the paragraph
// left margin (or from the value's reference for bar/right stops).
Position float64
// Alignment is the tab stop alignment. The empty value is treated as left.
Alignment TabAlignment
// Leader is the leader character; the empty value (or TabLeaderNone) draws
// no leader.
Leader TabLeader
}
TabStop describes a single paragraph tab stop.
type Table ¶
type Table struct {
// contains filtered or unexported fields
}
Table represents a table in a Word document.
func (*Table) Alignment ¶
Alignment returns the table's horizontal alignment within its column (w:tblPr/w:jc). Only left, center, and right apply to tables; anything else reports AlignmentLeft.
func (*Table) Borders ¶
func (t *Table) Borders() (TableBorders, bool)
Borders returns the table's borders (w:tblBorders) and whether the element is present.
func (*Table) Indent ¶
Indent returns the table's indentation from the leading margin in points (w:tblInd) and whether the element is present.
func (*Table) Layout ¶
func (t *Table) Layout() TableLayout
Layout returns the table's layout algorithm (w:tblLayout), or "" when unset.
func (*Table) SetAlignment ¶
SetAlignment sets the table's horizontal alignment (w:tblPr/w:jc). Tables support left, center, and right; AlignmentJustify is treated as left.
func (*Table) SetBorders ¶
func (t *Table) SetBorders(b TableBorders)
SetBorders sets the borders on the table.
func (*Table) SetCellMargins ¶
SetCellMargins sets the default cell margins for the table in points.
func (*Table) SetIndent ¶
SetIndent sets the table's indentation from the leading margin in points (w:tblInd).
func (*Table) SetLayout ¶
func (t *Table) SetLayout(layout TableLayout)
SetLayout sets the table's layout algorithm (w:tblLayout). Passing "" removes the element.
func (*Table) SetTableLook ¶
SetTableLook sets the table's conditional-formatting selection (w:tblLook), writing both the explicit boolean attributes and the equivalent w:val bitmask that Word emits.
func (*Table) Shading ¶
Shading returns the table's background fill color (w:tblPr/w:shd@w:fill), or "" when unset.
type TableBorders ¶
TableBorders defines borders for a table.
type TableCell ¶
type TableCell struct {
// contains filtered or unexported fields
}
TableCell represents a cell in a table.
func (*TableCell) AddParagraph ¶
AddParagraph adds a new paragraph to the cell. The paragraph carries the document backref, so runs created in it can add images end-to-end.
func (*TableCell) Borders ¶
func (tc *TableCell) Borders() (CellBorders, bool)
Borders returns the cell's borders (w:tcBorders) and whether the element is present.
func (*TableCell) ClearVerticalMerge ¶
func (tc *TableCell) ClearVerticalMerge()
ClearVerticalMerge removes the cell's w:vMerge element.
func (*TableCell) GridSpan ¶
GridSpan returns the number of grid columns the cell spans (w:gridSpan); 1 when unset.
func (*TableCell) Paragraphs ¶
Paragraphs returns all paragraphs in the cell.
func (*TableCell) SetBorders ¶
func (tc *TableCell) SetBorders(b CellBorders)
SetBorders sets the borders on the cell.
func (*TableCell) SetGridSpan ¶
SetGridSpan sets horizontal cell merging (column span).
func (*TableCell) SetShading ¶
SetShading sets the background color of the cell.
func (*TableCell) SetVerticalAlignment ¶
SetVerticalAlignment sets the vertical alignment of the cell content. Valid values: "top", "center", "bottom".
func (*TableCell) SetVerticalMerge ¶
func (tc *TableCell) SetVerticalMerge(m VerticalMerge)
SetVerticalMerge sets the cell's vertical-merge role (w:vMerge). VerticalMergeRestart marks the top cell of a merged column; VerticalMergeContinue marks a cell that merges upward into it and is emitted as a bare <w:vMerge/>, the form Word writes for a continued cell.
func (*TableCell) Shading ¶
Shading returns the cell's background fill color (w:tcPr/w:shd@w:fill), or "" when unset.
func (*TableCell) VerticalAlignment ¶
VerticalAlignment returns the cell's vertical content alignment (w:tcPr/w:vAlign): "top", "center", or "bottom", or "" when unset.
func (*TableCell) VerticalMerge ¶
func (tc *TableCell) VerticalMerge() VerticalMerge
VerticalMerge returns the cell's vertical-merge role (w:vMerge), or "" when the cell is not part of a vertical merge.
type TableLayout ¶
type TableLayout string
TableLayout names a table's layout algorithm (w:tblLayout@w:type).
const ( // TableLayoutFixed uses the grid's column widths verbatim. TableLayoutFixed TableLayout = "fixed" // TableLayoutAutofit sizes columns to their content. TableLayoutAutofit TableLayout = "autofit" )
type TableLook ¶
type TableLook struct {
FirstRow, LastRow bool
FirstColumn, LastColumn bool
// NoHBand / NoVBand suppress horizontal / vertical banding.
NoHBand, NoVBand bool
}
TableLook selects which conditional-formatting parts of the table's style are applied (w:tblLook): the special first/last row and column formatting and whether row/column banding is suppressed.
type TableRow ¶
type TableRow struct {
// contains filtered or unexported fields
}
TableRow represents a row in a table.
func (*TableRow) SetHeaderRow ¶
SetHeaderRow marks this row as a header row that repeats on page breaks.
type TextBox ¶
type TextBox struct {
// contains filtered or unexported fields
}
TextBox is a handle to a DrawingML (wps) or legacy VML text box or shape. It is returned by AddTextBox/AddShape and by Document.TextBoxes(), and exposes the box's text and geometry.
func (*TextBox) Floating ¶
Floating reports whether the box is anchored/floating rather than inline.
func (*TextBox) IsVML ¶
IsVML reports whether the box was read from a legacy VML w:pict drawing rather than a modern DrawingML (wps) drawing.
func (*TextBox) Shape ¶
Shape returns the box's preset geometry (e.g. ShapeRectangle), or "" if it was read from a legacy VML text box that carries no DrawingML preset.
type TextBoxOptions ¶
type TextBoxOptions struct {
// WidthEMU and HeightEMU are the box size in EMU (914400 per inch). When
// zero a default of 2in x 1in is used.
WidthEMU int64
HeightEMU int64
// Floating anchors the box (positioned relative to the page or paragraph)
// instead of placing it inline in the text flow.
Floating bool
// Anchor positions the box when Floating is set (same semantics as images).
Anchor Anchor
// Shape selects the preset geometry; empty means ShapeRectangle.
Shape ShapeType
// FillColor is the fill color as a hex "RRGGBB" string; empty uses the
// default (white). Set NoFill for a transparent shape.
FillColor string
// NoFill makes the shape transparent (no fill), overriding FillColor.
NoFill bool
// BorderColor is the outline color as a hex "RRGGBB" string; empty uses the
// default (black). Set NoBorder for no outline.
BorderColor string
// BorderWidthEMU is the outline width in EMU; zero uses a 0.5pt default.
BorderWidthEMU int64
// NoBorder removes the outline, overriding BorderColor/BorderWidthEMU.
NoBorder bool
// NoVMLFallback writes the DrawingML shape alone, without the
// mc:AlternateContent wrapper and legacy VML w:pict fallback that Word
// emits beside it.
//
// The wrapper is the default because without it the shape is not markup a
// conforming consumer can process: it sits in a:graphicData, whose wildcard
// is processContents="strict", and wps: is a Microsoft extension no ISO
// schema declares — so a reader that does not know the extension may
// neither render it nor skip it, and shows nothing at all. That is what the
// schema-conformance suite reported ("Element 'wsp': No matching global
// element declaration available, but demanded by the strict wildcard").
//
// Set it only when the output is for a consumer known to understand wps and
// the smaller part is worth more than down-level rendering.
NoVMLFallback bool
}
TextBoxOptions configures a text box or shape created with AddTextBox / AddShape. The zero value produces an inline rectangular text box with a white fill and a thin black border.
type UnderlineStyle ¶
type UnderlineStyle string
UnderlineStyle names the line style of a run's underline (the w:u@val attribute, ST_Underline). The string values are the WordprocessingML tokens, so they serialize directly.
const ( UnderlineNone UnderlineStyle = "none" UnderlineSingle UnderlineStyle = "single" UnderlineWords UnderlineStyle = "words" UnderlineDouble UnderlineStyle = "double" UnderlineThick UnderlineStyle = "thick" UnderlineDotted UnderlineStyle = "dotted" UnderlineDottedHeavy UnderlineStyle = "dottedHeavy" UnderlineDash UnderlineStyle = "dash" UnderlineDashedHeavy UnderlineStyle = "dashedHeavy" UnderlineDashLong UnderlineStyle = "dashLong" UnderlineDashLongHeavy UnderlineStyle = "dashLongHeavy" UnderlineDotDash UnderlineStyle = "dotDash" UnderlineDashDotHeavy UnderlineStyle = "dashDotHeavy" UnderlineDotDotDash UnderlineStyle = "dotDotDash" UnderlineDashDotDotHeavy UnderlineStyle = "dashDotDotHeavy" UnderlineWave UnderlineStyle = "wave" UnderlineWavyHeavy UnderlineStyle = "wavyHeavy" UnderlineWavyDouble UnderlineStyle = "wavyDouble" )
type VerticalMerge ¶
type VerticalMerge string
VerticalMerge names a table cell's vertical-merge role (w:vMerge). A merged column is expressed as a "restart" cell at the top followed by "continue" cells that fold their content upward into it.
const ( // VerticalMergeRestart begins a vertically merged region (w:vMerge="restart"). VerticalMergeRestart VerticalMerge = "restart" // VerticalMergeContinue continues the region begun by the cell above // (a bare <w:vMerge/>). VerticalMergeContinue VerticalMerge = "continue" )
type WarpPreset ¶
type WarpPreset string
WarpPreset names a DrawingML preset text-warp geometry (an a:prstTxWarp prst value). The value is emitted verbatim, so any other preset name Word recognizes (textStop, textTriangle, ...) can be passed through as well.
const ( // WarpNone applies no warp: the text is laid out straight (still a WordArt // shape, with the fill/outline styling). WarpNone WarpPreset = "" // WarpArchUp bends the text into an upward arch. WarpArchUp WarpPreset = "textArchUp" // WarpArchDown bends the text into a downward arch. WarpArchDown WarpPreset = "textArchDown" // WarpCircle wraps the text around a full circle. WarpCircle WarpPreset = "textCircle" // WarpInflate inflates the text (bulging outward top and bottom). WarpInflate WarpPreset = "textInflate" // WarpDeflate deflates the text (pinching inward top and bottom). WarpDeflate WarpPreset = "textDeflate" // WarpChevronUp bends the text into an upward chevron. WarpChevronUp WarpPreset = "textChevron" // WarpWave1 gives the text a single wave. WarpWave1 WarpPreset = "textWave1" )
type Watermark ¶
type Watermark struct {
Type WatermarkType
Text string
}
Watermark reports a detected watermark. Text is set for text watermarks.
type WatermarkOptions ¶
type WatermarkOptions struct {
// Font is the font family for a text watermark. Defaults to "Calibri".
Font string
// Color is the fill color of a text watermark as a hex RGB string
// (e.g. "C0C0C0" or "#C0C0C0"). Defaults to silver ("C0C0C0"). Ignored for
// image watermarks.
Color string
// Diagonal lays the watermark out on a 45° diagonal (the classic Word
// look). Ignored when Rotation is set.
Diagonal bool
// Rotation rotates the shape by this many degrees clockwise. When zero,
// Diagonal decides the angle (315° when set, otherwise horizontal).
Rotation float64
// DrawingML emits a text watermark as a DrawingML text box wrapped in an
// mc:AlternateContent whose fallback is the classic VML shape, matching the
// form newer Word versions write. Consumers that understand DrawingML
// (Requires="wps") render the text box; older ones fall back to the VML.
// Ignored for image watermarks, which remain VML-only.
DrawingML bool
}
WatermarkOptions configures a text or image watermark. The zero value is valid: a horizontal, silver watermark in Calibri.
type WatermarkType ¶
type WatermarkType int
WatermarkType classifies a detected watermark.
const ( // WatermarkNone means no watermark was detected. WatermarkNone WatermarkType = iota // WatermarkText is a WordArt text watermark (VML v:textpath). WatermarkText // WatermarkImage is a washed-out image watermark (VML v:imagedata). WatermarkImage )
type WordArtOptions ¶
type WordArtOptions struct {
// WidthEMU and HeightEMU are the shape size in EMU (914400 per inch). When
// zero a default of 3in x 0.75in is used.
WidthEMU int64
HeightEMU int64
// Floating anchors the shape (positioned relative to the page or paragraph)
// instead of placing it inline in the text flow.
Floating bool
// Anchor positions the shape when Floating is set (same semantics as images).
Anchor Anchor
// Warp selects the preset text-warp geometry; WarpNone lays the text out
// straight.
Warp WarpPreset
// FillColor is the text fill as a hex "RRGGBB" string; empty uses the default
// WordArt blue.
FillColor string
// FontSizePt is the text size in points; zero uses 36pt.
FontSizePt float64
// Bold makes the WordArt text bold.
Bold bool
}
WordArtOptions configures a WordArt shape created with AddWordArt. The zero value produces an inline, un-warped, 36pt blue caption 3in x 0.75in.
Source Files
¶
- activex.go
- bibliography.go
- bookmark.go
- buildingblocks.go
- chart.go
- comment.go
- content_control.go
- custom_properties.go
- customxml.go
- document.go
- encryption.go
- errors.go
- field.go
- footnote.go
- formfield.go
- frameset.go
- headerfooter.go
- hyperlink.go
- image.go
- image_read.go
- ink.go
- list.go
- mailmerge.go
- marshal.go
- math.go
- merge.go
- metaparts.go
- model3d.go
- modified.go
- mutate.go
- numbering.go
- ole.go
- paragraph.go
- paragraph_borders.go
- protection.go
- range_order.go
- rawxml.go
- relsweep.go
- replace.go
- revisions.go
- run.go
- section.go
- section_details.go
- section_layout.go
- settings.go
- shapegroup.go
- signatureline.go
- styles.go
- styles_default.go
- table.go
- table_props.go
- text.go
- textbox.go
- theme.go
- toc.go
- validate.go
- vba.go
- watermark.go
- wordart.go