Documentation
¶
Overview ¶
Package word is a pure-Go port of PHPWord for creating, reading, and filling Microsoft Word documents.
The public API follows PHPWord naming (AddSection, AddText, IOFactory) while using idiomatic Go types and error returns. The library depends only on the Go standard library.
doc := word.New()
section := doc.AddSection()
section.AddText("Hello World")
if err := doc.Save("hello.docx"); err != nil {
log.Fatal(err)
}
Index ¶
- Constants
- Variables
- func AddHTML(dst htmlContainer, html string, fullHTML ...bool) error
- func AddMarkdown(dst htmlContainer, md string) error
- func DefaultAsianFontName() string
- func DefaultFontColor() string
- func DefaultFontName() string
- func DefaultFontSize() float64
- func DefaultPaper() string
- func ExtractVariables(filename string, readerName ...string) ([]string, error)
- func HasCompatibility() bool
- func IsDefaultRtl() *bool
- func IsOutputEscapingEnabled() bool
- func MeasurementUnit() string
- func RegisterTemplateFilter(name string, fn func(in any, args ...string) string)
- func RenderHTML(r io.Reader, opts HTMLOptions) ([]byte, error)
- func RenderHTMLFile(path string, opts HTMLOptions) ([]byte, error)
- func RenderHTMLFileWithOptions(path string, readOpts ReadOptions, htmlOpts HTMLOptions) ([]byte, error)
- func RenderHTMLWithOptions(r io.Reader, readOpts ReadOptions, htmlOpts HTMLOptions) ([]byte, error)
- func SetCompatibility(v bool)
- func SetDefaultAsianFontName(name string)
- func SetDefaultFontColor(color string)
- func SetDefaultFontName(name string)
- func SetDefaultFontSize(size float64)
- func SetDefaultPaper(name string)
- func SetDefaultRtl(v *bool)
- func SetMacroChars(open, close string)
- func SetMacroClosingChars(s string)
- func SetMacroOpeningChars(s string)
- func SetMeasurementUnit(unit string)
- func SetOutputEscapingEnabled(v bool)
- func SetTempDir(dir string)
- func SetZipClass(name string)
- func StreamExtractImages(r io.Reader, fn func(img ImageFile) error) error
- func StreamExtractImagesWithOptions(r io.Reader, fn func(img ImageFile) error, opts ReadOptions) error
- func StreamExtractText(r io.Reader, fn func(paragraphText string) error) error
- func StreamExtractTextWithOptions(r io.Reader, fn func(paragraphText string) error, opts ReadOptions) error
- func TempDir() string
- func ZipClass() string
- type BlockData
- type ChartDataLabelOptions
- type Document
- func Load(filename string, readerName ...string) (*Document, error)
- func LoadBytes(data []byte) (*Document, error)
- func LoadBytesWithOptions(data []byte, opts ReadOptions) (*Document, error)
- func LoadWithOptions(filename string, opts ReadOptions) (*Document, error)
- func New() *Document
- func NewWithOptions(opts DocumentOptions) *Document
- func Open(filePath string) (*Document, error)
- func OpenWithOptions(filename string, opts ReadOptions) (*Document, error)
- func Read(r io.Reader) (*Document, error)
- func ReadWithOptions(r io.Reader, opts ReadOptions) (*Document, error)
- func (d *Document) AddBookmark(p *Paragraph, name string) *element.Bookmark
- func (d *Document) AddChart(chartType string, categories []string, seriesData ...[]float64) *element.Chart
- func (d *Document) AddChartStyled(chartType string, categories []string, values []float64, st style.Chart) *element.Chart
- func (d *Document) AddDeletion(text, author, date string, styles ...any) *element.Text
- func (d *Document) AddFontStyle(name string, font any, para ...any)
- func (d *Document) AddHTML(htmlText string) error
- func (d *Document) AddHyperlinkToBookmark(p *Paragraph, text, bookmarkName string) *element.Link
- func (d *Document) AddInsertion(text, author, date string, styles ...any) *element.Text
- func (d *Document) AddLinkStyle(name string, font any)
- func (d *Document) AddMarkdown(mdText string) error
- func (d *Document) AddMath(formula string) *element.Formula
- func (d *Document) AddNumPages() *element.Field
- func (d *Document) AddNumberingStyle(name string, num any)
- func (d *Document) AddPageNumber() *element.Field
- func (d *Document) AddParagraphStyle(name string, para any)
- func (d *Document) AddSection(st ...any) *element.Section
- func (d *Document) AddShape(shapeType ShapeType, opts ShapeOptions) *element.DMLShape
- func (d *Document) AddTableOfContents(depth ...int) *element.TOC
- func (d *Document) AddTableStyle(name string, table any, firstRow ...any)
- func (d *Document) AddTitleStyle(depth int, font any, para ...any)
- func (d *Document) AppendDocument(src *Document, opts MergeOptions) error
- func (d *Document) Bytes() ([]byte, error)
- func (d *Document) CommentOn(text, body, author string, extras ...string) *element.Text
- func (d *Document) Compatibility() *metadata.Compatibility
- func (d *Document) CountStyles() int
- func (d *Document) DocInfo() *metadata.DocInfo
- func (d *Document) EnableTrackChanges(on bool)
- func (d *Document) ExtractImages() ([]ImageFile, error)
- func (d *Document) ExtractText() string
- func (d *Document) GetBookmarks() []*element.Bookmark
- func (d *Document) GetCharts() []*element.Chart
- func (d *Document) GetComments() []*element.Comment
- func (d *Document) GetCompatibility() *metadata.Compatibility
- func (d *Document) GetDefaultAsianFontName() string
- func (d *Document) GetDefaultFontColor() string
- func (d *Document) GetDefaultFontName() string
- func (d *Document) GetDefaultFontSize() float64
- func (d *Document) GetDocInfo() *metadata.DocInfo
- func (d *Document) GetEndnotes() []*element.Endnote
- func (d *Document) GetFootnotes() []*element.Footnote
- func (d *Document) GetMetadata() *metadata.DocInfo
- func (d *Document) GetSection(index int) *element.Section
- func (d *Document) GetSections() []*element.Section
- func (d *Document) GetSettings() *metadata.Settings
- func (d *Document) GetStyle(name string) *NamedStyle
- func (d *Document) GetStyles() []NamedStyle
- func (d *Document) GetTitles() []*element.Title
- func (d *Document) Protect(editing, password string) error
- func (d *Document) RenderHTML(opts HTMLOptions) ([]byte, error)
- func (d *Document) RenderHTMLWithDiagnostics(opts HTMLOptions) (HTMLRenderResult, error)
- func (d *Document) ResetStyles()
- func (d *Document) Save(filename string) error
- func (d *Document) SaveAs(filename, format string) error
- func (d *Document) Sections() []*element.Section
- func (d *Document) SetDefaultAsianFontName(name string)
- func (d *Document) SetDefaultFontColor(color string)
- func (d *Document) SetDefaultFontName(name string)
- func (d *Document) SetDefaultFontSize(size float64)
- func (d *Document) SetDefaultParagraphStyle(para any)
- func (d *Document) SetDifferentFirstPage(enable bool)
- func (d *Document) SetEvenAndOddHeaders(enable bool)
- func (d *Document) SetImageWatermark(imageBytes []byte, opts ...ImageWatermarkOptions)
- func (d *Document) SetImageWatermarkFile(path string, opts ...ImageWatermarkOptions) error
- func (d *Document) SetTextWatermark(text string, opts ...WatermarkOptions)
- func (d *Document) Settings() *metadata.Settings
- func (d *Document) SortSections(less func(a, b *element.Section) bool)
- func (d *Document) StreamExtractImages(r io.Reader, fn func(img ImageFile) error) error
- func (d *Document) StreamExtractImagesWithOptions(r io.Reader, fn func(img ImageFile) error, opts ReadOptions) error
- func (d *Document) StreamExtractText(r io.Reader, fn func(paragraphText string) error) error
- func (d *Document) StreamExtractTextWithOptions(r io.Reader, fn func(paragraphText string) error, opts ReadOptions) error
- func (d *Document) TrackRevisions() bool
- func (d *Document) WriteHTML(w io.Writer, opts HTMLOptions) error
- func (d *Document) WriteTo(dest io.Writer) (int64, error)
- type DocumentOptions
- type HTMLDiagnostic
- type HTMLImageMode
- type HTMLOptions
- type HTMLRenderResult
- type HTMLUnsupportedError
- type ImageFile
- type ImageWatermarkOptions
- type MergeOptions
- type NamedStyle
- type PackageDiagnostic
- type Paragraph
- type PhpWord
- type ReadOptions
- type Reader
- type ShapeOptions
- type ShapeType
- type StreamWriter
- type TemplateFilter
- type TemplateProcessor
- func NewTemplateProcessor(filename string) (*TemplateProcessor, error)
- func NewTemplateProcessorBytes(data []byte) (*TemplateProcessor, error)
- func NewTemplateProcessorBytesWithOptions(data []byte, opts ReadOptions) (*TemplateProcessor, error)
- func NewTemplateProcessorWithOptions(filename string, opts ReadOptions) (*TemplateProcessor, error)
- func (t *TemplateProcessor) ApplyConditionsFromValues(values map[string]string) error
- func (t *TemplateProcessor) Bytes() ([]byte, error)
- func (t *TemplateProcessor) CloneBlock(blockName string, count int) error
- func (t *TemplateProcessor) CloneBlockAndSetValues(blockName string, values []map[string]string) error
- func (t *TemplateProcessor) CloneNestedBlock(blockName string, items []BlockData) error
- func (t *TemplateProcessor) CloneRow(search string, count int) error
- func (t *TemplateProcessor) CloneRowAndSetValues(search string, values []map[string]string) error
- func (t *TemplateProcessor) DeleteBlock(blockName string) error
- func (t *TemplateProcessor) DeleteRow(search string) error
- func (t *TemplateProcessor) GetVariableCount() map[string]int
- func (t *TemplateProcessor) GetVariables() []string
- func (t *TemplateProcessor) ReplaceBlock(blockName, replacement string) error
- func (t *TemplateProcessor) ReplaceCarriageReturns(s string) string
- func (t *TemplateProcessor) ReplaceXmlBlock(macroName, block, blockType string) error
- func (t *TemplateProcessor) Save(filename string) error
- func (t *TemplateProcessor) SaveAs(filename string) error
- func (t *TemplateProcessor) SetChart(search string, ch *element.Chart) error
- func (t *TemplateProcessor) SetCheckbox(search string, checked bool)
- func (t *TemplateProcessor) SetComplexBlock(search string, el element.Element) error
- func (t *TemplateProcessor) SetComplexValue(search string, el element.Element) error
- func (t *TemplateProcessor) SetCondition(name string, keep bool) error
- func (t *TemplateProcessor) SetConditions(conds map[string]bool) error
- func (t *TemplateProcessor) SetImageValue(search, path string) error
- func (t *TemplateProcessor) SetImageValueBytes(search, filename string, data []byte) error
- func (t *TemplateProcessor) SetMacroChars(open, close string)
- func (t *TemplateProcessor) SetMacroClosingChars(s string)
- func (t *TemplateProcessor) SetMacroOpeningChars(s string)
- func (t *TemplateProcessor) SetUpdateFields(update bool)
- func (t *TemplateProcessor) SetValue(search, replace string)
- func (t *TemplateProcessor) SetValueLimit(search, replace string, limit int)
- func (t *TemplateProcessor) SetValues(values map[string]string)
- type WatermarkOptions
- type Writer
Constants ¶
const ( ChartTypeBar = "bar" ChartTypeColumn = "column" ChartTypeLine = "line" ChartTypePie = "pie" ChartTypeArea = "area" ChartTypeStackedArea = "stacked_area" ChartTypePercentStackedArea = "percent_stacked_area" ChartTypeCombo = "combo" )
Chart type names used by AddChart and Container.AddChart.
const ( LegendTop = "t" LegendBottom = "b" LegendLeft = "l" LegendRight = "r" )
Legend positions (c:legendPos).
const ( DataLabelPosBestFit = "bestFit" DataLabelPosBottom = "b" DataLabelPosCenter = "ctr" DataLabelPosInBase = "inBase" DataLabelPosInEnd = "inEnd" DataLabelPosLeft = "l" DataLabelPosOutEnd = "outEnd" DataLabelPosRight = "r" DataLabelPosTop = "t" )
Data label positions (c:dLblPos).
const ( ProtectTypeNone = style.DocProtectNone ProtectTypeReadOnly = style.DocProtectReadOnly ProtectTypeComments = style.DocProtectComments ProtectTypeTrackedChanges = style.DocProtectTrackedChanges ProtectTypeForms = style.DocProtectForms )
Document protection modes (OOXML ST_DocProtect).
const ( VAlignTop = style.VAlignTop VAlignCenter = style.VAlignCenter VAlignBottom = style.VAlignBottom )
Vertical cell alignment (ST_VerticalJc), re-exported for document APIs.
const ( TextDirectionHorizontal = style.TextDirectionLrTb TextDirectionVertical = style.TextDirectionTbRl )
Text direction (ST_TextDirection).
const ( UnitTwip = "twip" UnitCM = "cm" UnitMM = "mm" UnitInch = "inch" UnitPoint = "point" UnitPica = "pica" )
Variables ¶
var ErrInvalidReadOptions = errors.New("word: invalid read options")
ErrInvalidReadOptions reports an invalid negative read budget.
var ErrReadLimitExceeded = common.ErrZipLimitExceeded
ErrReadLimitExceeded reports that a configured ZIP read budget was exceeded. Use errors.Is to recognize it through contextual errors.
Functions ¶
func AddHTML ¶
AddHTML parses HTML and appends equivalent elements to dst (PHPWord Shared\Html::addHtml).
func AddMarkdown ¶ added in v0.4.0
AddMarkdown parses Markdown and appends native GoWord elements to dst.
func DefaultAsianFontName ¶
func DefaultAsianFontName() string
DefaultAsianFontName returns the process-wide default East-Asian font.
func DefaultFontColor ¶
func DefaultFontColor() string
DefaultFontColor returns the process-wide default color (hex, no #).
func DefaultFontName ¶
func DefaultFontName() string
DefaultFontName returns the process-wide default font.
func DefaultFontSize ¶
func DefaultFontSize() float64
DefaultFontSize returns the process-wide default size in points.
func DefaultPaper ¶
func DefaultPaper() string
DefaultPaper returns the process-wide default paper size name.
func ExtractVariables ¶
ExtractVariables returns ${placeholder} names from a template file.
func HasCompatibility ¶
func HasCompatibility() bool
HasCompatibility reports XMLWriter compatibility mode (PHP Settings::hasCompatibility).
func IsDefaultRtl ¶
func IsDefaultRtl() *bool
IsDefaultRtl reports the process-wide default RTL flag.
func IsOutputEscapingEnabled ¶
func IsOutputEscapingEnabled() bool
IsOutputEscapingEnabled reports whether XML escaping is on.
func MeasurementUnit ¶
func MeasurementUnit() string
MeasurementUnit returns the process-wide unit (twip, cm, mm, inch, point, pica).
func RegisterTemplateFilter ¶ added in v0.7.0
RegisterTemplateFilter installs or replaces a named pipe filter.
func RenderHTML ¶ added in v0.12.0
func RenderHTML(r io.Reader, opts HTMLOptions) ([]byte, error)
RenderHTML reads a DOCX from r and renders it as HTML.
func RenderHTMLFile ¶ added in v0.12.0
func RenderHTMLFile(path string, opts HTMLOptions) ([]byte, error)
RenderHTMLFile loads a DOCX file and renders it as HTML.
func RenderHTMLFileWithOptions ¶ added in v0.12.0
func RenderHTMLFileWithOptions(path string, readOpts ReadOptions, htmlOpts HTMLOptions) ([]byte, error)
RenderHTMLFileWithOptions loads a DOCX with read budgets and renders it as HTML.
func RenderHTMLWithOptions ¶ added in v0.12.0
func RenderHTMLWithOptions(r io.Reader, readOpts ReadOptions, htmlOpts HTMLOptions) ([]byte, error)
RenderHTMLWithOptions reads a DOCX with read budgets and renders it as HTML.
func SetCompatibility ¶
func SetCompatibility(v bool)
SetCompatibility toggles XMLWriter compatibility mode.
func SetDefaultAsianFontName ¶
func SetDefaultAsianFontName(name string)
SetDefaultAsianFontName sets the process-wide default East-Asian font.
func SetDefaultFontColor ¶
func SetDefaultFontColor(color string)
SetDefaultFontColor sets the process-wide default color.
func SetDefaultFontName ¶
func SetDefaultFontName(name string)
SetDefaultFontName sets the process-wide default font.
func SetDefaultFontSize ¶
func SetDefaultFontSize(size float64)
SetDefaultFontSize sets the process-wide default size in points.
func SetDefaultPaper ¶
func SetDefaultPaper(name string)
SetDefaultPaper sets the process-wide default paper size name.
func SetDefaultRtl ¶
func SetDefaultRtl(v *bool)
SetDefaultRtl sets the process-wide default RTL flag.
func SetMacroChars ¶
func SetMacroChars(open, close string)
SetMacroChars sets both placeholder delimiters.
func SetMacroClosingChars ¶
func SetMacroClosingChars(s string)
SetMacroClosingChars sets the placeholder closing delimiter.
func SetMacroOpeningChars ¶
func SetMacroOpeningChars(s string)
SetMacroOpeningChars sets the placeholder opening delimiter (PHPWord).
func SetMeasurementUnit ¶
func SetMeasurementUnit(unit string)
SetMeasurementUnit sets the process-wide unit.
func SetOutputEscapingEnabled ¶
func SetOutputEscapingEnabled(v bool)
SetOutputEscapingEnabled toggles XML escaping of text (always recommended).
func SetZipClass ¶
func SetZipClass(name string)
SetZipClass is accepted for PHP parity; Go always uses archive/zip.
func StreamExtractImages ¶ added in v0.7.0
StreamExtractImages scans word/document.xml for DrawingML blips and VML imagedata, then streams each referenced media part from the ZIP into fn.
func StreamExtractImagesWithOptions ¶ added in v0.10.0
func StreamExtractImagesWithOptions(r io.Reader, fn func(img ImageFile) error, opts ReadOptions) error
StreamExtractImagesWithOptions scans images with optional ZIP budgets.
func StreamExtractText ¶ added in v0.7.0
StreamExtractText scans word/document.xml with xml.Decoder and invokes fn once for every complete w:p. Paragraph buffers are discarded after each callback so memory stays O(1) relative to document size.
func StreamExtractTextWithOptions ¶ added in v0.10.0
func StreamExtractTextWithOptions(r io.Reader, fn func(paragraphText string) error, opts ReadOptions) error
StreamExtractTextWithOptions scans word/document.xml with optional ZIP budgets.
Types ¶
type BlockData ¶ added in v0.3.0
BlockData is one clone of a named template block, including nested blocks and ${if} conditions scoped to that instance.
type ChartDataLabelOptions ¶ added in v0.7.0
type ChartDataLabelOptions = style.DataLabelOptions
ChartDataLabelOptions configures c:dLbls on a chart.
type Document ¶
type Document struct {
// contains filtered or unexported fields
}
Document is the PHPWord PhpWord class: an in-memory word-processing document.
func Load ¶
Load loads a document (PHPWord IOFactory::load). If readerName is omitted, the format is inferred from the file extension.
func LoadBytesWithOptions ¶ added in v0.10.0
func LoadBytesWithOptions(data []byte, opts ReadOptions) (*Document, error)
LoadBytesWithOptions loads a document with optional ZIP read budgets.
func LoadWithOptions ¶ added in v0.10.0
func LoadWithOptions(filename string, opts ReadOptions) (*Document, error)
LoadWithOptions loads a document from disk with optional ZIP read budgets.
func NewWithOptions ¶ added in v0.11.0
func NewWithOptions(opts DocumentOptions) *Document
NewWithOptions creates a document with instance-local defaults.
func OpenWithOptions ¶ added in v0.10.0
func OpenWithOptions(filename string, opts ReadOptions) (*Document, error)
OpenWithOptions is the Open counterpart with optional ZIP read budgets.
func ReadWithOptions ¶ added in v0.10.0
func ReadWithOptions(r io.Reader, opts ReadOptions) (*Document, error)
ReadWithOptions loads a document from r with optional ZIP read budgets.
func (*Document) AddBookmark ¶ added in v0.6.0
AddBookmark writes a bookmarkStart/bookmarkEnd pair on paragraph p. If p is nil, the bookmark is appended to the last section.
func (*Document) AddChart ¶ added in v0.4.0
func (d *Document) AddChart(chartType string, categories []string, seriesData ...[]float64) *element.Chart
AddChart appends a native OpenXML chart to the last (or a new) section. seriesData is one or more value series aligned with categories.
func (*Document) AddChartStyled ¶ added in v0.4.0
func (d *Document) AddChartStyled(chartType string, categories []string, values []float64, st style.Chart) *element.Chart
AddChartStyled is AddChart with DrawingML chart style options.
func (*Document) AddDeletion ¶ added in v0.4.0
AddDeletion appends tracked-delete text (w:del).
func (*Document) AddFontStyle ¶
AddFontStyle registers a named character style (PHPWord addFontStyle).
func (*Document) AddHyperlinkToBookmark ¶ added in v0.6.0
AddHyperlinkToBookmark appends an internal hyperlink (w:hyperlink w:anchor) that jumps to bookmarkName. If p is nil, the link is added to the last section.
func (*Document) AddInsertion ¶ added in v0.4.0
AddInsertion appends tracked-insert text (w:ins).
func (*Document) AddLinkStyle ¶
AddLinkStyle registers the Hyperlink character style.
func (*Document) AddMarkdown ¶ added in v0.4.0
AddMarkdown parses Markdown into the last (or a new) section.
func (*Document) AddMath ¶ added in v0.8.0
AddMath appends a display OMML equation parsed from a basic LaTeX string to the last (or a new) section.
func (*Document) AddNumPages ¶ added in v0.5.0
AddNumPages inserts a NUMPAGES field into the current section.
func (*Document) AddNumberingStyle ¶
AddNumberingStyle registers a named numbering definition.
func (*Document) AddPageNumber ¶ added in v0.5.0
AddPageNumber inserts a PAGE field into the current section.
func (*Document) AddParagraphStyle ¶
AddParagraphStyle registers a named paragraph style.
func (*Document) AddSection ¶
AddSection appends a section (PHPWord addSection).
func (*Document) AddShape ¶ added in v0.8.0
func (d *Document) AddShape(shapeType ShapeType, opts ShapeOptions) *element.DMLShape
AddShape appends a DrawingML shape (rectangle, rounded rectangle, arrow, or text box) to the last (or a new) section.
func (*Document) AddTableOfContents ¶ added in v0.5.0
AddTableOfContents inserts an OpenXML TOC field covering Heading 1–3 by default (TOC \o "1-3" \h \z \u). Optional depth is max, or min,max.
func (*Document) AddTableStyle ¶
AddTableStyle registers a named table style.
func (*Document) AddTitleStyle ¶
AddTitleStyle registers HeadingN (depth 1-9). depth 0 is Title.
func (*Document) AppendDocument ¶ added in v0.8.0
func (d *Document) AppendDocument(src *Document, opts MergeOptions) error
AppendDocument clones src onto d, remapping colliding style names, bookmark names, and media so the merged package writes unique rIds and part paths.
func (*Document) CommentOn ¶ added in v0.4.0
CommentOn annotates text in the last (or a new) section. extras is optional initials then date.
func (*Document) Compatibility ¶
func (d *Document) Compatibility() *metadata.Compatibility
Compatibility returns OOXML compatibility settings.
func (*Document) CountStyles ¶
CountStyles returns the number of registered named styles.
func (*Document) EnableTrackChanges ¶ added in v0.4.0
EnableTrackChanges turns on document-level revision tracking (w:trackRevisions).
func (*Document) ExtractImages ¶ added in v0.6.0
ExtractImages returns pictures from word/media/ (after Open/Read) or from in-memory image elements on a newly built document.
func (*Document) ExtractText ¶ added in v0.6.0
ExtractText returns document body text in paragraph and table order.
func (*Document) GetBookmarks ¶
GetBookmarks returns bookmark elements.
func (*Document) GetComments ¶
GetComments returns comment elements, including those attached as ranges.
func (*Document) GetCompatibility ¶
func (d *Document) GetCompatibility() *metadata.Compatibility
GetCompatibility is the PHPWord name for Compatibility.
func (*Document) GetDefaultAsianFontName ¶
func (*Document) GetDefaultFontColor ¶
func (*Document) GetDefaultFontName ¶
func (*Document) GetDefaultFontSize ¶
func (*Document) GetDocInfo ¶
GetDocInfo is the PHPWord name for DocInfo.
func (*Document) GetEndnotes ¶
GetEndnotes returns endnote elements.
func (*Document) GetFootnotes ¶
GetFootnotes returns footnote elements.
func (*Document) GetMetadata ¶ added in v0.6.0
GetMetadata returns core document properties (author, created, modified, ...).
func (*Document) GetSection ¶
GetSection returns the section at index, or nil.
func (*Document) GetSections ¶
GetSections is the PHPWord name for Sections.
func (*Document) GetSettings ¶
GetSettings is the PHPWord name for Settings.
func (*Document) GetStyle ¶
func (d *Document) GetStyle(name string) *NamedStyle
GetStyle returns a named style, or nil.
func (*Document) GetStyles ¶
func (d *Document) GetStyles() []NamedStyle
GetStyles returns registered named styles (PHPWord Style::getStyles).
func (*Document) Protect ¶ added in v0.5.0
Protect enables document protection (w:documentProtection). An empty password writes an unenforced-hash protection node; a non-empty password uses the Office SHA-1 / 100000-spin algorithm (ECMA-376).
func (*Document) RenderHTML ¶ added in v0.12.0
func (d *Document) RenderHTML(opts HTMLOptions) ([]byte, error)
RenderHTML renders a loaded document as an HTML fragment or standalone page.
func (*Document) RenderHTMLWithDiagnostics ¶ added in v0.12.0
func (d *Document) RenderHTMLWithDiagnostics(opts HTMLOptions) (HTMLRenderResult, error)
RenderHTMLWithDiagnostics renders a document and returns conversion diagnostics.
func (*Document) ResetStyles ¶
func (d *Document) ResetStyles()
ResetStyles clears the named-style registry (PHPWord Style::resetStyles).
func (*Document) SetDefaultAsianFontName ¶
func (*Document) SetDefaultFontColor ¶
func (*Document) SetDefaultFontName ¶
func (*Document) SetDefaultFontSize ¶
func (*Document) SetDefaultParagraphStyle ¶
SetDefaultParagraphStyle sets the Normal style.
func (*Document) SetDifferentFirstPage ¶ added in v0.5.0
SetDifferentFirstPage enables a first-page header/footer on the current section (w:titlePg plus HeaderFirst / FooterFirst).
func (*Document) SetEvenAndOddHeaders ¶ added in v0.5.0
SetEvenAndOddHeaders toggles odd/even page headers and footers (w:evenAndOddHeaders plus HeaderEven / FooterEven parts).
func (*Document) SetImageWatermark ¶ added in v0.5.0
func (d *Document) SetImageWatermark(imageBytes []byte, opts ...ImageWatermarkOptions)
SetImageWatermark stores a document-wide image watermark applied to every section header as VML v:imagedata (Word watermark drawing).
func (*Document) SetImageWatermarkFile ¶ added in v0.9.0
func (d *Document) SetImageWatermarkFile(path string, opts ...ImageWatermarkOptions) error
SetImageWatermarkFile loads a PNG or JPEG from disk as a page watermark.
func (*Document) SetTextWatermark ¶ added in v0.5.0
func (d *Document) SetTextWatermark(text string, opts ...WatermarkOptions)
SetTextWatermark stores a document-wide text watermark applied to every section header as Word-native VML (PowerPlusWaterMarkObject).
func (*Document) SortSections ¶
SortSections sorts sections with the given comparison.
func (*Document) StreamExtractImages ¶ added in v0.7.0
StreamExtractImages is the Document-method form of the package-level extractor.
func (*Document) StreamExtractImagesWithOptions ¶ added in v0.10.0
func (d *Document) StreamExtractImagesWithOptions(r io.Reader, fn func(img ImageFile) error, opts ReadOptions) error
StreamExtractImagesWithOptions is the Document-method form with ZIP budgets.
func (*Document) StreamExtractText ¶ added in v0.7.0
StreamExtractText is the Document-method form of the package-level extractor.
func (*Document) StreamExtractTextWithOptions ¶ added in v0.10.0
func (d *Document) StreamExtractTextWithOptions(r io.Reader, fn func(paragraphText string) error, opts ReadOptions) error
StreamExtractTextWithOptions is the Document-method form with ZIP budgets.
func (*Document) TrackRevisions ¶ added in v0.4.0
TrackRevisions reports whether revision tracking is on.
type DocumentOptions ¶ added in v0.11.0
type DocumentOptions struct {
DefaultFontName string
DefaultAsianFontName string
DefaultFontSize float64
DefaultFontColor string
}
DocumentOptions configures defaults for one document instance. Zero values inherit the package defaults used by New.
type HTMLDiagnostic ¶ added in v0.12.0
HTMLDiagnostic describes a lossy or unsupported conversion.
type HTMLImageMode ¶ added in v0.12.0
type HTMLImageMode string
HTMLImageMode controls image references in rendered HTML.
const ( HTMLImageDataURI HTMLImageMode = "data" HTMLImageURL HTMLImageMode = "url" )
type HTMLOptions ¶ added in v0.12.0
type HTMLOptions struct {
Standalone bool
Title string
ImageMode HTMLImageMode
ImageURL func(*element.Image) (string, error)
IncludeCSS bool // with Standalone, include built-in CSS and section page geometry
Strict bool
}
HTMLOptions controls DOCX to HTML rendering.
type HTMLRenderResult ¶ added in v0.12.0
type HTMLRenderResult struct {
HTML []byte
Diagnostics []HTMLDiagnostic
}
HTMLRenderResult contains rendered HTML and non-fatal diagnostics.
type HTMLUnsupportedError ¶ added in v0.12.0
type HTMLUnsupportedError struct{ Diagnostics []HTMLDiagnostic }
HTMLUnsupportedError reports unsupported elements in strict mode.
func (*HTMLUnsupportedError) Error ¶ added in v0.12.0
func (e *HTMLUnsupportedError) Error() string
type ImageWatermarkOptions ¶ added in v0.9.0
type ImageWatermarkOptions struct {
Washout bool // Word washout (gain/blacklevel)
Scale float64 // size multiplier; 0 leaves the default size
Opacity float64 // 0–1; 0 omits v:fill opacity
}
ImageWatermarkOptions configures a VML picture watermark (WordPictureWatermark).
type MergeOptions ¶ added in v0.8.0
MergeOptions controls how AppendDocument remaps colliding identifiers.
type NamedStyle ¶
type NamedStyle struct {
Name string
Kind string
Font *style.Font
Paragraph *style.Paragraph
Table *style.Table
FirstRow *style.Table
Numbering *style.Numbering
Depth int
}
NamedStyle is a document-scoped style definition (PHPWord Style registry entry).
type PackageDiagnostic ¶ added in v0.11.0
type PackageDiagnostic struct {
Severity string // error, warning
Code string
Part string
Message string
}
PackageDiagnostic describes a recoverable package validation finding.
func ValidatePackage ¶ added in v0.11.0
func ValidatePackage(data []byte) []PackageDiagnostic
ValidatePackage validates a DOCX ZIP package without mutating it.
type Paragraph ¶ added in v0.6.0
Paragraph is a rich-text paragraph used by bookmark and hyperlink APIs.
type PhpWord ¶
type PhpWord = Document
PhpWord is an alias for Document, matching the PHP class name.
type ReadOptions ¶ added in v0.10.0
type ReadOptions struct {
MaxArchiveSize int64 // compressed package bytes
MaxPartSize int64 // one uncompressed ZIP member
MaxTotalSize int64 // sum of uncompressed ZIP members
MaxEntries int // number of ZIP members
}
ReadOptions controls optional resource limits while reading a package. All limits are per call. Zero preserves the historical unlimited behavior.
type Reader ¶
Reader loads a document from a file.
func CreateReader ¶
CreateReader returns a reader for the named format (PHPWord IOFactory::createReader).
type ShapeOptions ¶ added in v0.8.0
type ShapeOptions struct {
Width int
Height int
FillColor string
LineColor string
LineWidth int
Text string
Font style.Font
}
ShapeOptions controls DrawingML fill, outline, size (EMU) and text.
type StreamWriter ¶ added in v0.2.0
type StreamWriter struct {
// contains filtered or unexported fields
}
StreamWriter writes paragraphs and tables incrementally into a Word2007 (.docx) ZIP stream. document.xml is opened on the first write so large tables never accumulate as a single in-memory XML tree.
Close finishes document.xml and emits the remaining OOXML parts (content types, relationships, styles, media). StreamWriter is not safe for concurrent use.
func NewStreamWriter ¶ added in v0.2.0
func NewStreamWriter(dest io.Writer) *StreamWriter
NewStreamWriter starts a Word2007 package on dest.
func (*StreamWriter) BytesWritten ¶ added in v0.2.0
func (s *StreamWriter) BytesWritten() int64
BytesWritten returns the number of bytes written to dest so far.
func (*StreamWriter) Close ¶ added in v0.2.0
func (s *StreamWriter) Close() error
Close finishes document.xml and writes the remaining package parts.
func (*StreamWriter) WriteElement ¶ added in v0.2.0
func (s *StreamWriter) WriteElement(el element.Element) error
WriteElement writes any document body element into the stream.
func (*StreamWriter) WriteParagraph ¶ added in v0.2.0
func (s *StreamWriter) WriteParagraph(text string, styles ...any) error
WriteParagraph writes a paragraph of text into the open document.xml stream. styles follows Section.AddText: optional font then paragraph style.
func (*StreamWriter) WriteTable ¶ added in v0.2.0
func (s *StreamWriter) WriteTable(tbl *element.Table) error
WriteTable writes a table, flushing XML after each row.
type TemplateFilter ¶ added in v0.7.0
TemplateFilter transforms a placeholder value. args are the : separated arguments from ${var | filter:arg}.
type TemplateProcessor ¶
type TemplateProcessor struct {
// contains filtered or unexported fields
}
TemplateProcessor fills ${placeholders} in an existing .docx (PHPWord TemplateProcessor).
func NewTemplateProcessor ¶
func NewTemplateProcessor(filename string) (*TemplateProcessor, error)
NewTemplateProcessor opens a .docx template from disk.
func NewTemplateProcessorBytes ¶
func NewTemplateProcessorBytes(data []byte) (*TemplateProcessor, error)
NewTemplateProcessorBytes opens a .docx template from memory.
func NewTemplateProcessorBytesWithOptions ¶ added in v0.10.0
func NewTemplateProcessorBytesWithOptions(data []byte, opts ReadOptions) (*TemplateProcessor, error)
NewTemplateProcessorBytesWithOptions opens a template with ZIP read budgets.
func NewTemplateProcessorWithOptions ¶ added in v0.10.0
func NewTemplateProcessorWithOptions(filename string, opts ReadOptions) (*TemplateProcessor, error)
NewTemplateProcessorWithOptions opens a disk template with ZIP read budgets.
func (*TemplateProcessor) ApplyConditionsFromValues ¶ added in v0.3.0
func (t *TemplateProcessor) ApplyConditionsFromValues(values map[string]string) error
ApplyConditionsFromValues treats empty/"0"/"false"/"no"/"off" as false.
func (*TemplateProcessor) Bytes ¶
func (t *TemplateProcessor) Bytes() ([]byte, error)
Bytes returns the filled template as a .docx package.
func (*TemplateProcessor) CloneBlock ¶
func (t *TemplateProcessor) CloneBlock(blockName string, count int) error
CloneBlock clones the region between ${block} and ${/block} count times. Nested ${inner}...${/inner} markers are indexed (${inner#1}) so they can be cloned per instance. Matching uses nesting depth for same-named blocks.
func (*TemplateProcessor) CloneBlockAndSetValues ¶
func (t *TemplateProcessor) CloneBlockAndSetValues(blockName string, values []map[string]string) error
CloneBlockAndSetValues clones ${block}...${/block} once per values row (PHPWord).
func (*TemplateProcessor) CloneNestedBlock ¶ added in v0.3.0
func (t *TemplateProcessor) CloneNestedBlock(blockName string, items []BlockData) error
CloneNestedBlock clones ${name}...${/name} once per item, then clones nested blocks and applies values / conditions with #n suffixes.
func (*TemplateProcessor) CloneRow ¶
func (t *TemplateProcessor) CloneRow(search string, count int) error
CloneRow clones the table row that contains ${search} count times, renaming macros to ${search#1}, ${search#2}, ... Vertically merged (w:vMerge restart/continue) rows are cloned as a single group.
func (*TemplateProcessor) CloneRowAndSetValues ¶
func (t *TemplateProcessor) CloneRowAndSetValues(search string, values []map[string]string) error
CloneRowAndSetValues clones a row and fills ${name#n} from values.
func (*TemplateProcessor) DeleteBlock ¶
func (t *TemplateProcessor) DeleteBlock(blockName string) error
DeleteBlock removes the region between ${block} and ${/block}.
func (*TemplateProcessor) DeleteRow ¶
func (t *TemplateProcessor) DeleteRow(search string) error
DeleteRow removes the table row that contains ${search}.
func (*TemplateProcessor) GetVariableCount ¶
func (t *TemplateProcessor) GetVariableCount() map[string]int
GetVariableCount returns placeholder name → occurrence count (PHPWord getVariableCount).
func (*TemplateProcessor) GetVariables ¶
func (t *TemplateProcessor) GetVariables() []string
GetVariables returns unique placeholder names in first-seen order.
func (*TemplateProcessor) ReplaceBlock ¶
func (t *TemplateProcessor) ReplaceBlock(blockName, replacement string) error
ReplaceBlock replaces the region between ${block} and ${/block}.
func (*TemplateProcessor) ReplaceCarriageReturns ¶
func (t *TemplateProcessor) ReplaceCarriageReturns(s string) string
ReplaceCarriageReturns turns newlines into Word break runs (PHPWord).
func (*TemplateProcessor) ReplaceXmlBlock ¶
func (t *TemplateProcessor) ReplaceXmlBlock(macroName, block, blockType string) error
ReplaceXmlBlock replaces the XML element of blockType that contains ${macro}.
func (*TemplateProcessor) Save ¶
func (t *TemplateProcessor) Save(filename string) error
Save writes the filled template to filename.
func (*TemplateProcessor) SaveAs ¶
func (t *TemplateProcessor) SaveAs(filename string) error
SaveAs is an alias for Save (PHPWord).
func (*TemplateProcessor) SetChart ¶
func (t *TemplateProcessor) SetChart(search string, ch *element.Chart) error
SetChart replaces ${search} with a chart drawing and chart XML part (PHPWord).
func (*TemplateProcessor) SetCheckbox ¶
func (t *TemplateProcessor) SetCheckbox(search string, checked bool)
SetCheckbox toggles a content-control checkbox at ${search}.
func (*TemplateProcessor) SetComplexBlock ¶
func (t *TemplateProcessor) SetComplexBlock(search string, el element.Element) error
SetComplexBlock replaces the w:p containing ${search} with the rendered element.
func (*TemplateProcessor) SetComplexValue ¶
func (t *TemplateProcessor) SetComplexValue(search string, el element.Element) error
SetComplexValue replaces the w:r containing ${search} with the rendered element.
func (*TemplateProcessor) SetCondition ¶ added in v0.3.0
func (t *TemplateProcessor) SetCondition(name string, keep bool) error
SetCondition keeps or clips ${if name}...${endif}.
func (*TemplateProcessor) SetConditions ¶ added in v0.3.0
func (t *TemplateProcessor) SetConditions(conds map[string]bool) error
SetConditions applies many named ${if} blocks.
func (*TemplateProcessor) SetImageValue ¶
func (t *TemplateProcessor) SetImageValue(search, path string) error
SetImageValue replaces a placeholder with a drawing that references a new image part.
func (*TemplateProcessor) SetImageValueBytes ¶
func (t *TemplateProcessor) SetImageValueBytes(search, filename string, data []byte) error
SetImageValueBytes embeds image bytes at ${search}.
func (*TemplateProcessor) SetMacroChars ¶
func (t *TemplateProcessor) SetMacroChars(open, close string)
func (*TemplateProcessor) SetMacroClosingChars ¶
func (t *TemplateProcessor) SetMacroClosingChars(s string)
func (*TemplateProcessor) SetMacroOpeningChars ¶
func (t *TemplateProcessor) SetMacroOpeningChars(s string)
func (*TemplateProcessor) SetUpdateFields ¶
func (t *TemplateProcessor) SetUpdateFields(update bool)
SetUpdateFields sets w:updateFields in word/settings.xml.
func (*TemplateProcessor) SetValue ¶
func (t *TemplateProcessor) SetValue(search, replace string)
SetValue replaces ${search} with replace across document parts.
func (*TemplateProcessor) SetValueLimit ¶
func (t *TemplateProcessor) SetValueLimit(search, replace string, limit int)
SetValueLimit replaces at most limit occurrences (-1 = all).
func (*TemplateProcessor) SetValues ¶
func (t *TemplateProcessor) SetValues(values map[string]string)
SetValues replaces many placeholders.
type WatermarkOptions ¶ added in v0.9.0
type WatermarkOptions struct {
Angle float64 // degrees; 0 defaults to -45
Color string // VML fillcolor, e.g. silver or C0C0C0
FontSize int // points; 0 uses Word's 1pt + fitshape
FontName string // default Calibri
Opacity float64 // 0–1; 0 defaults to 0.5. Values > 1 are treated as percent
Tile bool // full-page grid
Rows int // tile rows, default 3
Cols int // tile columns, default 3
}
WatermarkOptions configures a VML text watermark (PowerPlusWaterMarkObject).
Source Files
¶
- chart.go
- doc.go
- document_options.go
- enterprise.go
- html.go
- html_page.go
- html_render.go
- iofactory.go
- markdown.go
- math.go
- merger.go
- package_diagnostics.go
- parse.go
- phpword.go
- read_options.go
- reader_word2007.go
- reader_word2007_styles.go
- review.go
- settings.go
- shape.go
- stream.go
- stream_parser.go
- styles.go
- template.go
- template_blocks.go
- template_filter.go
- walk.go
- watermark.go
- writer_word2007.go
- writer_word2007_chart.go
- writer_word2007_elements.go
- writer_word2007_parts.go
- writer_word2007_static.go
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
all_in_one
command
Command all_in_one builds all_features_demo.docx, exercising every major GoWord surface: styles, merged tables, StreamWriter, charts, Markdown/HTML import, the template engine, comments, and track changes.
|
Command all_in_one builds all_features_demo.docx, exercising every major GoWord surface: styles, merged tables, StreamWriter, charts, Markdown/HTML import, the template engine, comments, and track changes. |
|
docx_to_html
command
|
|
|
read_limits
command
|
|
|
simple
command
|
|
|
v0.5.0_demo
command
Command v0.5.0_demo builds enterprise_demo.docx: watermarks, document protection, mixed portrait/landscape sections, first/odd/even headers, PAGE/NUMPAGES fields, and an H1–H3 table of contents.
|
Command v0.5.0_demo builds enterprise_demo.docx: watermarks, document protection, mixed portrait/landscape sections, first/odd/even headers, PAGE/NUMPAGES fields, and an H1–H3 table of contents. |
|
v0.6.0_demo
command
Command v0.6.0_demo builds parsing_demo.docx: nested tables, cell styling, bookmarks with internal hyperlinks, then re-opens the package and prints ExtractText / ExtractImages / GetMetadata results.
|
Command v0.6.0_demo builds parsing_demo.docx: nested tables, cell styling, bookmarks with internal hyperlinks, then re-opens the package and prints ExtractText / ExtractImages / GetMetadata results. |
|
v0.7.0_demo
command
Command v0.7.0_demo builds v070_demo.docx (area + combo charts, image) and template_v2.docx (pipe filters and comparison ifs), then streams 100_000 paragraphs through StreamExtractText.
|
Command v0.7.0_demo builds v070_demo.docx (area + combo charts, image) and template_v2.docx (pipe filters and comparison ifs), then streams 100_000 paragraphs through StreamExtractText. |
|
v0.8.0_demo
command
Command v0.8.0_demo builds v080_demo.docx (OMML math, DrawingML shapes, multi-column layout) and v080_merged.docx (document merger).
|
Command v0.8.0_demo builds v080_demo.docx (OMML math, DrawingML shapes, multi-column layout) and v080_merged.docx (document merger). |
|
v0.9.0_sdt
command
Command v0.9.0_sdt builds v090_sdt.docx with four Word content controls (plain text, drop-down, date picker, checkbox) that open in Microsoft Word.
|
Command v0.9.0_sdt builds v090_sdt.docx with four Word content controls (plain text, drop-down, date picker, checkbox) that open in Microsoft Word. |
|
v0.9.0_table_advanced
command
Command v0.9.0_table_advanced builds v090_table_advanced.docx with repeating table headers, unbreakable rows, vertical cell alignment, and vertical text direction.
|
Command v0.9.0_table_advanced builds v090_table_advanced.docx with repeating table headers, unbreakable rows, vertical cell alignment, and vertical text direction. |
|
v0.9.0_watermark_security
command
Command v0.9.0_watermark_security builds a protected document with a tiled diagonal text watermark, an image-watermark companion file, and exception ranges (w:permStart / w:permEnd) that remain editable.
|
Command v0.9.0_watermark_security builds a protected document with a tiled diagonal text watermark, an image-watermark companion file, and exception ranges (w:permStart / w:permEnd) that remain editable. |
|
word_diag
command
Command word_diag writes six single-module .docx files so Microsoft Word can isolate which OpenXML feature refuses to open.
|
Command word_diag writes six single-module .docx files so Microsoft Word can isolate which OpenXML feature refuses to open. |
|
pkg
|
|
|
tests
|
|
|
matrix
command
Command generate_full_feature_docs writes 50–100 randomly combined GoWord feature documents into ./test_output_docs.
|
Command generate_full_feature_docs writes 50–100 randomly combined GoWord feature documents into ./test_output_docs. |