Documentation
¶
Overview ¶
Package document 提供了用于创建、编辑和操作 Microsoft Word 文档的 Golang 库。
WordZero 专注于现代的 Office Open XML (OOXML) 格式(.docx 文件), 提供了简单易用的 API 来创建和修改 Word 文档。
主要功能 ¶
## 基础功能 - 创建新的 Word 文档 - 打开和解析现有的 .docx 文件 - 添加和格式化文本内容 - 设置段落样式和对齐方式 - 配置字体、颜色和文本格式 - 设置行间距和段落间距 - 错误处理和日志记录
## 高级功能 ✨ 新增 - **页眉页脚**: 支持默认、首页、偶数页不同的页眉页脚设置 - **目录生成**: 基于标题样式自动生成目录,支持超链接和页码 - **脚注尾注**: 完整的脚注和尾注功能,支持多种编号格式 - **列表编号**: 无序列表和有序列表,支持多级嵌套 - **页面设置**: 页面尺寸、方向、边距等完整页面属性设置 - **表格功能**: 强大的表格创建、格式化和样式设置功能 - **样式系统**: 18种预定义样式和自定义样式支持
快速开始 ¶
创建一个简单的文档:
doc := document.New()
doc.AddParagraph("Hello, World!")
err := doc.Save("hello.docx")
创建带格式的文档:
doc := document.New()
// 添加格式化标题
titleFormat := &document.TextFormat{
Bold: true,
FontSize: 18,
FontColor: "FF0000", // 红色
FontName: "微软雅黑",
}
title := doc.AddFormattedParagraph("文档标题", titleFormat)
title.SetAlignment(document.AlignCenter)
// 添加正文段落
para := doc.AddParagraph("这是正文内容...")
para.SetSpacing(&document.SpacingConfig{
LineSpacing: 1.5, // 1.5倍行距
BeforePara: 12, // 段前12磅
AfterPara: 6, // 段后6磅
FirstLineIndent: 24, // 首行缩进24磅
})
err := doc.Save("formatted.docx")
打开现有文档:
doc, err := document.Open("existing.docx")
if err != nil {
log.Fatal(err)
}
// 读取段落内容
for i, para := range doc.Body.Paragraphs {
fmt.Printf("段落 %d: ", i+1)
for _, run := range para.Runs {
fmt.Print(run.Text.Content)
}
fmt.Println()
}
高级功能示例 ¶
## 页眉页脚功能
// 添加页眉 doc.AddHeader(document.HeaderFooterTypeDefault, "这是页眉") // 添加带页码的页脚 doc.AddFooterWithPageNumber(document.HeaderFooterTypeDefault, "第", true) // 设置首页不同 doc.SetDifferentFirstPage(true)
## 目录生成
// 添加带书签的标题
doc.AddHeadingWithBookmark("第一章 概述", 1, "chapter1")
doc.AddHeadingWithBookmark("1.1 背景", 2, "section1_1")
// 生成目录
tocConfig := document.DefaultTOCConfig()
tocConfig.Title = "目录"
tocConfig.MaxLevel = 3
doc.GenerateTOC(tocConfig)
## 脚注和尾注
// 添加脚注
doc.AddFootnote("这是正文内容", "这是脚注内容")
// 添加尾注
doc.AddEndnote("更多说明", "这是尾注内容")
// 自定义脚注配置
footnoteConfig := &document.FootnoteConfig{
NumberFormat: document.FootnoteFormatLowerRoman,
StartNumber: 1,
RestartEach: document.FootnoteRestartEachPage,
Position: document.FootnotePositionPageBottom,
}
doc.SetFootnoteConfig(footnoteConfig)
## 列表功能
// 无序列表
doc.AddBulletList("列表项1", 0, document.BulletTypeDot)
doc.AddBulletList("子项目", 1, document.BulletTypeCircle)
// 有序列表
doc.AddNumberedList("第一项", 0, document.ListTypeDecimal)
doc.AddNumberedList("第二项", 0, document.ListTypeDecimal)
// 多级列表
items := []document.ListItem{
{Text: "一级项目", Level: 0, Type: document.ListTypeDecimal},
{Text: "二级项目", Level: 1, Type: document.ListTypeLowerLetter},
{Text: "三级项目", Level: 2, Type: document.ListTypeLowerRoman},
}
doc.CreateMultiLevelList(items)
## 页面设置
// 设置页面为A4横向
doc.SetPageOrientation(document.OrientationLandscape)
// 设置页面边距(毫米)
doc.SetPageMargins(25, 25, 25, 25)
// 完整页面设置
pageSettings := &document.PageSettings{
Size: document.PageSizeLetter,
Orientation: document.OrientationPortrait,
MarginTop: 30,
MarginRight: 20,
MarginBottom: 30,
MarginLeft: 20,
HeaderDistance: 15,
FooterDistance: 15,
GutterWidth: 0,
}
doc.SetPageSettings(pageSettings)
## 表格功能
// 创建表格
table := doc.CreateTable(&document.TableConfig{
Rows: 3,
Cols: 3,
Width: 5000,
})
// 设置单元格内容
table.SetCellText(0, 0, "标题")
// 设置表格样式
table.ApplyTableStyle(&document.TableStyleConfig{
HeaderRow: true,
FirstColumn: true,
BandedRows: true,
BandedCols: false,
})
错误处理 ¶
库提供了统一的错误处理机制:
doc, err := document.Open("nonexistent.docx")
if err != nil {
var docErr *document.DocumentError
if errors.As(err, &docErr) {
Errorf("文档操作失败 - 操作: %s, 错误: %v", docErr.Operation, docErr.Cause)
fmt.Printf("操作: %s, 错误: %v\n", docErr.Operation, docErr.Cause)
}
}
日志记录 ¶
可以配置日志级别来控制输出:
// 设置为调试模式 document.SetGlobalLevel(document.LogLevelDebug) // 只显示错误 document.SetGlobalLevel(document.LogLevelError)
文本格式 ¶
TextFormat 结构体支持多种文本格式选项:
format := &document.TextFormat{
Bold: true, // 粗体
Italic: true, // 斜体
FontSize: 14, // 字体大小(磅)
FontColor: "0000FF", // 字体颜色(十六进制)
FontName: "Times New Roman", // 字体名称
}
段落对齐 ¶
支持四种对齐方式:
para.SetAlignment(document.AlignLeft) // 左对齐 para.SetAlignment(document.AlignCenter) // 居中对齐 para.SetAlignment(document.AlignRight) // 右对齐 para.SetAlignment(document.AlignJustify) // 两端对齐
间距配置 ¶
可以精确控制段落间距:
config := &document.SpacingConfig{
LineSpacing: 1.5, // 行间距(倍数)
BeforePara: 12, // 段前间距(磅)
AfterPara: 6, // 段后间距(磅)
FirstLineIndent: 24, // 首行缩进(磅)
}
para.SetSpacing(config)
注意事项 ¶
- 字体大小以磅为单位,内部会自动转换为 Word 的半磅单位 - 颜色值使用十六进制格式,不需要 # 前缀 - 间距值以磅为单位,内部会转换为 TWIPs(1磅=20TWIPs) - 所有文本内容都使用 UTF-8 编码 - 页眉页脚类型包括:Default(默认)、First(首页)、Even(偶数页) - 脚注和尾注会自动编号,支持多种编号格式和重启规则 - 列表支持多级嵌套,最多支持9级缩进 - 目录功能需要先添加带书签的标题,然后调用生成目录方法
更多详细信息和示例,请参阅各个类型和函数的文档。
Package document 提供Word文档的核心操作功能 ¶
Package document 错误处理 ¶
Package document 提供Word文档域字段结构 ¶
Package document 提供Word文档脚注和尾注操作功能 ¶
Package document 提供Word文档的页眉页脚操作功能 ¶
Package document 提供Word文档的图片操作功能 ¶
Package document 日志系统 ¶
Package document 提供Word文档的核心操作功能 ¶
Package document 提供Word文档列表和编号操作功能 ¶
Package document 提供Word文档的页面设置功能 ¶
Package document 提供Word文档属性操作功能 ¶
Package document 提供Word文档的SDT(Structured Document Tag)结构 ¶
Package document 提供Word文档的表格操作功能 ¶
Package document 模板功能实现 ¶
Package document 提供Word文档目录生成功能
Index ¶
- Variables
- func Debug(msg string)
- func Debugf(format string, args ...interface{})
- func Error(msg string)
- func Errorf(format string, args ...interface{})
- func Info(msg string)
- func Infof(format string, args ...interface{})
- func SetGlobalLevel(level LogLevel)
- func SetGlobalOutput(output io.Writer)
- func Warn(msg string)
- func Warnf(format string, args ...interface{})
- func WrapError(operation string, err error) error
- func WrapErrorWithContext(operation string, err error, context string) error
- type AbstractNum
- type AbstractNumReference
- type AlignmentType
- type AnchorDrawing
- type AppProperties
- type AvLst
- type Blip
- type BlipFill
- type Body
- type BodyElement
- type Bold
- type BoldCs
- type BookmarkEnd
- type BookmarkStart
- type BorderConfig
- type BorderStyle
- type Break
- type BulletType
- type CNvGraphicFramePr
- type CNvPicPr
- type CNvPr
- type CPText
- type CantSplit
- type CellAlignment
- type CellBorderConfig
- type CellFormat
- type CellImageConfig
- type CellInfo
- type CellIterator
- type CellListConfig
- type CellTextDirection
- type CellVerticalAlignment
- type CharacterSpacingControl
- type Color
- type Columns
- type ContentTypes
- type CoreProperties
- type DCDate
- type DCText
- type Default
- type DefaultTabStop
- type DocGrid
- type DocGridType
- type DocPart
- type DocPartGallery
- type DocPartObj
- type DocPartUnique
- type Document
- func (d *Document) AddBulletList(text string, level int, bulletType BulletType) *Paragraph
- func (d *Document) AddCellImage(table *Table, row, col int, config *CellImageConfig) (*ImageInfo, error)
- func (d *Document) AddCellImageFromData(table *Table, row, col int, data []byte, widthMM float64) (*ImageInfo, error)
- func (d *Document) AddCellImageFromFile(table *Table, row, col int, filePath string, widthMM float64) (*ImageInfo, error)
- func (d *Document) AddEndnote(text string, endnoteText string) error
- func (d *Document) AddFooter(footerType HeaderFooterType, text string) error
- func (d *Document) AddFooterWithPageNumber(footerType HeaderFooterType, text string, showPageNum bool) error
- func (d *Document) AddFootnote(text string, footnoteText string) error
- func (d *Document) AddFootnoteToRun(run *Run, footnoteText string) error
- func (d *Document) AddFormattedFooter(footerType HeaderFooterType, config *HeaderFooterConfig) error
- func (d *Document) AddFormattedHeader(headerType HeaderFooterType, config *HeaderFooterConfig) error
- func (d *Document) AddFormattedParagraph(text string, format *TextFormat) *Paragraph
- func (d *Document) AddHeader(headerType HeaderFooterType, text string) error
- func (d *Document) AddHeaderWithPageNumber(headerType HeaderFooterType, text string, showPageNum bool) error
- func (d *Document) AddHeadingParagraph(text string, level int) *Paragraph
- func (d *Document) AddHeadingParagraphWithBookmark(text string, level int, bookmarkName string) *Paragraph
- func (d *Document) AddHeadingWithBookmark(text string, level int, bookmarkName string) *Paragraph
- func (d *Document) AddImageFromData(imageData []byte, fileName string, format ImageFormat, width, height int, ...) (*ImageInfo, error)
- func (d *Document) AddImageFromDataWithoutElement(imageData []byte, fileName string, format ImageFormat, width, height int, ...) (*ImageInfo, error)
- func (d *Document) AddImageFromFile(filePath string, config *ImageConfig) (*ImageInfo, error)
- func (d *Document) AddListItem(text string, config *ListConfig) *Paragraph
- func (d *Document) AddMathFormula(latex string, isBlock bool) *MathParagraph
- func (d *Document) AddNumberedList(text string, level int, numType ListType) *Paragraph
- func (d *Document) AddPageBreak()
- func (d *Document) AddParagraph(text string) *Paragraph
- func (d *Document) AddTable(config *TableConfig) (*Table, error)
- func (d *Document) AutoGenerateTOC(config *TOCConfig) error
- func (d *Document) ClearDocGrid() error
- func (d *Document) CreateMultiLevelList(items []ListItem) error
- func (d *Document) CreateTOCSDT(title string, maxLevel int) *SDT
- func (d *Document) CreateTable(config *TableConfig) (*Table, error)
- func (d *Document) GenerateTOC(config *TOCConfig) error
- func (d *Document) GetDocumentProperties() (*DocumentProperties, error)
- func (d *Document) GetEndnoteCount() int
- func (d *Document) GetFootnoteCount() int
- func (d *Document) GetHeadingCount() map[int]int
- func (d *Document) GetPageSettings() *PageSettings
- func (d *Document) GetParts() map[string][]byte
- func (d *Document) GetStyleManager() *style.StyleManager
- func (d *Document) ListHeadings() []TOCEntry
- func (d *Document) RemoveElementAt(index int) bool
- func (d *Document) RemoveEndnote(endnoteID string) error
- func (d *Document) RemoveFootnote(footnoteID string) error
- func (d *Document) RemoveParagraph(paragraph *Paragraph) bool
- func (d *Document) RemoveParagraphAt(index int) bool
- func (d *Document) ResizeImage(imageInfo *ImageInfo, size *ImageSize) error
- func (d *Document) RestartNumbering(numID string)
- func (d *Document) Save(filename string) error
- func (d *Document) SetAuthor(author string) error
- func (d *Document) SetCategory(category string) error
- func (d *Document) SetCustomPageSize(width, height float64) error
- func (d *Document) SetDescription(description string) error
- func (d *Document) SetDifferentFirstPage(different bool)
- func (d *Document) SetDocGrid(gridType DocGridType, linePitch int, charSpace int) error
- func (d *Document) SetDocumentProperties(properties *DocumentProperties) error
- func (d *Document) SetFootnoteConfig(config *FootnoteConfig) error
- func (d *Document) SetGutterWidth(width float64) error
- func (d *Document) SetHeaderFooterDistance(header, footer float64) error
- func (d *Document) SetImageAlignment(imageInfo *ImageInfo, alignment AlignmentType) error
- func (d *Document) SetImageAltText(imageInfo *ImageInfo, altText string) error
- func (d *Document) SetImagePosition(imageInfo *ImageInfo, position ImagePosition, offsetX, offsetY float64) error
- func (d *Document) SetImageTitle(imageInfo *ImageInfo, title string) error
- func (d *Document) SetImageWrapText(imageInfo *ImageInfo, wrapText ImageWrapText) error
- func (d *Document) SetKeywords(keywords string) error
- func (d *Document) SetPageMargins(top, right, bottom, left float64) error
- func (d *Document) SetPageOrientation(orientation PageOrientation) error
- func (d *Document) SetPageSettings(settings *PageSettings) error
- func (d *Document) SetPageSize(size PageSize) error
- func (d *Document) SetSubject(subject string) error
- func (d *Document) SetTOCStyle(level int, style *TextFormat) error
- func (d *Document) SetTitle(title string) error
- func (d *Document) ToBytes() ([]byte, error)
- func (d *Document) UpdateStatistics() error
- func (d *Document) UpdateTOC() error
- type DocumentError
- type DocumentProperties
- type DrawingDocPr
- type DrawingElement
- type DrawingExtent
- type DrawingGraphic
- type EffectExtent
- type Endnote
- type EndnoteNumFmt
- type EndnoteNumRestart
- type EndnoteNumStart
- type EndnotePos
- type EndnotePr
- type EndnoteProperties
- type EndnoteReference
- type Endnotes
- type Ext
- type FieldChar
- type FillRect
- type FontFamily
- type FontSize
- type FontSizeCs
- type Footer
- type FooterReference
- type Footnote
- type FootnoteConfig
- type FootnoteManager
- type FootnoteNumFmt
- type FootnoteNumRestart
- type FootnoteNumStart
- type FootnoteNumberFormat
- type FootnotePos
- type FootnotePosition
- type FootnotePr
- type FootnoteProperties
- type FootnoteReference
- type FootnoteRestart
- type FootnoteType
- type Footnotes
- type GraphicData
- type GraphicFrameLocks
- type GridSpan
- type Header
- type HeaderFooterConfig
- type HeaderFooterReference
- type HeaderFooterType
- type HideMark
- type Highlight
- type HorizontalPosition
- type Hyperlink
- type HyperlinkField
- type ILevel
- type ImageConfig
- type ImageFormat
- type ImageInfo
- type ImagePosition
- type ImageSize
- type ImageWrapText
- type Indentation
- type InlineDrawing
- type InstrText
- type Italic
- type ItalicCs
- type Justification
- type KeepLines
- type KeepNext
- type Level
- type LevelIndent
- type LevelJc
- type LevelPPr
- type LevelRPr
- type LevelText
- type ListConfig
- type ListItem
- type ListType
- type LogLevel
- type Logger
- func (l *Logger) Debug(msg string)
- func (l *Logger) Debugf(format string, args ...interface{})
- func (l *Logger) Error(msg string)
- func (l *Logger) Errorf(format string, args ...interface{})
- func (l *Logger) Info(msg string)
- func (l *Logger) Infof(format string, args ...interface{})
- func (l *Logger) SetLevel(level LogLevel)
- func (l *Logger) SetOutput(output io.Writer)
- func (l *Logger) Warn(msg string)
- func (l *Logger) Warnf(format string, args ...interface{})
- type MathParagraph
- type NoWrap
- type NumFmt
- type NumID
- type NumInstance
- type Numbering
- type NumberingManager
- type NumberingProperties
- type NvPicPr
- type Off
- type OfficeMath
- type OfficeMathPara
- type OutlineLevel
- type Override
- type PageBreakBefore
- type PageMargin
- type PageNumType
- type PageNumber
- type PageOrientation
- type PageRefField
- type PageSettings
- type PageSize
- type PageSizeXML
- type Paragraph
- func (p *Paragraph) AddFormattedText(text string, format *TextFormat)
- func (p *Paragraph) AddInlineMath(ommlContent string)
- func (p *Paragraph) AddPageBreak()
- func (p *Paragraph) ElementType() string
- func (p *Paragraph) SetAlignment(alignment AlignmentType)
- func (p *Paragraph) SetBold(bold bool)
- func (p *Paragraph) SetBorder(top, left, bottom, right *ParagraphBorderConfig)
- func (p *Paragraph) SetColor(color string)
- func (p *Paragraph) SetFontFamily(name string)
- func (p *Paragraph) SetFontSize(size int)
- func (p *Paragraph) SetHighlight(color string)
- func (p *Paragraph) SetHorizontalRule(style BorderStyle, size int, color string)
- func (p *Paragraph) SetIndentation(firstLineCm, leftCm, rightCm float64)
- func (p *Paragraph) SetItalic(italic bool)
- func (p *Paragraph) SetKeepLines(keep bool)
- func (p *Paragraph) SetKeepWithNext(keep bool)
- func (p *Paragraph) SetOutlineLevel(level int)
- func (p *Paragraph) SetPageBreakBefore(pageBreak bool)
- func (p *Paragraph) SetParagraphFormat(config *ParagraphFormatConfig)
- func (p *Paragraph) SetSnapToGrid(snapToGrid bool)
- func (p *Paragraph) SetSpacing(config *SpacingConfig)
- func (p *Paragraph) SetStrike(strike bool)
- func (p *Paragraph) SetStyle(styleID string)
- func (p *Paragraph) SetUnderline(underline bool)
- func (p *Paragraph) SetWidowControl(control bool)
- type ParagraphBorder
- type ParagraphBorderConfig
- type ParagraphBorderLine
- type ParagraphFormatConfig
- type ParagraphProperties
- type ParagraphStyle
- type PicElement
- type PicLocks
- type PolygonLineTo
- type PolygonStart
- type PosAlign
- type PosOffset
- type PrstGeom
- type Relationship
- type Relationships
- type RowBreakConfig
- type RowHeightConfig
- type RowHeightRule
- type Run
- type RunProperties
- type SDT
- type SDTColor
- type SDTContent
- type SDTEndPr
- type SDTID
- type SDTPlaceholder
- type SDTProperties
- type SectionProperties
- type Settings
- type ShadingConfig
- type ShadingPattern
- type SimplePosition
- type SnapToGrid
- type SpPr
- type Spacing
- type SpacingConfig
- type Start
- type Stretch
- type Strike
- type TOCConfig
- type TOCEntry
- type TOCField
- type Tab
- type TabDef
- type Table
- func (t *Table) AddCellFormattedParagraph(row, col int, text string, format *TextFormat) (*Paragraph, error)
- func (t *Table) AddCellFormattedText(row, col int, text string, format *TextFormat) error
- func (t *Table) AddCellList(row, col int, config *CellListConfig) error
- func (t *Table) AddCellParagraph(row, col int, text string) (*Paragraph, error)
- func (t *Table) AddNestedTable(row, col int, config *TableConfig) (*Table, error)
- func (t *Table) AppendColumn(data []string, width int) error
- func (t *Table) AppendRow(data []string) error
- func (t *Table) ApplyTableStyle(config *TableStyleConfig) error
- func (t *Table) ClearCellContent(row, col int) error
- func (t *Table) ClearCellFormat(row, col int) error
- func (t *Table) ClearCellParagraphs(row, col int) error
- func (t *Table) ClearTable()
- func (t *Table) CopyTable() *Table
- func (t *Table) CreateCustomTableStyle(styleID, styleName string, borderConfig *TableBorderConfig, ...) error
- func (t *Table) DeleteColumn(colIndex int) error
- func (t *Table) DeleteColumns(startIndex, endIndex int) error
- func (t *Table) DeleteRow(rowIndex int) error
- func (t *Table) DeleteRows(startIndex, endIndex int) error
- func (t *Table) ElementType() string
- func (t *Table) FindCells(predicate func(row, col int, cell *TableCell, text string) bool) ([]*CellInfo, error)
- func (t *Table) FindCellsByText(searchText string, exactMatch bool) ([]*CellInfo, error)
- func (t *Table) ForEach(fn func(row, col int, cell *TableCell, text string) error) error
- func (t *Table) ForEachInColumn(colIndex int, fn func(row int, cell *TableCell, text string) error) error
- func (t *Table) ForEachInRow(rowIndex int, fn func(col int, cell *TableCell, text string) error) error
- func (t *Table) GetCell(row, col int) (*TableCell, error)
- func (t *Table) GetCellFormat(row, col int) (*CellFormat, error)
- func (t *Table) GetCellParagraphs(row, col int) ([]Paragraph, error)
- func (t *Table) GetCellRange(startRow, startCol, endRow, endCol int) ([]*CellInfo, error)
- func (t *Table) GetCellText(row, col int) (string, error)
- func (t *Table) GetCellTextDirection(row, col int) (CellTextDirection, error)
- func (t *Table) GetColumnCount() int
- func (t *Table) GetMergedCellInfo(row, col int) (map[string]interface{}, error)
- func (t *Table) GetNestedTables(row, col int) ([]Table, error)
- func (t *Table) GetRowCount() int
- func (t *Table) GetRowHeight(rowIndex int) (*RowHeightConfig, error)
- func (t *Table) GetTableBreakInfo() map[string]interface{}
- func (t *Table) GetTableLayout() *TableLayoutConfig
- func (t *Table) InsertColumn(position int, data []string, width int) error
- func (t *Table) InsertRow(position int, data []string) error
- func (t *Table) IsCellMerged(row, col int) (bool, error)
- func (t *Table) IsRowHeader(rowIndex int) (bool, error)
- func (t *Table) IsRowKeepTogether(rowIndex int) (bool, error)
- func (t *Table) MergeCellsHorizontal(row, startCol, endCol int) error
- func (t *Table) MergeCellsRange(startRow, endRow, startCol, endCol int) error
- func (t *Table) MergeCellsVertical(startRow, endRow, col int) error
- func (t *Table) NewCellIterator() *CellIterator
- func (t *Table) RemoveCellBorders(row, col int) error
- func (t *Table) RemoveTableBorders() error
- func (t *Table) SetAlternatingRowColors(evenRowColor, oddRowColor string) error
- func (t *Table) SetCellBorders(row, col int, config *CellBorderConfig) error
- func (t *Table) SetCellFormat(row, col int, format *CellFormat) error
- func (t *Table) SetCellFormattedText(row, col int, text string, format *TextFormat) error
- func (t *Table) SetCellPadding(row, col int, padding int) error
- func (t *Table) SetCellShading(row, col int, config *ShadingConfig) error
- func (t *Table) SetCellText(row, col int, text string) error
- func (t *Table) SetCellTextDirection(row, col int, direction CellTextDirection) error
- func (t *Table) SetHeaderRows(startRow, endRow int) error
- func (t *Table) SetRowAsHeader(rowIndex int, isHeader bool) error
- func (t *Table) SetRowHeight(rowIndex int, config *RowHeightConfig) error
- func (t *Table) SetRowHeightRange(startRow, endRow int, config *RowHeightConfig) error
- func (t *Table) SetRowKeepTogether(rowIndex int, keepTogether bool) error
- func (t *Table) SetRowKeepWithNext(rowIndex int, keepWithNext bool) error
- func (t *Table) SetTableAlignment(alignment TableAlignment) error
- func (t *Table) SetTableBorders(config *TableBorderConfig) error
- func (t *Table) SetTableLayout(config *TableLayoutConfig) error
- func (t *Table) SetTablePageBreak(config *TablePageBreakConfig) error
- func (t *Table) SetTableShading(config *ShadingConfig) error
- func (t *Table) UnmergeCells(row, col int) error
- type TableAlignment
- type TableAnalysis
- type TableBorder
- type TableBorderConfig
- type TableBorders
- type TableBreakRule
- type TableCell
- type TableCellBorder
- type TableCellBorders
- type TableCellMargins
- type TableCellMarginsCell
- type TableCellProperties
- type TableCellShading
- type TableCellSpace
- type TableCellSpaceCell
- type TableCellW
- type TableConfig
- type TableGrid
- type TableGridCol
- type TableIndentation
- type TableJc
- type TableLayoutConfig
- type TableLayoutType
- type TableLook
- type TablePageBreakConfig
- type TablePosition
- type TablePositioning
- type TableProperties
- type TableRow
- type TableRowH
- type TableRowProperties
- type TableRowPropertiesExtended
- type TableShading
- type TableStyle
- type TableStyleConfig
- type TableStyleTemplate
- type TableTextWrap
- type TableWidth
- type Tabs
- type TblHeader
- type Template
- type TemplateAnalysis
- type TemplateBlock
- type TemplateData
- func (td *TemplateData) Clear()
- func (td *TemplateData) FromStruct(data interface{}) error
- func (td *TemplateData) GetCondition(name string) (bool, bool)
- func (td *TemplateData) GetImage(name string) (*TemplateImageData, bool)
- func (td *TemplateData) GetList(name string) ([]interface{}, bool)
- func (td *TemplateData) GetVariable(name string) (interface{}, bool)
- func (td *TemplateData) Merge(other *TemplateData)
- func (td *TemplateData) SetCondition(name string, value bool)
- func (td *TemplateData) SetImage(name, filePath string, config *ImageConfig)
- func (td *TemplateData) SetImageFromData(name string, data []byte, config *ImageConfig)
- func (td *TemplateData) SetImageWithDetails(name, filePath string, data []byte, config *ImageConfig, altText, title string)
- func (td *TemplateData) SetList(name string, list []interface{})
- func (td *TemplateData) SetVariable(name string, value interface{})
- func (td *TemplateData) SetVariables(variables map[string]interface{})
- type TemplateEngine
- func (te *TemplateEngine) ClearCache()
- func (te *TemplateEngine) GetTemplate(name string) (*Template, error)
- func (te *TemplateEngine) LoadTemplate(name, content string) (*Template, error)
- func (te *TemplateEngine) LoadTemplateFromDocument(name string, doc *Document) (*Template, error)
- func (te *TemplateEngine) RemoveTemplate(name string)
- func (te *TemplateEngine) RenderTemplateToDocument(templateName string, data *TemplateData) (*Document, error)
- func (te *TemplateEngine) RenderToDocument(templateName string, data *TemplateData) (*Document, error)
- func (te *TemplateEngine) SetBasePath(path string)
- func (te *TemplateEngine) ValidateTemplate(template *Template) error
- type TemplateImageData
- type TemplateLogger
- type TemplateRenderer
- func (tr *TemplateRenderer) AnalyzeTemplate(templateName string) (*TemplateAnalysis, error)
- func (tr *TemplateRenderer) LoadTemplateFromFile(name, filePath string) (*Template, error)
- func (tr *TemplateRenderer) RenderTemplate(templateName string, data *TemplateData) (*Document, error)
- func (tr *TemplateRenderer) SetLogging(enabled bool)
- type Text
- type TextDirection
- type TextFormat
- type TitlePage
- type Underline
- type VAlign
- type VMerge
- type ValidationError
- type VerticalPosition
- type WidowControl
- type WrapNone
- type WrapPolygon
- type WrapSquare
- type WrapThrough
- type WrapTight
- type WrapTopAndBottom
- type Xfrm
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalidDocument 无效文档 ErrInvalidDocument = errors.New("invalid document") // ErrDocumentNotFound 文档未找到 ErrDocumentNotFound = errors.New("document not found") // ErrInvalidFormat 无效格式 ErrInvalidFormat = errors.New("invalid format") // ErrCorruptedFile 文件损坏 ErrCorruptedFile = errors.New("corrupted file") // ErrUnsupportedOperation 不支持的操作 ErrUnsupportedOperation = errors.New("unsupported operation") )
预定义错误类型
var ( // ErrTemplateNotFound 模板未找到 ErrTemplateNotFound = NewDocumentError("template_not_found", fmt.Errorf("template not found"), "") // ErrTemplateSyntaxError 模板语法错误 ErrTemplateSyntaxError = NewDocumentError("template_syntax_error", fmt.Errorf("template syntax error"), "") // ErrTemplateRenderError 模板渲染错误 ErrTemplateRenderError = NewDocumentError("template_render_error", fmt.Errorf("template render error"), "") // ErrInvalidTemplateData 无效模板数据 ErrInvalidTemplateData = NewDocumentError("invalid_template_data", fmt.Errorf("invalid template data"), "") // ErrBlockNotFound 块未找到 ErrBlockNotFound = NewDocumentError("block_not_found", fmt.Errorf("block not found"), "") // ErrInvalidBlockDefinition 无效块定义 ErrInvalidBlockDefinition = NewDocumentError("invalid_block_definition", fmt.Errorf("invalid block definition"), "") )
模板相关错误
var ( // ErrInvalidPageSettings 无效的页面设置 ErrInvalidPageSettings = errors.New("invalid page settings") )
页面设置相关错误
Functions ¶
Types ¶
type AbstractNum ¶
type AbstractNum struct {
XMLName xml.Name `xml:"w:abstractNum"`
AbstractNumID string `xml:"w:abstractNumId,attr"`
Levels []*Level `xml:"w:lvl"`
}
AbstractNum 抽象编号定义
type AbstractNumReference ¶
type AbstractNumReference struct {
XMLName xml.Name `xml:"w:abstractNumId"`
Val string `xml:"w:val,attr"`
}
AbstractNumReference 抽象编号引用
type AlignmentType ¶
type AlignmentType string
AlignmentType 对齐类型
const ( // AlignLeft 左对齐 AlignLeft AlignmentType = "left" // AlignCenter 居中对齐 AlignCenter AlignmentType = "center" // AlignRight 右对齐 AlignRight AlignmentType = "right" // AlignJustify 两端对齐 AlignJustify AlignmentType = "both" )
type AnchorDrawing ¶ added in v1.3.3
type AnchorDrawing struct {
XMLName xml.Name `xml:"wp:anchor"`
DistT string `xml:"distT,attr,omitempty"`
DistB string `xml:"distB,attr,omitempty"`
DistL string `xml:"distL,attr,omitempty"`
DistR string `xml:"distR,attr,omitempty"`
SimplePos string `xml:"simplePos,attr,omitempty"`
RelativeHeight string `xml:"relativeHeight,attr,omitempty"`
BehindDoc string `xml:"behindDoc,attr,omitempty"`
Locked string `xml:"locked,attr,omitempty"`
LayoutInCell string `xml:"layoutInCell,attr,omitempty"`
AllowOverlap string `xml:"allowOverlap,attr,omitempty"`
SimplePosition *SimplePosition `xml:"wp:simplePos,omitempty"`
PositionH *HorizontalPosition `xml:"wp:positionH,omitempty"`
PositionV *VerticalPosition `xml:"wp:positionV,omitempty"`
Extent *DrawingExtent `xml:"wp:extent"`
EffectExtent *EffectExtent `xml:"wp:effectExtent,omitempty"`
WrapNone *WrapNone `xml:"wp:wrapNone,omitempty"`
WrapSquare *WrapSquare `xml:"wp:wrapSquare,omitempty"`
WrapTight *WrapTight `xml:"wp:wrapTight,omitempty"`
WrapThrough *WrapThrough `xml:"wp:wrapThrough,omitempty"`
WrapTopAndBottom *WrapTopAndBottom `xml:"wp:wrapTopAndBottom,omitempty"`
DocPr *DrawingDocPr `xml:"wp:docPr"`
CNvGraphicFramePr *CNvGraphicFramePr `xml:"wp:cNvGraphicFramePr,omitempty"`
Graphic *DrawingGraphic `xml:"a:graphic"`
}
AnchorDrawing 浮动绘图
type AppProperties ¶
type AppProperties struct {
XMLName xml.Name `xml:"Properties"`
Xmlns string `xml:"xmlns,attr"`
XmlnsVT string `xml:"xmlns:vt,attr"`
Application string `xml:"Application,omitempty"`
DocSecurity int `xml:"DocSecurity,omitempty"`
ScaleCrop bool `xml:"ScaleCrop,omitempty"`
LinksUpToDate bool `xml:"LinksUpToDate,omitempty"`
Pages int `xml:"Pages,omitempty"`
Words int `xml:"Words,omitempty"`
Characters int `xml:"Characters,omitempty"`
Paragraphs int `xml:"Paragraphs,omitempty"`
Lines int `xml:"Lines,omitempty"`
}
AppProperties 应用程序属性XML结构
type BlipFill ¶ added in v1.3.3
type BlipFill struct {
XMLName xml.Name `xml:"pic:blipFill"`
Blip *Blip `xml:"a:blip"`
Stretch *Stretch `xml:"a:stretch"`
}
BlipFill 图片填充
type Body ¶
type Body struct {
XMLName xml.Name `xml:"w:body"`
Elements []interface{} `xml:"-"` // 不序列化此字段,使用自定义方法
}
Body 表示文档主体
func (*Body) MarshalXML ¶
MarshalXML 自定义XML序列化,按照元素顺序输出
type BookmarkEnd ¶
BookmarkEnd 书签结束
type BookmarkStart ¶
type BookmarkStart struct {
XMLName xml.Name `xml:"w:bookmarkStart"`
ID string `xml:"w:id,attr"`
Name string `xml:"w:name,attr"`
}
BookmarkStart 书签开始
func (*BookmarkStart) ElementType ¶
func (b *BookmarkStart) ElementType() string
ElementType 返回书签开始元素类型
type BorderConfig ¶
type BorderConfig struct {
Style BorderStyle // 边框样式
Width int // 边框宽度(1/8磅)
Color string // 边框颜色(十六进制,如 "FF0000")
Space int // 边框间距
}
BorderConfig 边框配置
type BorderStyle ¶
type BorderStyle string
BorderStyle 边框样式常量
const ( BorderStyleNone BorderStyle = "none" // 无边框 BorderStyleSingle BorderStyle = "single" // 单线 BorderStyleThick BorderStyle = "thick" // 粗线 BorderStyleDouble BorderStyle = "double" // 双线 BorderStyleDotted BorderStyle = "dotted" // 点线 BorderStyleDashed BorderStyle = "dashed" // 虚线 BorderStyleDotDash BorderStyle = "dotDash" // 点划线 BorderStyleDotDotDash BorderStyle = "dotDotDash" // 双点划线 BorderStyleTriple BorderStyle = "triple" // 三线 BorderStyleThinThickSmallGap BorderStyle = "thinThickSmallGap" // 细粗细线(小间距) BorderStyleThickThinSmallGap BorderStyle = "thickThinSmallGap" // 粗细粗线(小间距) BorderStyleThinThickThinSmallGap BorderStyle = "thinThickThinSmallGap" // 细粗细线(小间距) BorderStyleThinThickMediumGap BorderStyle = "thinThickMediumGap" // 细粗细线(中间距) BorderStyleThickThinMediumGap BorderStyle = "thickThinMediumGap" // 粗细粗线(中间距) BorderStyleThinThickThinMediumGap BorderStyle = "thinThickThinMediumGap" // 细粗细线(中间距) BorderStyleThinThickLargeGap BorderStyle = "thinThickLargeGap" // 细粗细线(大间距) BorderStyleThickThinLargeGap BorderStyle = "thickThinLargeGap" // 粗细粗线(大间距) BorderStyleThinThickThinLargeGap BorderStyle = "thinThickThinLargeGap" // 细粗细线(大间距) BorderStyleWave BorderStyle = "wave" // 波浪线 BorderStyleDoubleWave BorderStyle = "doubleWave" // 双波浪线 BorderStyleDashSmallGap BorderStyle = "dashSmallGap" // 虚线(小间距) BorderStyleDashDotStroked BorderStyle = "dashDotStroked" // 划点线 BorderStyleThreeDEmboss BorderStyle = "threeDEmboss" // 3D浮雕 BorderStyleThreeDEngrave BorderStyle = "threeDEngrave" // 3D雕刻 BorderStyleOutset BorderStyle = "outset" // 外凸 BorderStyleInset BorderStyle = "inset" // 内凹 )
type Break ¶ added in v1.5.0
type Break struct {
XMLName xml.Name `xml:"w:br"`
Type string `xml:"w:type,attr,omitempty"` // "page" 表示分页符 / "page" indicates a page break
}
Break 分页符 Break represents page breaks in Word documents
type BulletType ¶
type BulletType string
BulletType 项目符号类型
const ( // BulletTypeDot 圆点符号 BulletTypeDot BulletType = "•" // BulletTypeCircle 空心圆 BulletTypeCircle BulletType = "○" // BulletTypeSquare 方块 BulletTypeSquare BulletType = "■" // BulletTypeDash 短横线 BulletTypeDash BulletType = "–" // BulletTypeArrow 箭头 BulletTypeArrow BulletType = "→" )
type CNvGraphicFramePr ¶ added in v1.3.3
type CNvGraphicFramePr struct {
XMLName xml.Name `xml:"wp:cNvGraphicFramePr"`
GraphicFrameLocks *GraphicFrameLocks `xml:"a:graphicFrameLocks,omitempty"`
}
CNvGraphicFramePr 非可视图形框架属性
type CNvPicPr ¶ added in v1.3.9
type CNvPicPr struct {
XMLName xml.Name `xml:"pic:cNvPicPr"`
PicLocks *PicLocks `xml:"a:picLocks,omitempty"`
}
CNvPicPr 图片特定非可视属性
type CNvPr ¶ added in v1.3.3
type CNvPr struct {
XMLName xml.Name `xml:"pic:cNvPr"`
ID string `xml:"id,attr"`
Name string `xml:"name,attr"`
Descr string `xml:"descr,attr,omitempty"`
Title string `xml:"title,attr,omitempty"`
}
CNvPr 通用非可视属性
type CantSplit ¶
type CantSplit struct {
XMLName xml.Name `xml:"w:cantSplit"`
Val string `xml:"w:val,attr,omitempty"`
}
CantSplit 禁止分割
type CellAlignment ¶
type CellAlignment string
CellAlignment 单元格对齐方式
const ( // CellAlignLeft 左对齐 CellAlignLeft CellAlignment = "left" // CellAlignCenter 居中对齐 CellAlignCenter CellAlignment = "center" // CellAlignRight 右对齐 CellAlignRight CellAlignment = "right" // CellAlignJustify 两端对齐 CellAlignJustify CellAlignment = "both" )
type CellBorderConfig ¶
type CellBorderConfig struct {
Top *BorderConfig // 上边框
Left *BorderConfig // 左边框
Bottom *BorderConfig // 下边框
Right *BorderConfig // 右边框
DiagDown *BorderConfig // 左上到右下对角线
DiagUp *BorderConfig // 右上到左下对角线
}
CellBorderConfig 单元格边框配置
type CellFormat ¶
type CellFormat struct {
TextFormat *TextFormat // 文字格式
HorizontalAlign CellAlignment // 水平对齐
VerticalAlign CellVerticalAlignment // 垂直对齐
TextDirection CellTextDirection // 文字方向
BackgroundColor string // 背景颜色
BorderStyle string // 边框样式
Padding int // 内边距(磅)
}
CellFormat 单元格格式配置
type CellImageConfig ¶ added in v1.5.0
type CellImageConfig struct {
// 图片来源 - 文件路径
FilePath string
// 图片来源 - 二进制数据
Data []byte
// 图片格式(当使用Data时需要指定)
Format ImageFormat
// 图片宽度(毫米),0表示自动
Width float64
// 图片高度(毫米),0表示自动
Height float64
// 是否保持宽高比
KeepAspectRatio bool
// 图片替代文字
AltText string
// 图片标题
Title string
}
CellImageConfig 单元格图片配置
type CellInfo ¶
type CellInfo struct {
Row int // 行索引
Col int // 列索引
Cell *TableCell // 单元格引用
Text string // 单元格文本
IsLast bool // 是否为最后一个单元格
}
CellInfo 单元格信息
type CellIterator ¶
type CellIterator struct {
// contains filtered or unexported fields
}
CellIterator 单元格迭代器
func (*CellIterator) Current ¶
func (iter *CellIterator) Current() (int, int)
Current 获取当前位置信息(不移动迭代器)
func (*CellIterator) Progress ¶
func (iter *CellIterator) Progress() float64
Progress 获取迭代进度(0.0-1.0)
type CellListConfig ¶ added in v1.5.0
type CellListConfig struct {
Type ListType // 列表类型
BulletSymbol BulletType // 项目符号(仅用于无序列表)
Items []string // 列表项内容
}
CellListConfig 单元格列表配置
type CellTextDirection ¶
type CellTextDirection string
CellTextDirection 单元格文字方向
const ( // TextDirectionLR 从左到右(默认) TextDirectionLR CellTextDirection = "lrTb" // TextDirectionTB 从上到下 TextDirectionTB CellTextDirection = "tbRl" // TextDirectionBT 从下到上 TextDirectionBT CellTextDirection = "btLr" // TextDirectionRL 从右到左 TextDirectionRL CellTextDirection = "rlTb" // TextDirectionTBV 从上到下,垂直显示 TextDirectionTBV CellTextDirection = "tbLrV" // TextDirectionBTV 从下到上,垂直显示 TextDirectionBTV CellTextDirection = "btLrV" )
type CellVerticalAlignment ¶
type CellVerticalAlignment string
CellVerticalAlignment 单元格垂直对齐方式
const ( // CellVAlignTop 顶部对齐 CellVAlignTop CellVerticalAlignment = "top" // CellVAlignCenter 居中对齐 CellVAlignCenter CellVerticalAlignment = "center" // CellVAlignBottom 底部对齐 CellVAlignBottom CellVerticalAlignment = "bottom" )
type CharacterSpacingControl ¶ added in v1.3.3
type CharacterSpacingControl struct {
XMLName xml.Name `xml:"w:characterSpacingControl"`
Val string `xml:"w:val,attr"`
}
CharacterSpacingControl 字符间距控制
type Columns ¶
type Columns struct {
XMLName xml.Name `xml:"w:cols"`
Space string `xml:"w:space,attr,omitempty"` // 栏间距
Num string `xml:"w:num,attr,omitempty"` // 栏数
}
Columns 分栏设置
type ContentTypes ¶
type ContentTypes struct {
XMLName xml.Name `xml:"Types"`
Xmlns string `xml:"xmlns,attr"`
Defaults []Default `xml:"Default"`
Overrides []Override `xml:"Override"`
}
ContentTypes 内容类型
type CoreProperties ¶
type CoreProperties struct {
XMLName xml.Name `xml:"cp:coreProperties"`
XmlnsCP string `xml:"xmlns:cp,attr"`
XmlnsDC string `xml:"xmlns:dc,attr"`
XmlnsDCTerms string `xml:"xmlns:dcterms,attr"`
XmlnsDCMIType string `xml:"xmlns:dcmitype,attr"`
XmlnsXSI string `xml:"xmlns:xsi,attr"`
Title *DCText `xml:"dc:title,omitempty"`
Subject *DCText `xml:"dc:subject,omitempty"`
Creator *DCText `xml:"dc:creator,omitempty"`
Keywords *CPText `xml:"cp:keywords,omitempty"`
Description *DCText `xml:"dc:description,omitempty"`
Language *DCText `xml:"dc:language,omitempty"`
Category *CPText `xml:"cp:category,omitempty"`
Version *CPText `xml:"cp:version,omitempty"`
Revision *CPText `xml:"cp:revision,omitempty"`
Created *DCDate `xml:"dcterms:created,omitempty"`
Modified *DCDate `xml:"dcterms:modified,omitempty"`
LastPrinted *DCDate `xml:"cp:lastPrinted,omitempty"`
}
CoreProperties 核心属性XML结构
type Default ¶
type Default struct {
Extension string `xml:"Extension,attr"`
ContentType string `xml:"ContentType,attr"`
}
Default 默认内容类型
type DefaultTabStop ¶ added in v1.3.3
type DefaultTabStop struct {
XMLName xml.Name `xml:"w:defaultTabStop"`
Val string `xml:"w:val,attr"`
}
DefaultTabStop 默认制表位设置
type DocGrid ¶ added in v1.3.8
type DocGrid struct {
XMLName xml.Name `xml:"w:docGrid"`
Type string `xml:"w:type,attr,omitempty"` // 网格类型
LinePitch string `xml:"w:linePitch,attr,omitempty"` // 行网格间距
CharSpace string `xml:"w:charSpace,attr,omitempty"` // 字符间距
}
DocGrid 文档网格设置
type DocGridType ¶ added in v1.3.8
type DocGridType string
DocGridType 文档网格类型
const ( // DocGridDefault 默认网格类型 DocGridDefault DocGridType = "default" // DocGridLines 仅影响行间距 DocGridLines DocGridType = "lines" // DocGridSnapToChars 文字对齐到网格 DocGridSnapToChars DocGridType = "snapToChars" // DocGridSnapToLines 文字行对齐到网格 DocGridSnapToLines DocGridType = "snapToLines" )
type DocPartGallery ¶
type DocPartGallery struct {
XMLName xml.Name `xml:"w:docPartGallery"`
Val string `xml:"w:val,attr"`
}
DocPartGallery 文档部件库
type DocPartObj ¶
type DocPartObj struct {
XMLName xml.Name `xml:"w:docPartObj"`
DocPartGallery *DocPartGallery `xml:"w:docPartGallery,omitempty"`
DocPartUnique *DocPartUnique `xml:"w:docPartUnique,omitempty"`
}
DocPartObj 文档部件对象
type DocPartUnique ¶
DocPartUnique 文档部件唯一标识
type Document ¶
type Document struct {
// 文档的主要内容
Body *Body
// contains filtered or unexported fields
}
Document 表示一个Word文档
func Open ¶
Open 打开一个现有的Word文档。
参数 filename 是要打开的 .docx 文件路径。 该函数会解析整个文档结构,包括文本内容、格式和属性。
如果文件不存在、格式错误或解析失败,会返回相应的错误。
示例:
doc, err := document.Open("existing.docx")
if err != nil {
log.Fatal(err)
}
// 打印所有段落内容
for i, para := range doc.Body.Paragraphs {
fmt.Printf("段落 %d: ", i+1)
for _, run := range para.Runs {
fmt.Print(run.Text.Content)
}
fmt.Println()
}
func OpenFromMemory ¶ added in v1.4.0
func OpenFromMemory(readCloser io.ReadCloser) (*Document, error)
func (*Document) AddBulletList ¶
func (d *Document) AddBulletList(text string, level int, bulletType BulletType) *Paragraph
AddBulletList 添加无序列表项
func (*Document) AddCellImage ¶ added in v1.5.0
func (d *Document) AddCellImage(table *Table, row, col int, config *CellImageConfig) (*ImageInfo, error)
AddCellImage 向表格单元格添加图片
此方法用于向表格单元格中添加图片,支持从文件路径或二进制数据添加。 由于图片需要在文档级别管理资源关系,所以此方法必须在Document上调用。
参数:
- table: 目标表格
- row: 行索引(从0开始)
- col: 列索引(从0开始)
- config: 单元格图片配置
返回:
- *ImageInfo: 添加的图片信息
- error: 如果添加失败则返回错误
示例:
table, _ := doc.AddTable(&document.TableConfig{Rows: 2, Cols: 2, Width: 6000})
imageConfig := &document.CellImageConfig{
FilePath: "logo.png",
Width: 50, // 50mm宽度
KeepAspectRatio: true,
}
imageInfo, err := doc.AddCellImage(table, 0, 0, imageConfig)
func (*Document) AddCellImageFromData ¶ added in v1.5.0
func (d *Document) AddCellImageFromData(table *Table, row, col int, data []byte, widthMM float64) (*ImageInfo, error)
AddCellImageFromData 从二进制数据向表格单元格添加图片(便捷方法)
此方法是AddCellImage的便捷封装,直接从二进制数据添加图片。
参数:
- table: 目标表格
- row: 行索引(从0开始)
- col: 列索引(从0开始)
- data: 图片二进制数据
- widthMM: 图片宽度(毫米),0表示使用原始尺寸
返回:
- *ImageInfo: 添加的图片信息
- error: 如果添加失败则返回错误
func (*Document) AddCellImageFromFile ¶ added in v1.5.0
func (d *Document) AddCellImageFromFile(table *Table, row, col int, filePath string, widthMM float64) (*ImageInfo, error)
AddCellImageFromFile 从文件向表格单元格添加图片(便捷方法)
此方法是AddCellImage的便捷封装,直接从文件路径添加图片。
参数:
- table: 目标表格
- row: 行索引(从0开始)
- col: 列索引(从0开始)
- filePath: 图片文件路径
- widthMM: 图片宽度(毫米),0表示使用原始尺寸
返回:
- *ImageInfo: 添加的图片信息
- error: 如果添加失败则返回错误
func (*Document) AddEndnote ¶
AddEndnote 添加尾注
func (*Document) AddFooter ¶
func (d *Document) AddFooter(footerType HeaderFooterType, text string) error
AddFooter 添加页脚
func (*Document) AddFooterWithPageNumber ¶
func (d *Document) AddFooterWithPageNumber(footerType HeaderFooterType, text string, showPageNum bool) error
AddFooterWithPageNumber 添加带页码的页脚
func (*Document) AddFootnote ¶
AddFootnote 添加脚注
func (*Document) AddFootnoteToRun ¶
AddFootnoteToRun 在现有Run中添加脚注引用
func (*Document) AddFormattedFooter ¶ added in v1.5.0
func (d *Document) AddFormattedFooter(footerType HeaderFooterType, config *HeaderFooterConfig) error
AddFormattedFooter 添加格式化页脚
该方法允许添加带有自定义文本格式和对齐方式的页脚。
参数:
- footerType: 页脚类型 (HeaderFooterTypeDefault, HeaderFooterTypeFirst, HeaderFooterTypeEven)
- config: 页脚配置,包含文本内容、格式和对齐方式
示例:
doc.AddFormattedFooter(document.HeaderFooterTypeDefault, &document.HeaderFooterConfig{
Text: "第 1 页",
Format: &document.TextFormat{
FontSize: 9,
FontColor: "666666",
FontFamily: "宋体",
},
Alignment: document.AlignCenter,
})
func (*Document) AddFormattedHeader ¶ added in v1.5.0
func (d *Document) AddFormattedHeader(headerType HeaderFooterType, config *HeaderFooterConfig) error
AddFormattedHeader 添加格式化页眉
该方法允许添加带有自定义文本格式和对齐方式的页眉。
参数:
- headerType: 页眉类型 (HeaderFooterTypeDefault, HeaderFooterTypeFirst, HeaderFooterTypeEven)
- config: 页眉配置,包含文本内容、格式和对齐方式
示例:
doc.AddFormattedHeader(document.HeaderFooterTypeDefault, &document.HeaderFooterConfig{
Text: "公司报告",
Format: &document.TextFormat{
FontSize: 10,
FontColor: "8e8e8e",
FontFamily: "Arial",
},
Alignment: document.AlignCenter,
})
func (*Document) AddFormattedParagraph ¶
func (d *Document) AddFormattedParagraph(text string, format *TextFormat) *Paragraph
AddFormattedParagraph 向文档添加一个格式化段落。
参数 text 是段落的文本内容。 参数 format 指定文本格式,如果为 nil 则使用默认格式。
返回新创建段落的指针,可用于进一步设置段落属性。
示例:
doc := document.New()
// 创建格式配置
titleFormat := &document.TextFormat{
Bold: true,
FontSize: 18,
FontColor: "FF0000", // 红色
FontName: "微软雅黑",
}
// 添加格式化标题
title := doc.AddFormattedParagraph("文档标题", titleFormat)
title.SetAlignment(document.AlignCenter)
func (*Document) AddHeader ¶
func (d *Document) AddHeader(headerType HeaderFooterType, text string) error
AddHeader 添加页眉
func (*Document) AddHeaderWithPageNumber ¶
func (d *Document) AddHeaderWithPageNumber(headerType HeaderFooterType, text string, showPageNum bool) error
AddHeaderWithPageNumber 添加带页码的页眉
func (*Document) AddHeadingParagraph ¶
AddHeadingParagraph 向文档添加一个标题段落。
参数 text 是标题的文本内容。 参数 level 是标题级别(1-9),对应 Heading1 到 Heading9。
返回新创建段落的指针,可用于进一步设置段落属性。 此方法会自动设置正确的样式引用,确保标题能被 Word 导航窗格识别。
示例:
doc := document.New()
// 添加一级标题
h1 := doc.AddHeadingParagraph("第一章:概述", 1)
// 添加二级标题
h2 := doc.AddHeadingParagraph("1.1 背景", 2)
// 添加三级标题
h3 := doc.AddHeadingParagraph("1.1.1 研究目标", 3)
func (*Document) AddHeadingParagraphWithBookmark ¶
func (d *Document) AddHeadingParagraphWithBookmark(text string, level int, bookmarkName string) *Paragraph
AddHeadingParagraphWithBookmark 向文档添加一个带书签的标题段落。
参数 text 是标题的文本内容。 参数 level 是标题级别(1-9),对应 Heading1 到 Heading9。 参数 bookmarkName 是书签名称,如果为空字符串则不添加书签。
返回新创建段落的指针,可用于进一步设置段落属性。 此方法会自动设置正确的样式引用,确保标题能被 Word 导航窗格识别, 并在需要时添加书签以支持目录导航和超链接。
示例:
doc := document.New()
// 添加带书签的一级标题
h1 := doc.AddHeadingParagraphWithBookmark("第一章:概述", 1, "chapter1")
// 添加不带书签的二级标题
h2 := doc.AddHeadingParagraphWithBookmark("1.1 背景", 2, "")
// 添加自动生成书签名的三级标题
h3 := doc.AddHeadingParagraphWithBookmark("1.1.1 研究目标", 3, "auto_bookmark")
func (*Document) AddHeadingWithBookmark ¶
AddHeadingWithBookmark 添加带书签的标题
func (*Document) AddImageFromData ¶ added in v1.3.3
func (d *Document) AddImageFromData(imageData []byte, fileName string, format ImageFormat, width, height int, config *ImageConfig) (*ImageInfo, error)
AddImageFromData 从数据添加图片到文档
func (*Document) AddImageFromDataWithoutElement ¶ added in v1.3.9
func (d *Document) AddImageFromDataWithoutElement(imageData []byte, fileName string, format ImageFormat, width, height int, config *ImageConfig) (*ImageInfo, error)
AddImageFromDataWithoutElement 从数据添加图片到文档但不创建段落元素 此方法供模板引擎等需要自行管理图片段落的场景使用
func (*Document) AddImageFromFile ¶ added in v1.3.3
func (d *Document) AddImageFromFile(filePath string, config *ImageConfig) (*ImageInfo, error)
AddImageFromFile 从文件添加图片到文档
func (*Document) AddListItem ¶
func (d *Document) AddListItem(text string, config *ListConfig) *Paragraph
AddListItem 添加列表项
func (*Document) AddMathFormula ¶ added in v1.5.0
func (d *Document) AddMathFormula(latex string, isBlock bool) *MathParagraph
AddMathFormula 向文档添加数学公式 latex: LaTeX格式的数学公式 isBlock: 是否为块级公式(true为块级,false为行内)
func (*Document) AddNumberedList ¶
AddNumberedList 添加有序列表项
func (*Document) AddPageBreak ¶ added in v1.5.0
func (d *Document) AddPageBreak()
AddPageBreak 向文档添加一个分页符。
分页符会强制在当前位置开始一个新页面。 此方法会创建一个包含分页符的段落。
示例:
doc := document.New()
doc.AddParagraph("第一页内容")
doc.AddPageBreak()
doc.AddParagraph("第二页内容")
func (*Document) AddParagraph ¶
AddParagraph 向文档添加一个普通段落。
参数 text 是段落的文本内容。段落会使用默认格式, 可以后续通过返回的 Paragraph 指针设置格式和属性。
返回新创建段落的指针,可用于进一步格式化。
示例:
doc := document.New()
// 添加普通段落
para := doc.AddParagraph("这是一个段落")
// 设置段落属性
para.SetAlignment(document.AlignCenter)
para.SetSpacing(&document.SpacingConfig{
LineSpacing: 1.5,
BeforePara: 12,
})
func (*Document) AddTable ¶
func (d *Document) AddTable(config *TableConfig) (*Table, error)
AddTable 将表格添加到文档中 参数:
- config: 表格配置
返回:
- *Table: 添加的表格对象
- error: 如果配置无效则返回错误
func (*Document) AutoGenerateTOC ¶
AutoGenerateTOC 自动生成目录,检测现有文档中的标题
func (*Document) ClearDocGrid ¶ added in v1.3.8
ClearDocGrid 清除文档网格设置
func (*Document) CreateMultiLevelList ¶
CreateMultiLevelList 创建多级列表
func (*Document) CreateTOCSDT ¶
CreateTOCSDT 创建目录SDT结构
func (*Document) CreateTable ¶
func (d *Document) CreateTable(config *TableConfig) (*Table, error)
CreateTable 创建一个新表格 参数:
- config: 表格配置
返回:
- *Table: 创建的表格对象
- error: 如果配置无效则返回错误
func (*Document) GenerateTOC ¶
GenerateTOC 生成目录
func (*Document) GetDocumentProperties ¶
func (d *Document) GetDocumentProperties() (*DocumentProperties, error)
GetDocumentProperties 获取文档属性
func (*Document) GetFootnoteCount ¶
GetFootnoteCount 获取脚注数量
func (*Document) GetHeadingCount ¶
GetHeadingCount 获取文档中标题的数量,用于调试
func (*Document) GetPageSettings ¶
func (d *Document) GetPageSettings() *PageSettings
GetPageSettings 获取当前文档的页面设置
func (*Document) GetParts ¶ added in v1.3.3
GetParts 获取文档部件映射
返回包含文档所有部件的映射,主要用于测试和调试。 键是部件名称,值是部件内容的字节数组。
示例:
parts := doc.GetParts() settingsXML := parts["word/settings.xml"]
func (*Document) GetStyleManager ¶
func (d *Document) GetStyleManager() *style.StyleManager
GetStyleManager 获取文档的样式管理器。
返回文档的样式管理器,可用于访问和管理样式。
示例:
doc := document.New()
styleManager := doc.GetStyleManager()
headingStyle := styleManager.GetStyle("Heading1")
func (*Document) ListHeadings ¶
ListHeadings 列出文档中所有的标题,用于调试
func (*Document) RemoveElementAt ¶ added in v1.5.0
RemoveElementAt 根据元素索引删除元素(包括段落、表格等)。
参数 index 是要删除的元素在文档主体中的索引(从0开始)。 如果索引超出范围,此方法会返回错误。
返回值表示是否成功删除元素。
示例:
doc := document.New()
doc.AddParagraph("段落")
doc.AddTable(&document.TableConfig{Rows: 2, Cols: 2})
doc.RemoveElementAt(0) // 删除第一个元素(段落)
func (*Document) RemoveEndnote ¶
RemoveEndnote 删除指定尾注
func (*Document) RemoveFootnote ¶
RemoveFootnote 删除指定脚注
func (*Document) RemoveParagraph ¶ added in v1.5.0
RemoveParagraph 从文档中删除指定的段落。
参数 paragraph 是要删除的段落对象。 如果段落不存在于文档中,此方法不会产生任何效果。
返回值表示是否成功删除段落。
示例:
doc := document.New()
para := doc.AddParagraph("要删除的段落")
doc.RemoveParagraph(para)
func (*Document) RemoveParagraphAt ¶ added in v1.5.0
RemoveParagraphAt 根据索引删除段落。
参数 index 是要删除的段落在所有段落中的索引(从0开始)。 如果索引超出范围,此方法会返回错误。
返回值表示是否成功删除段落。
示例:
doc := document.New()
doc.AddParagraph("第一段")
doc.AddParagraph("第二段")
doc.RemoveParagraphAt(0) // 删除第一段
func (*Document) ResizeImage ¶ added in v1.3.3
ResizeImage 调整图片大小
func (*Document) RestartNumbering ¶
RestartNumbering 重新开始编号
func (*Document) Save ¶
Save 将文档保存到指定的文件路径。
参数 filename 是保存文件的路径,包含文件名和扩展名。 如果目录不存在,会自动创建所需的目录结构。
保存过程包括序列化所有文档内容、压缩为ZIP格式, 并写入到文件系统。
示例:
doc := document.New()
doc.AddParagraph("示例内容")
// 保存到当前目录
err := doc.Save("example.docx")
// 保存到子目录(会自动创建目录)
err = doc.Save("output/documents/example.docx")
if err != nil {
log.Fatal(err)
}
func (*Document) SetCategory ¶
SetCategory 设置文档类别
func (*Document) SetCustomPageSize ¶
SetCustomPageSize 设置自定义页面大小(毫米)
func (*Document) SetDescription ¶
SetDescription 设置文档描述
func (*Document) SetDifferentFirstPage ¶
SetDifferentFirstPage 设置首页不同
func (*Document) SetDocGrid ¶ added in v1.3.8
func (d *Document) SetDocGrid(gridType DocGridType, linePitch int, charSpace int) error
SetDocGrid 设置文档网格
func (*Document) SetDocumentProperties ¶
func (d *Document) SetDocumentProperties(properties *DocumentProperties) error
SetDocumentProperties 设置文档属性
func (*Document) SetFootnoteConfig ¶
func (d *Document) SetFootnoteConfig(config *FootnoteConfig) error
SetFootnoteConfig 设置脚注配置
func (*Document) SetGutterWidth ¶
SetGutterWidth 设置装订线宽度(毫米)
func (*Document) SetHeaderFooterDistance ¶
SetHeaderFooterDistance 设置页眉页脚距离(毫米)
func (*Document) SetImageAlignment ¶ added in v1.3.3
func (d *Document) SetImageAlignment(imageInfo *ImageInfo, alignment AlignmentType) error
SetImageAlignment 设置图片对齐方式
此方法用于设置嵌入式图片(ImagePositionInline)的对齐方式。 对于浮动图片,请使用SetImagePosition方法。
参数 alignment 指定对齐类型,支持以下值:
- AlignLeft: 左对齐
- AlignCenter: 居中对齐
- AlignRight: 右对齐
- AlignJustify: 两端对齐
示例:
imageInfo, err := doc.AddImageFromFile("image.png", nil)
if err != nil {
return err
}
err = doc.SetImageAlignment(imageInfo, document.AlignCenter)
func (*Document) SetImageAltText ¶ added in v1.3.3
SetImageAltText 设置图片替代文字
func (*Document) SetImagePosition ¶ added in v1.3.3
func (d *Document) SetImagePosition(imageInfo *ImageInfo, position ImagePosition, offsetX, offsetY float64) error
SetImagePosition 设置图片位置
func (*Document) SetImageTitle ¶ added in v1.3.3
SetImageTitle 设置图片标题
func (*Document) SetImageWrapText ¶ added in v1.3.3
func (d *Document) SetImageWrapText(imageInfo *ImageInfo, wrapText ImageWrapText) error
SetImageWrapText 设置图片文字环绕
func (*Document) SetKeywords ¶
SetKeywords 设置文档关键字
func (*Document) SetPageMargins ¶
SetPageMargins 设置页面边距(毫米)
func (*Document) SetPageOrientation ¶
func (d *Document) SetPageOrientation(orientation PageOrientation) error
SetPageOrientation 设置页面方向
func (*Document) SetPageSettings ¶
func (d *Document) SetPageSettings(settings *PageSettings) error
SetPageSettings 设置文档的页面属性
func (*Document) SetPageSize ¶
SetPageSize 设置页面大小
func (*Document) SetTOCStyle ¶
func (d *Document) SetTOCStyle(level int, style *TextFormat) error
SetTOCStyle 设置目录样式
func (*Document) UpdateStatistics ¶
UpdateStatistics 更新文档统计信息
type DocumentError ¶
DocumentError 文档操作错误
func NewDocumentError ¶
func NewDocumentError(operation string, cause error, context string) *DocumentError
NewDocumentError 创建新的文档错误
func (*DocumentError) Unwrap ¶
func (e *DocumentError) Unwrap() error
Unwrap 解包错误,支持errors.Is和errors.As
type DocumentProperties ¶
type DocumentProperties struct {
// 核心属性
Title string // 文档标题
Subject string // 文档主题
Creator string // 创建者
Keywords string // 关键字
Description string // 描述
Language string // 语言
Category string // 类别
Version string // 版本
Revision string // 修订版本
// 时间属性
Created time.Time // 创建时间
LastModified time.Time // 最后修改时间
LastPrinted time.Time // 最后打印时间
// 统计属性
Pages int // 页数
Words int // 字数
Characters int // 字符数
Paragraphs int // 段落数
Lines int // 行数
}
DocumentProperties 文档属性结构
type DrawingDocPr ¶ added in v1.3.3
type DrawingDocPr struct {
XMLName xml.Name `xml:"wp:docPr"`
ID string `xml:"id,attr"`
Name string `xml:"name,attr"`
Descr string `xml:"descr,attr,omitempty"`
Title string `xml:"title,attr,omitempty"`
}
DrawingDocPr 文档属性
type DrawingElement ¶ added in v1.3.3
type DrawingElement struct {
XMLName xml.Name `xml:"w:drawing"`
Inline *InlineDrawing `xml:"wp:inline,omitempty"`
Anchor *AnchorDrawing `xml:"wp:anchor,omitempty"`
}
DrawingElement 绘图元素(包含图片)
type DrawingExtent ¶ added in v1.3.3
type DrawingExtent struct {
XMLName xml.Name `xml:"wp:extent"`
Cx string `xml:"cx,attr"`
Cy string `xml:"cy,attr"`
}
DrawingExtent 尺寸
type DrawingGraphic ¶ added in v1.3.3
type DrawingGraphic struct {
XMLName xml.Name `xml:"a:graphic"`
Xmlns string `xml:"xmlns:a,attr"`
GraphicData *GraphicData `xml:"a:graphicData"`
}
DrawingGraphic 图形
type EffectExtent ¶ added in v1.3.3
type EffectExtent struct {
XMLName xml.Name `xml:"wp:effectExtent"`
L string `xml:"l,attr,omitempty"`
T string `xml:"t,attr,omitempty"`
R string `xml:"r,attr,omitempty"`
B string `xml:"b,attr,omitempty"`
}
EffectExtent 效果范围
type Endnote ¶
type Endnote struct {
XMLName xml.Name `xml:"w:endnote"`
Type string `xml:"w:type,attr,omitempty"`
ID string `xml:"w:id,attr"`
Paragraphs []*Paragraph `xml:"w:p"`
}
Endnote 尾注结构
type EndnoteNumFmt ¶ added in v1.3.3
EndnoteNumFmt 尾注编号格式
type EndnoteNumRestart ¶ added in v1.3.3
type EndnoteNumRestart struct {
XMLName xml.Name `xml:"w:numRestart"`
Val string `xml:"w:val,attr"`
}
EndnoteNumRestart 尾注重新开始规则
type EndnoteNumStart ¶ added in v1.3.3
EndnoteNumStart 尾注起始编号
type EndnotePos ¶ added in v1.3.3
EndnotePos 尾注位置
type EndnotePr ¶ added in v1.3.3
type EndnotePr struct {
XMLName xml.Name `xml:"w:endnotePr"`
NumFmt *EndnoteNumFmt `xml:"w:numFmt,omitempty"`
NumStart *EndnoteNumStart `xml:"w:numStart,omitempty"`
NumRestart *EndnoteNumRestart `xml:"w:numRestart,omitempty"`
Pos *EndnotePos `xml:"w:pos,omitempty"`
}
EndnotePr 尾注属性设置
type EndnoteProperties ¶ added in v1.3.3
type EndnoteProperties struct {
NumberFormat string `xml:"w:numFmt,attr,omitempty"`
StartNumber int `xml:"w:numStart,attr,omitempty"`
RestartRule string `xml:"w:numRestart,attr,omitempty"`
Position string `xml:"w:pos,attr,omitempty"`
}
EndnoteProperties 尾注属性
type EndnoteReference ¶
type EndnoteReference struct {
XMLName xml.Name `xml:"w:endnoteReference"`
ID string `xml:"w:id,attr"`
}
EndnoteReference 尾注引用
type Endnotes ¶
type Endnotes struct {
XMLName xml.Name `xml:"w:endnotes"`
Xmlns string `xml:"xmlns:w,attr"`
Endnotes []*Endnote `xml:"w:endnote"`
}
Endnotes 尾注集合
type Ext ¶ added in v1.3.3
type Ext struct {
XMLName xml.Name `xml:"a:ext"`
Cx string `xml:"cx,attr"`
Cy string `xml:"cy,attr"`
}
Ext 范围
type FieldChar ¶
type FieldChar struct {
XMLName xml.Name `xml:"w:fldChar"`
FieldCharType string `xml:"w:fldCharType,attr"`
}
FieldChar 域字符
type FontFamily ¶
type FontFamily struct {
XMLName xml.Name `xml:"w:rFonts"`
ASCII string `xml:"w:ascii,attr,omitempty"`
HAnsi string `xml:"w:hAnsi,attr,omitempty"`
EastAsia string `xml:"w:eastAsia,attr,omitempty"`
CS string `xml:"w:cs,attr,omitempty"`
Hint string `xml:"w:hint,attr,omitempty"`
}
FontFamily 字体族
type FontSizeCs ¶ added in v1.3.6
FontSizeCs 复杂脚本字体大小
type Footnote ¶
type Footnote struct {
XMLName xml.Name `xml:"w:footnote"`
Type string `xml:"w:type,attr,omitempty"`
ID string `xml:"w:id,attr"`
Paragraphs []*Paragraph `xml:"w:p"`
}
Footnote 脚注结构
type FootnoteConfig ¶
type FootnoteConfig struct {
NumberFormat FootnoteNumberFormat // 编号格式
StartNumber int // 起始编号
RestartEach FootnoteRestart // 重新开始规则
Position FootnotePosition // 位置
}
FootnoteConfig 脚注配置
func DefaultFootnoteConfig ¶
func DefaultFootnoteConfig() *FootnoteConfig
DefaultFootnoteConfig 返回默认脚注配置
type FootnoteManager ¶
type FootnoteManager struct {
// contains filtered or unexported fields
}
FootnoteManager 脚注管理器
type FootnoteNumFmt ¶ added in v1.3.3
FootnoteNumFmt 脚注编号格式
type FootnoteNumRestart ¶ added in v1.3.3
type FootnoteNumRestart struct {
XMLName xml.Name `xml:"w:numRestart"`
Val string `xml:"w:val,attr"`
}
FootnoteNumRestart 脚注重新开始规则
type FootnoteNumStart ¶ added in v1.3.3
FootnoteNumStart 脚注起始编号
type FootnoteNumberFormat ¶
type FootnoteNumberFormat string
FootnoteNumberFormat 脚注编号格式
const ( // FootnoteFormatDecimal 十进制数字 FootnoteFormatDecimal FootnoteNumberFormat = "decimal" // FootnoteFormatLowerRoman 小写罗马数字 FootnoteFormatLowerRoman FootnoteNumberFormat = "lowerRoman" // FootnoteFormatUpperRoman 大写罗马数字 FootnoteFormatUpperRoman FootnoteNumberFormat = "upperRoman" // FootnoteFormatLowerLetter 小写字母 FootnoteFormatLowerLetter FootnoteNumberFormat = "lowerLetter" // FootnoteFormatUpperLetter 大写字母 FootnoteFormatUpperLetter FootnoteNumberFormat = "upperLetter" // FootnoteFormatSymbol 符号 FootnoteFormatSymbol FootnoteNumberFormat = "symbol" )
type FootnotePos ¶ added in v1.3.3
FootnotePos 脚注位置
type FootnotePosition ¶
type FootnotePosition string
FootnotePosition 脚注位置
const ( // FootnotePositionPageBottom 页面底部 FootnotePositionPageBottom FootnotePosition = "pageBottom" // FootnotePositionBeneathText 文本下方 FootnotePositionBeneathText FootnotePosition = "beneathText" // FootnotePositionSectionEnd 节末尾 FootnotePositionSectionEnd FootnotePosition = "sectEnd" // FootnotePositionDocumentEnd 文档末尾 FootnotePositionDocumentEnd FootnotePosition = "docEnd" )
type FootnotePr ¶ added in v1.3.3
type FootnotePr struct {
XMLName xml.Name `xml:"w:footnotePr"`
NumFmt *FootnoteNumFmt `xml:"w:numFmt,omitempty"`
NumStart *FootnoteNumStart `xml:"w:numStart,omitempty"`
NumRestart *FootnoteNumRestart `xml:"w:numRestart,omitempty"`
Pos *FootnotePos `xml:"w:pos,omitempty"`
}
FootnotePr 脚注属性设置
type FootnoteProperties ¶ added in v1.3.3
type FootnoteProperties struct {
NumberFormat string `xml:"w:numFmt,attr,omitempty"`
StartNumber int `xml:"w:numStart,attr,omitempty"`
RestartRule string `xml:"w:numRestart,attr,omitempty"`
Position string `xml:"w:pos,attr,omitempty"`
}
FootnoteProperties 脚注属性
type FootnoteReference ¶
type FootnoteReference struct {
XMLName xml.Name `xml:"w:footnoteReference"`
ID string `xml:"w:id,attr"`
}
FootnoteReference 脚注引用
type FootnoteRestart ¶
type FootnoteRestart string
FootnoteRestart 脚注重新开始规则
const ( // FootnoteRestartContinuous 连续编号 FootnoteRestartContinuous FootnoteRestart = "continuous" // FootnoteRestartEachSection 每节重新开始 FootnoteRestartEachSection FootnoteRestart = "eachSect" // FootnoteRestartEachPage 每页重新开始 FootnoteRestartEachPage FootnoteRestart = "eachPage" )
type FootnoteType ¶
type FootnoteType string
FootnoteType 脚注类型
const ( // FootnoteTypeFootnote 脚注 FootnoteTypeFootnote FootnoteType = "footnote" // FootnoteTypeEndnote 尾注 FootnoteTypeEndnote FootnoteType = "endnote" )
type Footnotes ¶
type Footnotes struct {
XMLName xml.Name `xml:"w:footnotes"`
Xmlns string `xml:"xmlns:w,attr"`
Footnotes []*Footnote `xml:"w:footnote"`
}
Footnotes 脚注集合
type GraphicData ¶ added in v1.3.3
type GraphicData struct {
XMLName xml.Name `xml:"a:graphicData"`
Uri string `xml:"uri,attr"`
Pic *PicElement `xml:"pic:pic"`
}
GraphicData 图形数据
type GraphicFrameLocks ¶ added in v1.3.3
type GraphicFrameLocks struct {
XMLName xml.Name `xml:"a:graphicFrameLocks"`
Xmlns string `xml:"xmlns:a,attr,omitempty"`
NoChangeAspect string `xml:"noChangeAspect,attr,omitempty"`
NoCrop string `xml:"noCrop,attr,omitempty"`
NoMove string `xml:"noMove,attr,omitempty"`
NoResize string `xml:"noResize,attr,omitempty"`
NoRot string `xml:"noRot,attr,omitempty"`
NoSelect string `xml:"noSelect,attr,omitempty"`
}
GraphicFrameLocks 图形框架锁定
type Header ¶
type Header struct {
XMLName xml.Name `xml:"w:hdr"`
XmlnsWPC string `xml:"xmlns:wpc,attr"`
XmlnsMC string `xml:"xmlns:mc,attr"`
XmlnsO string `xml:"xmlns:o,attr"`
XmlnsR string `xml:"xmlns:r,attr"`
XmlnsM string `xml:"xmlns:m,attr"`
XmlnsV string `xml:"xmlns:v,attr"`
XmlnsWP14 string `xml:"xmlns:wp14,attr"`
XmlnsWP string `xml:"xmlns:wp,attr"`
XmlnsW10 string `xml:"xmlns:w10,attr"`
XmlnsW string `xml:"xmlns:w,attr"`
XmlnsW14 string `xml:"xmlns:w14,attr"`
XmlnsW15 string `xml:"xmlns:w15,attr"`
XmlnsWPG string `xml:"xmlns:wpg,attr"`
XmlnsWPI string `xml:"xmlns:wpi,attr"`
XmlnsWNE string `xml:"xmlns:wne,attr"`
XmlnsWPS string `xml:"xmlns:wps,attr"`
XmlnsWPSCD string `xml:"xmlns:wpsCustomData,attr"`
MCIgnorable string `xml:"mc:Ignorable,attr"`
Paragraphs []*Paragraph `xml:"w:p"`
}
Header 页眉结构
type HeaderFooterConfig ¶ added in v1.5.0
type HeaderFooterConfig struct {
}
HeaderFooterConfig 页眉页脚配置
type HeaderFooterType ¶
type HeaderFooterType string
HeaderFooterType 页眉页脚类型
const ( HeaderFooterTypeDefault HeaderFooterType = "default" HeaderFooterTypeFirst HeaderFooterType = "first" HeaderFooterTypeEven HeaderFooterType = "even" )
type HideMark ¶
type HideMark struct {
XMLName xml.Name `xml:"w:hideMark"`
Val string `xml:"w:val,attr,omitempty"`
}
HideMark 隐藏标记
type HorizontalPosition ¶ added in v1.3.3
type HorizontalPosition struct {
XMLName xml.Name `xml:"wp:positionH"`
RelativeFrom string `xml:"relativeFrom,attr"`
Align *PosAlign `xml:"wp:align,omitempty"`
PosOffset *PosOffset `xml:"wp:posOffset,omitempty"`
}
HorizontalPosition 水平位置
type Hyperlink ¶
type Hyperlink struct {
XMLName xml.Name `xml:"w:hyperlink"`
Anchor string `xml:"w:anchor,attr,omitempty"`
Runs []Run `xml:"w:r"`
}
Hyperlink 超链接结构
type HyperlinkField ¶
type HyperlinkField struct {
BeginChar FieldChar
InstrText InstrText
SeparateChar FieldChar
EndChar FieldChar
}
HyperlinkField 超链接域
func CreateHyperlinkField ¶
func CreateHyperlinkField(anchor string) HyperlinkField
CreateHyperlinkField 创建超链接域
type ImageConfig ¶ added in v1.3.3
type ImageConfig struct {
// 图片大小
Size *ImageSize
// 图片位置
Position ImagePosition
// 图片对齐方式(用于嵌入式图片)
Alignment AlignmentType
// 文字环绕
WrapText ImageWrapText
// 图片描述(替代文字)
AltText string
// 图片标题
Title string
// 水平偏移(毫米)
OffsetX float64
// 垂直偏移(毫米)
OffsetY float64
}
ImageConfig 图片配置
type ImageFormat ¶ added in v1.3.3
type ImageFormat string
ImageFormat 图片格式类型
const ( // 支持的图片格式 ImageFormatJPEG ImageFormat = "jpeg" ImageFormatPNG ImageFormat = "png" ImageFormatGIF ImageFormat = "gif" )
type ImageInfo ¶ added in v1.3.3
type ImageInfo struct {
ID string // 图片ID
RelationID string // 关系ID
Format ImageFormat // 图片格式
Width int // 原始宽度(像素)
Height int // 原始高度(像素)
Data []byte // 图片数据
Config *ImageConfig // 图片配置
}
ImageInfo 图片信息
type ImagePosition ¶ added in v1.3.3
type ImagePosition string
ImagePosition 图片位置类型
const ( // 图片位置选项 ImagePositionInline ImagePosition = "inline" // 嵌入式(默认) ImagePositionFloatLeft ImagePosition = "floatLeft" // 左浮动 ImagePositionFloatRight ImagePosition = "floatRight" // 右浮动 )
type ImageSize ¶ added in v1.3.3
type ImageSize struct {
Width float64 // 宽度(毫米)
Height float64 // 高度(毫米)
// 是否保持长宽比(当只设置一个维度时)
KeepAspectRatio bool
}
ImageSize 图片大小配置
type ImageWrapText ¶ added in v1.3.3
type ImageWrapText string
ImageWrapText 文字环绕类型
const ( // 文字环绕选项 ImageWrapNone ImageWrapText = "none" // 无环绕 ImageWrapSquare ImageWrapText = "square" // 四周环绕 ImageWrapTight ImageWrapText = "tight" // 紧密环绕 ImageWrapTopAndBottom ImageWrapText = "topAndBottom" // 上下环绕 )
type Indentation ¶
type Indentation struct {
XMLName xml.Name `xml:"w:ind"`
FirstLine string `xml:"w:firstLine,attr,omitempty"`
Left string `xml:"w:left,attr,omitempty"`
Right string `xml:"w:right,attr,omitempty"`
}
Indentation 缩进设置
type InlineDrawing ¶ added in v1.3.3
type InlineDrawing struct {
XMLName xml.Name `xml:"wp:inline"`
DistT string `xml:"distT,attr,omitempty"`
DistB string `xml:"distB,attr,omitempty"`
DistL string `xml:"distL,attr,omitempty"`
DistR string `xml:"distR,attr,omitempty"`
Extent *DrawingExtent `xml:"wp:extent"`
DocPr *DrawingDocPr `xml:"wp:docPr"`
Graphic *DrawingGraphic `xml:"a:graphic"`
}
InlineDrawing 嵌入式绘图
type InstrText ¶
type InstrText struct {
XMLName xml.Name `xml:"w:instrText"`
Space string `xml:"xml:space,attr,omitempty"`
Content string `xml:",chardata"`
}
InstrText 域指令文本
type Justification ¶
Justification 对齐方式
type KeepLines ¶
type KeepLines struct {
XMLName xml.Name `xml:"w:keepLines"`
Val string `xml:"w:val,attr,omitempty"`
}
KeepLines 段落中的行保持在一起
type KeepNext ¶
type KeepNext struct {
XMLName xml.Name `xml:"w:keepNext"`
Val string `xml:"w:val,attr,omitempty"`
}
KeepNext 与下一段落保持在一起
type Level ¶
type Level struct {
XMLName xml.Name `xml:"w:lvl"`
ILevel string `xml:"w:ilvl,attr"`
Start *Start `xml:"w:start,omitempty"`
NumFmt *NumFmt `xml:"w:numFmt,omitempty"`
LevelText *LevelText `xml:"w:lvlText,omitempty"`
LevelJc *LevelJc `xml:"w:lvlJc,omitempty"`
PPr *LevelPPr `xml:"w:pPr,omitempty"`
RPr *LevelRPr `xml:"w:rPr,omitempty"`
}
Level 编号级别
type LevelIndent ¶
type LevelIndent struct {
XMLName xml.Name `xml:"w:ind"`
Left string `xml:"w:left,attr,omitempty"`
Hanging string `xml:"w:hanging,attr,omitempty"`
}
LevelIndent 级别缩进
type LevelPPr ¶
type LevelPPr struct {
XMLName xml.Name `xml:"w:pPr"`
Ind *LevelIndent `xml:"w:ind,omitempty"`
}
LevelPPr 级别段落属性
type LevelRPr ¶
type LevelRPr struct {
XMLName xml.Name `xml:"w:rPr"`
FontFamily *FontFamily `xml:"w:rFonts,omitempty"`
}
LevelRPr 级别文本属性
type ListConfig ¶
type ListConfig struct {
Type ListType // 列表类型
BulletSymbol BulletType // 项目符号(仅用于无序列表)
StartNumber int // 起始编号(仅用于有序列表)
IndentLevel int // 缩进级别(0-8)
}
ListConfig 列表配置
type ListItem ¶
type ListItem struct {
Text string // 文本内容
Level int // 缩进级别
Type ListType // 列表类型
BulletSymbol BulletType // 项目符号
StartNumber int // 起始编号
}
ListItem 列表项结构
type ListType ¶
type ListType string
ListType 列表类型
const ( // ListTypeBullet 无序列表(项目符号) ListTypeBullet ListType = "bullet" // ListTypeNumber 有序列表(数字编号) ListTypeNumber ListType = "number" // ListTypeDecimal 十进制编号 ListTypeDecimal ListType = "decimal" // ListTypeLowerLetter 小写字母编号 ListTypeLowerLetter ListType = "lowerLetter" // ListTypeUpperLetter 大写字母编号 ListTypeUpperLetter ListType = "upperLetter" // ListTypeLowerRoman 小写罗马数字 ListTypeLowerRoman ListType = "lowerRoman" // ListTypeUpperRoman 大写罗马数字 ListTypeUpperRoman ListType = "upperRoman" )
type MathParagraph ¶ added in v1.5.0
type MathParagraph struct {
XMLName xml.Name `xml:"w:p"`
Properties *ParagraphProperties `xml:"w:pPr,omitempty"`
Math *OfficeMath `xml:"m:oMath,omitempty"`
MathPara *OfficeMathPara `xml:"m:oMathPara,omitempty"`
Runs []Run `xml:"w:r"`
}
MathParagraph 表示包含数学公式的段落 用于在文档中嵌入数学公式
func (*MathParagraph) ElementType ¶ added in v1.5.0
func (mp *MathParagraph) ElementType() string
ElementType 返回数学段落元素类型
func (*MathParagraph) MarshalXML ¶ added in v1.5.0
func (mp *MathParagraph) MarshalXML(e *xml.Encoder, start xml.StartElement) error
MarshalXML 自定义序列化
type NumInstance ¶
type NumInstance struct {
XMLName xml.Name `xml:"w:num"`
NumID string `xml:"w:numId,attr"`
AbstractNumID *AbstractNumReference `xml:"w:abstractNumId"`
}
NumInstance 编号实例
type Numbering ¶
type Numbering struct {
XMLName xml.Name `xml:"w:numbering"`
Xmlns string `xml:"xmlns:w,attr"`
AbstractNums []*AbstractNum `xml:"w:abstractNum"`
NumberingInstances []*NumInstance `xml:"w:num"`
}
Numbering 编号定义
type NumberingManager ¶
type NumberingManager struct {
// contains filtered or unexported fields
}
NumberingManager 编号管理器
type NumberingProperties ¶
type NumberingProperties struct {
XMLName xml.Name `xml:"w:numPr"`
ILevel *ILevel `xml:"w:ilvl,omitempty"`
NumID *NumID `xml:"w:numId,omitempty"`
}
NumberingProperties 段落编号属性
type NvPicPr ¶ added in v1.3.3
type NvPicPr struct {
XMLName xml.Name `xml:"pic:nvPicPr"`
CNvPr *CNvPr `xml:"pic:cNvPr"`
CNvPicPr *CNvPicPr `xml:"pic:cNvPicPr"`
}
NvPicPr 非可视图片属性
type OfficeMath ¶ added in v1.5.0
type OfficeMath struct {
XMLName xml.Name `xml:"m:oMath"`
Xmlns string `xml:"xmlns:m,attr,omitempty"`
RawXML string `xml:",innerxml"` // 存储内部XML内容
}
OfficeMath 表示Office数学公式元素 对应OMML中的 m:oMath 元素
type OfficeMathPara ¶ added in v1.5.0
type OfficeMathPara struct {
XMLName xml.Name `xml:"m:oMathPara"`
Xmlns string `xml:"xmlns:m,attr,omitempty"`
Math *OfficeMath `xml:"m:oMath"`
}
OfficeMathPara 表示Office数学公式段落(用于块级公式) 对应OMML中的 m:oMathPara 元素
type OutlineLevel ¶ added in v1.5.0
OutlineLevel 大纲级别
type Override ¶
type Override struct {
PartName string `xml:"PartName,attr"`
ContentType string `xml:"ContentType,attr"`
}
Override 覆盖内容类型
type PageBreakBefore ¶ added in v1.5.0
type PageBreakBefore struct {
XMLName xml.Name `xml:"w:pageBreakBefore"`
Val string `xml:"w:val,attr,omitempty"`
}
PageBreakBefore 段前分页
type PageMargin ¶
type PageMargin struct {
XMLName xml.Name `xml:"w:pgMar"`
Top string `xml:"w:top,attr"` // 上边距(twips)
Right string `xml:"w:right,attr"` // 右边距(twips)
Bottom string `xml:"w:bottom,attr"` // 下边距(twips)
Left string `xml:"w:left,attr"` // 左边距(twips)
Header string `xml:"w:header,attr"` // 页眉距离(twips)
Gutter string `xml:"w:gutter,attr"` // 装订线(twips)
}
PageMargin 页面边距
type PageNumType ¶
type PageNumType struct {
XMLName xml.Name `xml:"w:pgNumType"`
Fmt string `xml:"w:fmt,attr,omitempty"`
}
PageNumType 页码类型
type PageNumber ¶
type PageNumber struct {
XMLName xml.Name `xml:"w:fldSimple"`
Instr string `xml:"w:instr,attr"`
Text *Text `xml:"w:t,omitempty"`
}
PageNumber 页码字段
type PageOrientation ¶
type PageOrientation string
PageOrientation 页面方向类型
const ( // OrientationPortrait 纵向 OrientationPortrait PageOrientation = "portrait" // OrientationLandscape 横向 OrientationLandscape PageOrientation = "landscape" )
type PageRefField ¶
type PageRefField struct {
BeginChar FieldChar
InstrText InstrText
SeparateChar FieldChar
EndChar FieldChar
}
PageRefField 页码引用域
func CreatePageRefField ¶
func CreatePageRefField(anchor string) PageRefField
CreatePageRefField 创建页码引用域
type PageSettings ¶
type PageSettings struct {
// 页面尺寸
Size PageSize
// 自定义尺寸(当Size为Custom时使用)
CustomWidth float64 // 自定义宽度(毫米)
CustomHeight float64 // 自定义高度(毫米)
// 页面方向
Orientation PageOrientation
// 页面边距(毫米)
MarginTop float64
MarginRight float64
MarginBottom float64
MarginLeft float64
// 页眉页脚距离(毫米)
HeaderDistance float64
// 装订线宽度(毫米)
GutterWidth float64
// 文档网格设置
DocGridType DocGridType // 文档网格类型
DocGridLinePitch int // 行网格间距(1/20磅)
DocGridCharSpace int // 字符间距
}
PageSettings 页面设置配置
func DefaultPageSettings ¶
func DefaultPageSettings() *PageSettings
DefaultPageSettings 返回默认页面设置(A4纵向)
type PageSize ¶
type PageSize string
PageSize 页面尺寸类型
const ( // PageSizeA4 A4纸张 (210mm x 297mm) PageSizeA4 PageSize = "A4" // PageSizeLetter 美国Letter (8.5" x 11") PageSizeLetter PageSize = "Letter" // PageSizeLegal 美国Legal (8.5" x 14") PageSizeLegal PageSize = "Legal" // PageSizeA3 A3纸张 (297mm x 420mm) PageSizeA3 PageSize = "A3" // PageSizeA5 A5纸张 (148mm x 210mm) PageSizeA5 PageSize = "A5" // PageSizeCustom 自定义尺寸 PageSizeCustom PageSize = "Custom" )
type PageSizeXML ¶
type PageSizeXML struct {
XMLName xml.Name `xml:"w:pgSz"`
W string `xml:"w:w,attr"` // 页面宽度(twips)
H string `xml:"w:h,attr"` // 页面高度(twips)
Orient string `xml:"w:orient,attr"` // 页面方向
}
PageSizeXML 页面尺寸XML结构
type Paragraph ¶
type Paragraph struct {
XMLName xml.Name `xml:"w:p"`
Properties *ParagraphProperties `xml:"w:pPr,omitempty"`
Runs []Run `xml:"w:r"`
}
Paragraph 表示一个段落
func (*Paragraph) AddFormattedText ¶
func (p *Paragraph) AddFormattedText(text string, format *TextFormat)
AddFormattedText 向段落添加格式化的文本内容。
此方法允许在一个段落中混合使用不同格式的文本。 新的文本会作为一个新的 Run 添加到段落中。
参数 text 是要添加的文本内容。 参数 format 指定文本格式,如果为 nil 则使用默认格式。
示例:
para := doc.AddParagraph("这个段落包含")
// 添加粗体红色文本
para.AddFormattedText("粗体红色", &document.TextFormat{
Bold: true,
FontColor: "FF0000",
})
// 添加普通文本
para.AddFormattedText("和普通文本", nil)
// 添加斜体蓝色文本
para.AddFormattedText("以及斜体蓝色", &document.TextFormat{
Italic: true,
FontColor: "0000FF",
FontSize: 14,
})
func (*Paragraph) AddInlineMath ¶ added in v1.5.0
AddInlineMathFormula 向段落中添加行内数学公式 这将在当前段落的末尾添加一个数学公式
func (*Paragraph) AddPageBreak ¶ added in v1.5.0
func (p *Paragraph) AddPageBreak()
AddPageBreak 向段落添加一个分页符。
此方法在当前段落中添加一个分页符,分页符之后的内容将显示在新页面上。 与 Document.AddPageBreak() 不同,此方法不会创建新段落,而是在当前段落的运行中添加分页符。
示例:
para := doc.AddParagraph("第一页的内容")
para.AddPageBreak()
para.AddFormattedText("第二页的内容", nil)
func (*Paragraph) SetAlignment ¶
func (p *Paragraph) SetAlignment(alignment AlignmentType)
SetAlignment 设置段落的对齐方式。
参数 alignment 指定对齐类型,支持以下值:
- AlignLeft: 左对齐(默认)
- AlignCenter: 居中对齐
- AlignRight: 右对齐
- AlignJustify: 两端对齐
示例:
para := doc.AddParagraph("居中标题")
para.SetAlignment(document.AlignCenter)
para2 := doc.AddParagraph("右对齐文本")
para2.SetAlignment(document.AlignRight)
func (*Paragraph) SetBold ¶ added in v1.5.0
SetBold 设置段落中所有文本的粗体效果。
参数 bold 表示是否启用粗体。 当设置为 true 时,将对段落中所有运行应用粗体效果。 当设置为 false 时,将移除所有运行的粗体效果。
示例:
para := doc.AddParagraph("这是粗体文本")
para.SetBold(true)
func (*Paragraph) SetBorder ¶ added in v1.3.9
func (p *Paragraph) SetBorder(top, left, bottom, right *ParagraphBorderConfig)
SetBorder 设置段落的边框。
此方法用于为段落添加边框装饰,特别适用于实现Markdown分割线(---)的转换。
参数:
- top: 上边框配置,传入nil表示不设置上边框
- left: 左边框配置,传入nil表示不设置左边框
- bottom: 下边框配置,传入nil表示不设置下边框
- right: 右边框配置,传入nil表示不设置右边框
边框配置包含样式、粗细、颜色和间距等属性。
示例:
// 设置分割线效果(仅底边框)
para := doc.AddParagraph("")
para.SetBorder(nil, nil, &document.ParagraphBorderConfig{
Style: document.BorderStyleSingle,
Size: 12, // 1.5磅粗细
Color: "000000", // 黑色
Space: 1, // 1磅间距
}, nil)
// 设置完整边框
para := doc.AddParagraph("带边框的段落")
borderConfig := &document.ParagraphBorderConfig{
Style: document.BorderStyleDouble,
Size: 8,
Color: "0000FF", // 蓝色
Space: 2,
}
para.SetBorder(borderConfig, borderConfig, borderConfig, borderConfig)
func (*Paragraph) SetColor ¶ added in v1.5.0
SetColor 设置段落中所有文本的颜色。
参数 color 是十六进制颜色值,如 "FF0000"(红色)、"0000FF"(蓝色)等。 颜色值不需要 "#" 前缀,如果包含会自动移除。 传入空字符串将移除颜色设置。
示例:
para := doc.AddParagraph("这是红色文本")
para.SetColor("FF0000")
func (*Paragraph) SetFontFamily ¶ added in v1.5.0
SetFontFamily 设置段落中所有文本的字体。
参数 name 是字体名称,如 "Arial"、"Times New Roman"、"微软雅黑" 等。
示例:
para := doc.AddParagraph("这是自定义字体文本")
para.SetFontFamily("微软雅黑")
func (*Paragraph) SetFontSize ¶ added in v1.5.0
SetFontSize 设置段落中所有文本的字体大小。
参数 size 是字体大小(磅),如 12、14、16 等。 传入 0 或负数将移除字体大小设置。
示例:
para := doc.AddParagraph("这是大号文本")
para.SetFontSize(16)
func (*Paragraph) SetHighlight ¶ added in v1.5.0
SetHighlight 设置段落中所有文本的高亮颜色。
参数 color 是高亮颜色名称,支持的颜色包括: "yellow", "green", "cyan", "magenta", "blue", "red", "darkBlue", "darkCyan", "darkGreen", "darkMagenta", "darkRed", "darkYellow", "darkGray", "lightGray", "black" 等。 传入空字符串将移除高亮效果。
示例:
para := doc.AddParagraph("这是高亮文本")
para.SetHighlight("yellow")
func (*Paragraph) SetHorizontalRule ¶ added in v1.3.9
func (p *Paragraph) SetHorizontalRule(style BorderStyle, size int, color string)
SetHorizontalRule 设置水平分割线。
此方法是SetBorder的简化版本,专门用于快速创建Markdown风格的分割线效果。 只在段落底部添加一条水平线,适用于Markdown中的 --- 或 *** 语法。
参数:
- style: 边框样式,如BorderStyleSingle、BorderStyleDouble等
- size: 边框粗细(1/8磅为单位,建议值12-18)
- color: 边框颜色(十六进制,如"000000")
示例:
// 创建简单分割线
para := doc.AddParagraph("")
para.SetHorizontalRule(document.BorderStyleSingle, 12, "000000")
// 创建粗双线分割线
para := doc.AddParagraph("")
para.SetHorizontalRule(document.BorderStyleDouble, 18, "808080")
func (*Paragraph) SetIndentation ¶
SetIndentation 设置段落的缩进属性。
参数:
- firstLineCm: 首行缩进,单位为厘米(可以为负数表示悬挂缩进)
- leftCm: 左缩进,单位为厘米
- rightCm: 右缩进,单位为厘米
示例:
para := doc.AddParagraph("这是一个有缩进的段落")
para.SetIndentation(0.5, 0, 0) // 首行缩进0.5厘米
para.SetIndentation(-0.5, 1, 0) // 悬挂缩进0.5厘米,左缩进1厘米
func (*Paragraph) SetItalic ¶ added in v1.5.0
SetItalic 设置段落中所有文本的斜体效果。
参数 italic 表示是否启用斜体。 当设置为 true 时,将对段落中所有运行应用斜体效果。 当设置为 false 时,将移除所有运行的斜体效果。
示例:
para := doc.AddParagraph("这是斜体文本")
para.SetItalic(true)
func (*Paragraph) SetKeepLines ¶ added in v1.5.0
SetKeepLines 设置段落中的所有行保持在同一页。
此方法用于防止段落在分页时被拆分到多个页面, 确保段落的所有行都显示在同一页上。
参数:
- keep: true表示启用该属性,false表示禁用
示例:
// 确保整个段落不被分页
para := doc.AddParagraph("这是一个重要的段落,需要保持完整显示。")
para.SetKeepLines(true)
func (*Paragraph) SetKeepWithNext ¶ added in v1.5.0
SetKeepWithNext 设置段落与下一段落保持在同一页。
此方法用于确保当前段落和下一段落不会被分页符分隔, 常用于标题和正文的组合,或需要保持连续性的内容。
参数:
- keep: true表示启用该属性,false表示禁用
示例:
// 标题与下一段保持在一起
title := doc.AddParagraph("第一章 概述")
title.SetKeepWithNext(true)
doc.AddParagraph("本章介绍...") // 这段内容会与标题保持在同一页
func (*Paragraph) SetOutlineLevel ¶ added in v1.5.0
SetOutlineLevel 设置段落的大纲级别。
大纲级别用于在文档导航窗格中显示文档结构,级别范围为0-8。 通常用于标题段落,配合目录功能使用。
参数:
- level: 大纲级别,0-8之间的整数(0表示正文,1-8对应标题1-8)
示例:
// 设置为一级标题的大纲级别
title := doc.AddParagraph("第一章")
title.SetOutlineLevel(0) // 对应Heading1
// 设置为二级标题的大纲级别
subtitle := doc.AddParagraph("1.1 概述")
subtitle.SetOutlineLevel(1) // 对应Heading2
func (*Paragraph) SetPageBreakBefore ¶ added in v1.5.0
SetPageBreakBefore 设置段落前插入分页符。
此方法用于在段落之前强制插入分页符,使段落从新页开始显示。 常用于章节标题或需要单独成页的内容。
参数:
- pageBreak: true表示启用段前分页,false表示禁用
示例:
// 章节标题从新页开始
chapter := doc.AddParagraph("第二章 详细说明")
chapter.SetPageBreakBefore(true)
func (*Paragraph) SetParagraphFormat ¶ added in v1.5.0
func (p *Paragraph) SetParagraphFormat(config *ParagraphFormatConfig)
SetParagraphFormat 使用配置一次性设置段落的所有格式属性。
此方法提供了一种便捷的方式来设置段落的所有格式属性, 而不需要调用多个单独的设置方法。只有非零值的属性会被应用。
参数:
- config: 段落格式配置,包含所有格式属性
示例:
// 创建一个带完整格式的段落
para := doc.AddParagraph("重要章节标题")
para.SetParagraphFormat(&document.ParagraphFormatConfig{
Alignment: document.AlignCenter,
Style: "Heading1",
LineSpacing: 1.5,
BeforePara: 24,
AfterPara: 12,
KeepWithNext: true,
PageBreakBefore: true,
OutlineLevel: 0,
})
// 设置带缩进的正文段落
para2 := doc.AddParagraph("正文内容...")
para2.SetParagraphFormat(&document.ParagraphFormatConfig{
Alignment: document.AlignJustify,
FirstLineCm: 0.5,
LineSpacing: 1.5,
BeforePara: 6,
AfterPara: 6,
WidowControl: true,
})
func (*Paragraph) SetSnapToGrid ¶ added in v1.5.0
SetSnapToGrid 设置段落的网格对齐属性。
网格对齐控制段落的行是否对齐到文档的网格。当文档启用了网格设置时 (如中文文档中常见的"如果定义了文档网格,则对齐到网格"选项), 自定义的行间距可能不会精确生效,因为行会自动对齐到网格线。
通过设置 snapToGrid 为 false,可以禁用该段落的网格对齐, 从而使自定义行间距能够精确生效。
参数:
- snapToGrid: true表示启用网格对齐(默认),false表示禁用网格对齐
示例:
// 禁用网格对齐,使自定义行间距精确生效
para := doc.AddParagraph("这段文字使用精确的行间距")
para.SetSpacing(&document.SpacingConfig{LineSpacing: 1.5})
para.SetSnapToGrid(false) // 禁用网格对齐
func (*Paragraph) SetSpacing ¶
func (p *Paragraph) SetSpacing(config *SpacingConfig)
SetSpacing 设置段落的间距配置。
参数 config 包含各种间距设置,如果为 nil 则不进行任何设置。 配置选项包括:
- LineSpacing: 行间距倍数(如 1.5 表示1.5倍行距)
- BeforePara: 段前间距(磅)
- AfterPara: 段后间距(磅)
- FirstLineIndent: 首行缩进(磅)
注意:间距值会自动转换为 Word 内部使用的 TWIPs 单位(1磅=20TWIPs)。
示例:
para := doc.AddParagraph("带间距的段落")
// 设置复杂间距
para.SetSpacing(&document.SpacingConfig{
LineSpacing: 1.5, // 1.5倍行距
BeforePara: 12, // 段前12磅
AfterPara: 6, // 段后6磅
FirstLineIndent: 24, // 首行缩进24磅
})
// 只设置行间距
para2 := doc.AddParagraph("双倍行距")
para2.SetSpacing(&document.SpacingConfig{
LineSpacing: 2.0,
})
func (*Paragraph) SetStrike ¶ added in v1.5.0
SetStrike 设置段落中所有文本的删除线效果。
参数 strike 表示是否启用删除线。 当设置为 true 时,将对段落中所有运行应用删除线效果。 当设置为 false 时,将移除所有运行的删除线效果。
示例:
para := doc.AddParagraph("这是删除线文本")
para.SetStrike(true)
func (*Paragraph) SetStyle ¶
SetStyle 设置段落的样式。
参数 styleID 是要应用的样式ID,如 "Heading1"、"Normal" 等。 此方法会设置段落的样式引用,确保段落使用指定的样式。
示例:
para := doc.AddParagraph("这是一个段落")
para.SetStyle("Heading2") // 设置为二级标题样式
func (*Paragraph) SetUnderline ¶ added in v1.5.0
SetUnderline 设置段落中所有文本的下划线效果。
参数 underline 表示是否启用下划线。 当设置为 true 时,将对段落中所有运行应用单线下划线效果。 当设置为 false 时,将移除所有运行的下划线效果。
示例:
para := doc.AddParagraph("这是下划线文本")
para.SetUnderline(true)
func (*Paragraph) SetWidowControl ¶ added in v1.5.0
SetWidowControl 设置段落的孤行控制。
孤行控制用于防止段落的第一行或最后一行单独出现在页面底部或顶部, 提高文档的排版质量。
参数:
- control: true表示启用孤行控制(默认),false表示禁用
示例:
para := doc.AddParagraph("这是一个长段落...")
para.SetWidowControl(true) // 启用孤行控制
type ParagraphBorder ¶ added in v1.3.9
type ParagraphBorder struct {
XMLName xml.Name `xml:"w:pBdr"`
Top *ParagraphBorderLine `xml:"w:top,omitempty"`
Left *ParagraphBorderLine `xml:"w:left,omitempty"`
Bottom *ParagraphBorderLine `xml:"w:bottom,omitempty"`
Right *ParagraphBorderLine `xml:"w:right,omitempty"`
}
ParagraphBorder 段落边框
type ParagraphBorderConfig ¶ added in v1.3.9
type ParagraphBorderConfig struct {
Style BorderStyle // 边框样式
Size int // 边框粗细(1/8磅为单位,默认值建议12,即1.5磅)
Color string // 边框颜色(十六进制,如"000000"表示黑色)
Space int // 边框与文本的间距(磅,默认值建议1)
}
ParagraphBorderConfig 段落边框配置(区别于表格边框配置)
type ParagraphBorderLine ¶ added in v1.3.9
type ParagraphBorderLine struct {
Val string `xml:"w:val,attr"`
Color string `xml:"w:color,attr"`
Sz string `xml:"w:sz,attr"`
Space string `xml:"w:space,attr"`
}
ParagraphBorderLine 段落边框线
type ParagraphFormatConfig ¶ added in v1.5.0
type ParagraphFormatConfig struct {
// 基础格式
Alignment AlignmentType // 对齐方式(AlignLeft, AlignCenter, AlignRight, AlignJustify)
Style string // 段落样式ID(如"Heading1", "Normal"等)
// 间距设置
LineSpacing float64 // 行间距(倍数,如1.5表示1.5倍行距)
BeforePara int // 段前间距(磅)
AfterPara int // 段后间距(磅)
FirstLineIndent int // 首行缩进(磅)
// 缩进设置
FirstLineCm float64 // 首行缩进(厘米,可以为负数表示悬挂缩进)
LeftCm float64 // 左缩进(厘米)
RightCm float64 // 右缩进(厘米)
// 分页与控制
KeepWithNext bool // 与下一段落保持在同一页
KeepLines bool // 段落中的所有行保持在同一页
PageBreakBefore bool // 段前分页
WidowControl bool // 孤行控制
SnapToGrid *bool // 是否对齐网格(设置为false可禁用网格对齐,使自定义行间距精确生效)
// 大纲级别
OutlineLevel int // 大纲级别(0-8,0表示正文,1-8对应标题1-8)
}
ParagraphFormatConfig 段落格式配置
此结构体提供了段落所有格式属性的统一配置接口, 允许一次性设置多个段落属性,提高代码的可读性和易用性。
type ParagraphProperties ¶
type ParagraphProperties struct {
XMLName xml.Name `xml:"w:pPr"`
ParagraphStyle *ParagraphStyle `xml:"w:pStyle,omitempty"`
NumberingProperties *NumberingProperties `xml:"w:numPr,omitempty"`
ParagraphBorder *ParagraphBorder `xml:"w:pBdr,omitempty"`
Tabs *Tabs `xml:"w:tabs,omitempty"`
SnapToGrid *SnapToGrid `xml:"w:snapToGrid,omitempty"` // 网格对齐设置
Spacing *Spacing `xml:"w:spacing,omitempty"`
Indentation *Indentation `xml:"w:ind,omitempty"`
Justification *Justification `xml:"w:jc,omitempty"`
KeepNext *KeepNext `xml:"w:keepNext,omitempty"` // 与下一段落保持在一起
KeepLines *KeepLines `xml:"w:keepLines,omitempty"` // 段落中的行保持在一起
PageBreakBefore *PageBreakBefore `xml:"w:pageBreakBefore,omitempty"` // 段前分页
WidowControl *WidowControl `xml:"w:widowControl,omitempty"` // 孤行控制
OutlineLevel *OutlineLevel `xml:"w:outlineLvl,omitempty"` // 大纲级别
}
ParagraphProperties 段落属性
type ParagraphStyle ¶
ParagraphStyle 段落样式引用
type PicElement ¶ added in v1.3.3
type PicElement struct {
XMLName xml.Name `xml:"pic:pic"`
Xmlns string `xml:"xmlns:pic,attr"`
NvPicPr *NvPicPr `xml:"pic:nvPicPr"`
BlipFill *BlipFill `xml:"pic:blipFill"`
SpPr *SpPr `xml:"pic:spPr"`
}
PicElement 图片
type PicLocks ¶ added in v1.3.9
type PicLocks struct {
XMLName xml.Name `xml:"a:picLocks"`
NoChangeAspect string `xml:"noChangeAspect,attr,omitempty"`
NoChangeArrowheads string `xml:"noChangeArrowheads,attr,omitempty"`
}
PicLocks 图片锁定属性
type PolygonLineTo ¶ added in v1.3.3
type PolygonLineTo struct {
XMLName xml.Name `xml:"wp:lineTo"`
X string `xml:"x,attr"`
Y string `xml:"y,attr"`
}
PolygonLineTo 多边形线段
type PolygonStart ¶ added in v1.3.3
type PolygonStart struct {
XMLName xml.Name `xml:"wp:start"`
X string `xml:"x,attr"`
Y string `xml:"y,attr"`
}
PolygonStart 多边形起点
type PrstGeom ¶ added in v1.3.3
type PrstGeom struct {
XMLName xml.Name `xml:"a:prstGeom"`
Prst string `xml:"prst,attr"`
AvLst *AvLst `xml:"a:avLst"`
}
PrstGeom 预设几何图形
type Relationship ¶
type Relationship struct {
ID string `xml:"Id,attr"`
Type string `xml:"Type,attr"`
Target string `xml:"Target,attr"`
}
Relationship 单个关系
type Relationships ¶
type Relationships struct {
XMLName xml.Name `xml:"Relationships"`
Xmlns string `xml:"xmlns,attr"`
Relationships []Relationship `xml:"Relationship"`
}
Relationships 文档关系
type RowBreakConfig ¶
type RowBreakConfig struct {
XMLName xml.Name `xml:"w:trPr"`
CantSplit *CantSplit `xml:"w:cantSplit,omitempty"` // 禁止跨页分割
TrHeight *TableRowH `xml:"w:trHeight,omitempty"` // 行高
TblHeader *TblHeader `xml:"w:tblHeader,omitempty"` // 标题行重复
}
RowBreakConfig 行分页配置
type RowHeightConfig ¶
type RowHeightConfig struct {
Height int // 行高值(磅,1磅=20twips)
Rule RowHeightRule // 行高规则
}
RowHeightConfig 行高配置
type RowHeightRule ¶
type RowHeightRule string
RowHeightRule 行高规则
const ( // RowHeightAuto 自动调整行高 RowHeightAuto RowHeightRule = "auto" // RowHeightMinimum 最小行高 RowHeightMinimum RowHeightRule = "atLeast" // RowHeightExact 固定行高 RowHeightExact RowHeightRule = "exact" )
type Run ¶
type Run struct {
XMLName xml.Name `xml:"w:r"`
Properties *RunProperties `xml:"w:rPr,omitempty"`
Text Text `xml:"w:t,omitempty"`
Break *Break `xml:"w:br,omitempty"` // 分页符 / Page break
Drawing *DrawingElement `xml:"w:drawing,omitempty"`
FieldChar *FieldChar `xml:"w:fldChar,omitempty"`
InstrText *InstrText `xml:"w:instrText,omitempty"`
}
Run 表示一段文本
func (*Run) MarshalXML ¶ added in v1.5.0
MarshalXML 自定义Run的XML序列化 此方法确保只有非空元素才被序列化,特别是对于Drawing元素
type RunProperties ¶
type RunProperties struct {
XMLName xml.Name `xml:"w:rPr"`
FontFamily *FontFamily `xml:"w:rFonts,omitempty"`
Bold *Bold `xml:"w:b,omitempty"`
BoldCs *BoldCs `xml:"w:bCs,omitempty"`
Italic *Italic `xml:"w:i,omitempty"`
ItalicCs *ItalicCs `xml:"w:iCs,omitempty"`
Underline *Underline `xml:"w:u,omitempty"`
Strike *Strike `xml:"w:strike,omitempty"`
Color *Color `xml:"w:color,omitempty"`
FontSize *FontSize `xml:"w:sz,omitempty"`
FontSizeCs *FontSizeCs `xml:"w:szCs,omitempty"`
Highlight *Highlight `xml:"w:highlight,omitempty"`
}
RunProperties 文本属性 注意:字段顺序必须符合OpenXML标准,w:rFonts必须在w:color之前
type SDT ¶
type SDT struct {
XMLName xml.Name `xml:"w:sdt"`
Properties *SDTProperties `xml:"w:sdtPr"`
EndPr *SDTEndPr `xml:"w:sdtEndPr,omitempty"`
Content *SDTContent `xml:"w:sdtContent"`
}
SDT 结构化文档标签,用于目录等特殊功能
func (*SDT) AddTOCEntry ¶
AddTOCEntry 向目录SDT添加条目
type SDTContent ¶
type SDTContent struct {
XMLName xml.Name `xml:"w:sdtContent"`
Elements []interface{} `xml:"-"` // 使用自定义序列化
}
SDTContent SDT内容
func (*SDTContent) MarshalXML ¶
func (s *SDTContent) MarshalXML(e *xml.Encoder, start xml.StartElement) error
MarshalXML 自定义XML序列化
type SDTEndPr ¶
type SDTEndPr struct {
XMLName xml.Name `xml:"w:sdtEndPr"`
RunPr *RunProperties `xml:"w:rPr,omitempty"`
}
SDTEndPr SDT结束属性
type SDTPlaceholder ¶
type SDTPlaceholder struct {
XMLName xml.Name `xml:"w:placeholder"`
DocPart *DocPart `xml:"w:docPart,omitempty"`
}
SDTPlaceholder SDT占位符
type SDTProperties ¶
type SDTProperties struct {
XMLName xml.Name `xml:"w:sdtPr"`
RunPr *RunProperties `xml:"w:rPr,omitempty"`
ID *SDTID `xml:"w:id,omitempty"`
Color *SDTColor `xml:"w15:color,omitempty"`
DocPartObj *DocPartObj `xml:"w:docPartObj,omitempty"`
Placeholder *SDTPlaceholder `xml:"w:placeholder,omitempty"`
}
SDTProperties SDT属性
type SectionProperties ¶
type SectionProperties struct {
XMLName xml.Name `xml:"w:sectPr"`
XmlnsR string `xml:"xmlns:r,attr,omitempty"`
PageSize *PageSizeXML `xml:"w:pgSz,omitempty"`
PageMargins *PageMargin `xml:"w:pgMar,omitempty"`
Columns *Columns `xml:"w:cols,omitempty"`
HeaderReferences []*HeaderFooterReference `xml:"w:headerReference,omitempty"`
TitlePage *TitlePage `xml:"w:titlePg,omitempty"`
PageNumType *PageNumType `xml:"w:pgNumType,omitempty"`
DocGrid *DocGrid `xml:"w:docGrid,omitempty"`
}
SectionProperties 节属性,包含页面设置信息
func (*SectionProperties) ElementType ¶
func (s *SectionProperties) ElementType() string
ElementType 返回节属性元素类型
type Settings ¶ added in v1.3.3
type Settings struct {
XMLName xml.Name `xml:"w:settings"`
Xmlns string `xml:"xmlns:w,attr"`
DefaultTabStop *DefaultTabStop `xml:"w:defaultTabStop,omitempty"`
CharacterSpacingControl *CharacterSpacingControl `xml:"w:characterSpacingControl,omitempty"`
FootnotePr *FootnotePr `xml:"w:footnotePr,omitempty"`
EndnotePr *EndnotePr `xml:"w:endnotePr,omitempty"`
}
Settings 文档设置XML结构
type ShadingConfig ¶
type ShadingConfig struct {
Pattern ShadingPattern // 底纹图案
ForegroundColor string // 前景色(十六进制)
BackgroundColor string // 背景色(十六进制)
}
ShadingConfig 底纹配置
type ShadingPattern ¶
type ShadingPattern string
ShadingPattern 底纹图案类型
const ( ShadingPatternClear ShadingPattern = "clear" // 透明/实色 ShadingPatternSolid ShadingPattern = "clear" // 实色(使用clear实现) ShadingPatternPct5 ShadingPattern = "pct5" // 5% ShadingPatternPct10 ShadingPattern = "pct10" // 10% ShadingPatternPct20 ShadingPattern = "pct20" // 20% ShadingPatternPct25 ShadingPattern = "pct25" // 25% ShadingPatternPct30 ShadingPattern = "pct30" // 30% ShadingPatternPct40 ShadingPattern = "pct40" // 40% ShadingPatternPct50 ShadingPattern = "pct50" // 50% ShadingPatternPct60 ShadingPattern = "pct60" // 60% ShadingPatternPct70 ShadingPattern = "pct70" // 70% ShadingPatternPct75 ShadingPattern = "pct75" // 75% ShadingPatternPct80 ShadingPattern = "pct80" // 80% ShadingPatternPct90 ShadingPattern = "pct90" // 90% ShadingPatternHorzStripe ShadingPattern = "horzStripe" // 水平条纹 ShadingPatternVertStripe ShadingPattern = "vertStripe" // 垂直条纹 ShadingPatternReverseDiagStripe ShadingPattern = "reverseDiagStripe" // 反对角条纹 ShadingPatternDiagStripe ShadingPattern = "diagStripe" // 对角条纹 ShadingPatternHorzCross ShadingPattern = "horzCross" // 水平十字 ShadingPatternDiagCross ShadingPattern = "diagCross" // 对角十字 )
type SimplePosition ¶ added in v1.3.3
type SimplePosition struct {
XMLName xml.Name `xml:"wp:simplePos"`
X string `xml:"x,attr"`
Y string `xml:"y,attr"`
}
SimplePosition 简单位置
type SnapToGrid ¶ added in v1.5.0
type SnapToGrid struct {
XMLName xml.Name `xml:"w:snapToGrid"`
Val string `xml:"w:val,attr,omitempty"`
}
SnapToGrid 网格对齐设置 设置为 "0" 或 "false" 时禁用网格对齐,允许自定义行间距生效 注意:此类型在 style 包中有相同定义,这是有意为之,因为两个包可独立使用
type SpPr ¶ added in v1.3.3
type SpPr struct {
XMLName xml.Name `xml:"pic:spPr"`
Xfrm *Xfrm `xml:"a:xfrm"`
PrstGeom *PrstGeom `xml:"a:prstGeom"`
}
SpPr 形状属性
type Spacing ¶
type Spacing struct {
XMLName xml.Name `xml:"w:spacing"`
Before string `xml:"w:before,attr,omitempty"`
After string `xml:"w:after,attr,omitempty"`
Line string `xml:"w:line,attr,omitempty"`
LineRule string `xml:"w:lineRule,attr,omitempty"`
}
Spacing 间距设置
type SpacingConfig ¶
type SpacingConfig struct {
LineSpacing float64 // 行间距(倍数,如1.5表示1.5倍行距)
BeforePara int // 段前间距(磅)
AfterPara int // 段后间距(磅)
FirstLineIndent int // 首行缩进(磅)
}
SpacingConfig 间距配置
type TOCConfig ¶
type TOCConfig struct {
Title string // 目录标题,默认为"目录"
MaxLevel int // 最大级别,默认为3(显示1-3级标题)
ShowPageNum bool // 是否显示页码,默认为true
RightAlign bool // 页码是否右对齐,默认为true
UseHyperlink bool // 是否使用超链接,默认为true
DotLeader bool // 是否使用点状引导线,默认为true
}
TOCConfig 目录配置
type TOCEntry ¶
type TOCEntry struct {
Text string // 条目文本
Level int // 级别(1-9)
PageNum int // 页码
BookmarkID string // 书签ID(用于超链接)
}
TOCEntry 目录条目
type TOCField ¶
type TOCField struct {
XMLName xml.Name `xml:"w:fldSimple"`
Instr string `xml:"w:instr,attr"`
Runs []Run `xml:"w:r"`
}
TOCField 目录域
type TabDef ¶
type TabDef struct {
XMLName xml.Name `xml:"w:tab"`
Val string `xml:"w:val,attr"`
Leader string `xml:"w:leader,attr,omitempty"`
Pos string `xml:"w:pos,attr"`
}
TabDef 制表符定义
type Table ¶
type Table struct {
XMLName xml.Name `xml:"w:tbl"`
Properties *TableProperties `xml:"w:tblPr,omitempty"`
Grid *TableGrid `xml:"w:tblGrid,omitempty"`
Rows []TableRow `xml:"w:tr"`
}
Table 表示一个表格
func (*Table) AddCellFormattedParagraph ¶ added in v1.5.0
func (t *Table) AddCellFormattedParagraph(row, col int, text string, format *TextFormat) (*Paragraph, error)
AddCellFormattedParagraph 向单元格添加格式化段落 参数:
- row: 行索引(从0开始)
- col: 列索引(从0开始)
- text: 段落文本内容
- format: 文本格式配置
返回:
- *Paragraph: 新添加的段落对象
- error: 如果索引无效则返回错误
func (*Table) AddCellFormattedText ¶
func (t *Table) AddCellFormattedText(row, col int, text string, format *TextFormat) error
AddCellFormattedText 添加格式化文本到单元格(追加模式)
func (*Table) AddCellList ¶ added in v1.5.0
func (t *Table) AddCellList(row, col int, config *CellListConfig) error
AddCellList 向单元格添加列表 参数:
- row: 行索引(从0开始)
- col: 列索引(从0开始)
- config: 列表配置
返回:
- error: 如果索引无效则返回错误
func (*Table) AddCellParagraph ¶ added in v1.5.0
AddCellParagraph 向单元格添加段落 参数:
- row: 行索引(从0开始)
- col: 列索引(从0开始)
- text: 段落文本内容
返回:
- *Paragraph: 新添加的段落对象
- error: 如果索引无效则返回错误
func (*Table) AddNestedTable ¶ added in v1.5.0
func (t *Table) AddNestedTable(row, col int, config *TableConfig) (*Table, error)
AddNestedTable 向单元格添加嵌套表格 参数:
- row: 行索引(从0开始)
- col: 列索引(从0开始)
- config: 嵌套表格的配置
返回:
- *Table: 新创建的嵌套表格对象
- error: 如果索引无效或配置无效则返回错误
func (*Table) AppendColumn ¶
AppendColumn 在表格末尾添加列
func (*Table) ApplyTableStyle ¶
func (t *Table) ApplyTableStyle(config *TableStyleConfig) error
ApplyTableStyle 应用表格样式
func (*Table) ClearCellContent ¶
ClearCellContent 清空单元格内容但保留格式
func (*Table) ClearCellFormat ¶
ClearCellFormat 清空单元格格式但保留内容
func (*Table) ClearCellParagraphs ¶ added in v1.5.0
ClearCellParagraphs 清空单元格中的所有段落,只保留一个空段落 参数:
- row: 行索引(从0开始)
- col: 列索引(从0开始)
返回:
- error: 如果索引无效则返回错误
func (*Table) CreateCustomTableStyle ¶
func (t *Table) CreateCustomTableStyle(styleID, styleName string, borderConfig *TableBorderConfig, shadingConfig *ShadingConfig, firstRowBold bool) error
CreateCustomTableStyle 创建自定义表格样式
func (*Table) DeleteColumns ¶
DeleteColumns 删除指定范围的列
func (*Table) DeleteRows ¶
DeleteRows 删除指定范围的行
func (*Table) FindCells ¶
func (t *Table) FindCells(predicate func(row, col int, cell *TableCell, text string) bool) ([]*CellInfo, error)
FindCells 查找满足条件的单元格
func (*Table) FindCellsByText ¶
FindCellsByText 根据文本内容查找单元格
func (*Table) ForEachInColumn ¶
func (t *Table) ForEachInColumn(colIndex int, fn func(row int, cell *TableCell, text string) error) error
ForEachInColumn 遍历指定列的所有单元格
func (*Table) ForEachInRow ¶
func (t *Table) ForEachInRow(rowIndex int, fn func(col int, cell *TableCell, text string) error) error
ForEachInRow 遍历指定行的所有单元格
func (*Table) GetCellFormat ¶
func (t *Table) GetCellFormat(row, col int) (*CellFormat, error)
GetCellFormat 获取单元格格式信息
func (*Table) GetCellParagraphs ¶ added in v1.5.0
GetCellParagraphs 获取单元格中的所有段落 参数:
- row: 行索引(从0开始)
- col: 列索引(从0开始)
返回:
- []Paragraph: 单元格中的所有段落
- error: 如果索引无效则返回错误
func (*Table) GetCellRange ¶
GetCellRange 获取指定范围内的所有单元格
func (*Table) GetCellText ¶
GetCellText 获取单元格文本
func (*Table) GetCellTextDirection ¶
func (t *Table) GetCellTextDirection(row, col int) (CellTextDirection, error)
GetCellTextDirection 获取单元格文字方向
func (*Table) GetMergedCellInfo ¶
GetMergedCellInfo 获取合并单元格信息
func (*Table) GetNestedTables ¶ added in v1.5.0
GetNestedTables 获取单元格中的所有嵌套表格 参数:
- row: 行索引(从0开始)
- col: 列索引(从0开始)
返回:
- []Table: 单元格中的所有嵌套表格
- error: 如果索引无效则返回错误
func (*Table) GetRowHeight ¶
func (t *Table) GetRowHeight(rowIndex int) (*RowHeightConfig, error)
GetRowHeight 获取行高配置
func (*Table) GetTableBreakInfo ¶
GetTableBreakInfo 获取表格分页信息
func (*Table) GetTableLayout ¶
func (t *Table) GetTableLayout() *TableLayoutConfig
GetTableLayout 获取表格布局配置
func (*Table) InsertColumn ¶
InsertColumn 在指定位置插入列
func (*Table) IsCellMerged ¶
IsCellMerged 检查单元格是否被合并
func (*Table) IsRowHeader ¶
IsRowHeader 检查行是否为标题行
func (*Table) IsRowKeepTogether ¶
IsRowKeepTogether 检查行是否禁止跨页分割
func (*Table) MergeCellsHorizontal ¶
MergeCellsHorizontal 水平合并单元格(合并列)
func (*Table) MergeCellsRange ¶
MergeCellsRange 合并单元格区域(多行多列)
func (*Table) MergeCellsVertical ¶
MergeCellsVertical 垂直合并单元格(合并行)
func (*Table) NewCellIterator ¶
func (t *Table) NewCellIterator() *CellIterator
NewCellIterator 创建新的单元格迭代器
func (*Table) RemoveCellBorders ¶
RemoveCellBorders 移除单元格边框
func (*Table) RemoveTableBorders ¶
RemoveTableBorders 移除表格边框
func (*Table) SetAlternatingRowColors ¶
SetAlternatingRowColors 设置奇偶行颜色交替
func (*Table) SetCellBorders ¶
func (t *Table) SetCellBorders(row, col int, config *CellBorderConfig) error
SetCellBorders 设置单元格边框
func (*Table) SetCellFormat ¶
func (t *Table) SetCellFormat(row, col int, format *CellFormat) error
SetCellFormat 设置单元格格式
func (*Table) SetCellFormattedText ¶
func (t *Table) SetCellFormattedText(row, col int, text string, format *TextFormat) error
SetCellFormattedText 设置单元格富文本内容
func (*Table) SetCellPadding ¶
SetCellPadding 设置单元格内边距
func (*Table) SetCellShading ¶
func (t *Table) SetCellShading(row, col int, config *ShadingConfig) error
SetCellShading 设置单元格背景
func (*Table) SetCellText ¶
SetCellText 设置单元格文本
func (*Table) SetCellTextDirection ¶
func (t *Table) SetCellTextDirection(row, col int, direction CellTextDirection) error
SetCellTextDirection 设置单元格文字方向
func (*Table) SetHeaderRows ¶
SetHeaderRows 设置表格标题行范围
func (*Table) SetRowAsHeader ¶
SetRowAsHeader 设置行为重复的标题行
func (*Table) SetRowHeight ¶
func (t *Table) SetRowHeight(rowIndex int, config *RowHeightConfig) error
SetRowHeight 设置行高
func (*Table) SetRowHeightRange ¶
func (t *Table) SetRowHeightRange(startRow, endRow int, config *RowHeightConfig) error
SetRowHeightRange 批量设置行高
func (*Table) SetRowKeepTogether ¶
SetRowKeepTogether 设置行禁止跨页分割
func (*Table) SetRowKeepWithNext ¶
SetRowKeepWithNext 设置行与下一行保持在同一页
func (*Table) SetTableAlignment ¶
func (t *Table) SetTableAlignment(alignment TableAlignment) error
SetTableAlignment 设置表格对齐方式(快捷方法)
func (*Table) SetTableBorders ¶
func (t *Table) SetTableBorders(config *TableBorderConfig) error
SetTableBorders 设置表格边框
func (*Table) SetTableLayout ¶
func (t *Table) SetTableLayout(config *TableLayoutConfig) error
SetTableLayout 设置表格布局和定位
func (*Table) SetTablePageBreak ¶
func (t *Table) SetTablePageBreak(config *TablePageBreakConfig) error
SetTablePageBreak 设置表格分页控制
func (*Table) SetTableShading ¶
func (t *Table) SetTableShading(config *ShadingConfig) error
SetTableShading 设置表格背景
type TableAlignment ¶
type TableAlignment string
TableAlignment 表格对齐类型
const ( // TableAlignLeft 左对齐 TableAlignLeft TableAlignment = "left" // TableAlignCenter 居中对齐 TableAlignCenter TableAlignment = "center" // TableAlignRight 右对齐 TableAlignRight TableAlignment = "right" // TableAlignInside 内侧对齐 TableAlignInside TableAlignment = "inside" // TableAlignOutside 外侧对齐 TableAlignOutside TableAlignment = "outside" )
type TableAnalysis ¶ added in v1.3.7
type TableAnalysis struct {
Index int // 表格索引
RowCount int // 行数
ColCount int // 列数
HasTemplate bool // 是否包含模板语法
TemplateRowIndex int // 模板行索引
TemplateVars map[string]bool // 模板变量
LoopVariables []string // 循环变量
}
TableAnalysis 表格分析结果
type TableBorder ¶
type TableBorder struct {
Val string `xml:"w:val,attr"` // 边框样式
Sz string `xml:"w:sz,attr"` // 边框粗细(1/8磅)
Space string `xml:"w:space,attr"` // 边框间距
Color string `xml:"w:color,attr"` // 边框颜色
ThemeColor string `xml:"w:themeColor,attr,omitempty"` // 主题颜色
}
TableBorder 边框定义
type TableBorderConfig ¶
type TableBorderConfig struct {
Top *BorderConfig // 上边框
Left *BorderConfig // 左边框
Bottom *BorderConfig // 下边框
Right *BorderConfig // 右边框
InsideH *BorderConfig // 内部水平边框
InsideV *BorderConfig // 内部垂直边框
}
TableBorderConfig 表格边框配置
type TableBorders ¶
type TableBorders struct {
XMLName xml.Name `xml:"w:tblBorders"`
Top *TableBorder `xml:"w:top,omitempty"` // 上边框
Left *TableBorder `xml:"w:left,omitempty"` // 左边框
Bottom *TableBorder `xml:"w:bottom,omitempty"` // 下边框
Right *TableBorder `xml:"w:right,omitempty"` // 右边框
InsideH *TableBorder `xml:"w:insideH,omitempty"` // 内部水平边框
InsideV *TableBorder `xml:"w:insideV,omitempty"` // 内部垂直边框
}
TableBorders 表格边框
type TableBreakRule ¶
type TableBreakRule string
TableBreakRule 表格分页规则
const ( // BreakAuto 自动分页(默认) BreakAuto TableBreakRule = "auto" // BreakPage 强制分页 BreakPage TableBreakRule = "page" // BreakColumn 强制分栏 BreakColumn TableBreakRule = "column" )
type TableCell ¶
type TableCell struct {
XMLName xml.Name `xml:"w:tc"`
Properties *TableCellProperties `xml:"w:tcPr,omitempty"`
Paragraphs []Paragraph `xml:"w:p"`
Tables []Table `xml:"w:tbl"` // 支持嵌套表格
}
TableCell 表格单元格
func (*TableCell) MarshalXML ¶ added in v1.5.0
MarshalXML 自定义XML序列化,确保嵌套表格正确序列化 OOXML要求: 单元格内容应按照原始文档顺序输出段落和表格
type TableCellBorder ¶
type TableCellBorder struct {
Val string `xml:"w:val,attr"` // 边框样式
Sz string `xml:"w:sz,attr"` // 边框粗细(1/8磅)
Space string `xml:"w:space,attr"` // 边框间距
Color string `xml:"w:color,attr"` // 边框颜色
ThemeColor string `xml:"w:themeColor,attr,omitempty"` // 主题颜色
}
TableCellBorder 单元格边框定义
type TableCellBorders ¶
type TableCellBorders struct {
XMLName xml.Name `xml:"w:tcBorders"`
Top *TableCellBorder `xml:"w:top,omitempty"` // 上边框
Left *TableCellBorder `xml:"w:left,omitempty"` // 左边框
Bottom *TableCellBorder `xml:"w:bottom,omitempty"` // 下边框
Right *TableCellBorder `xml:"w:right,omitempty"` // 右边框
InsideH *TableCellBorder `xml:"w:insideH,omitempty"` // 内部水平边框
InsideV *TableCellBorder `xml:"w:insideV,omitempty"` // 内部垂直边框
TL2BR *TableCellBorder `xml:"w:tl2br,omitempty"` // 左上到右下对角线
TR2BL *TableCellBorder `xml:"w:tr2bl,omitempty"` // 右上到左下对角线
}
TableCellBorders 单元格边框
type TableCellMargins ¶
type TableCellMargins struct {
XMLName xml.Name `xml:"w:tblCellMar"`
Top *TableCellSpace `xml:"w:top,omitempty"`
Left *TableCellSpace `xml:"w:left,omitempty"`
Bottom *TableCellSpace `xml:"w:bottom,omitempty"`
Right *TableCellSpace `xml:"w:right,omitempty"`
}
TableCellMargins 表格单元格边距
type TableCellMarginsCell ¶
type TableCellMarginsCell struct {
XMLName xml.Name `xml:"w:tcMar"`
Top *TableCellSpaceCell `xml:"w:top,omitempty"`
Left *TableCellSpaceCell `xml:"w:left,omitempty"`
Bottom *TableCellSpaceCell `xml:"w:bottom,omitempty"`
Right *TableCellSpaceCell `xml:"w:right,omitempty"`
}
TableCellMarginsCell 单元格边距(与表格边距不同的XML结构)
type TableCellProperties ¶
type TableCellProperties struct {
XMLName xml.Name `xml:"w:tcPr"`
TableCellW *TableCellW `xml:"w:tcW,omitempty"`
VAlign *VAlign `xml:"w:vAlign,omitempty"`
GridSpan *GridSpan `xml:"w:gridSpan,omitempty"`
VMerge *VMerge `xml:"w:vMerge,omitempty"`
TextDirection *TextDirection `xml:"w:textDirection,omitempty"`
Shd *TableCellShading `xml:"w:shd,omitempty"` // 单元格背景
TcBorders *TableCellBorders `xml:"w:tcBorders,omitempty"` // 单元格边框
TcMar *TableCellMarginsCell `xml:"w:tcMar,omitempty"` // 单元格边距
NoWrap *NoWrap `xml:"w:noWrap,omitempty"` // 禁止换行
HideMark *HideMark `xml:"w:hideMark,omitempty"` // 隐藏标记
}
TableCellProperties 表格单元格属性
type TableCellShading ¶
type TableCellShading struct {
XMLName xml.Name `xml:"w:shd"`
Val string `xml:"w:val,attr"` // 底纹样式
Color string `xml:"w:color,attr,omitempty"` // 前景色
Fill string `xml:"w:fill,attr,omitempty"` // 背景色
ThemeFill string `xml:"w:themeFill,attr,omitempty"` // 主题填充色
}
TableCellShading 单元格背景
type TableCellSpace ¶
TableCellSpace 表格单元格空间
type TableCellSpaceCell ¶
TableCellSpaceCell 单元格空间设置
type TableCellW ¶
type TableCellW struct {
XMLName xml.Name `xml:"w:tcW"`
W string `xml:"w:w,attr"`
Type string `xml:"w:type,attr"`
}
TableCellW 单元格宽度
type TableConfig ¶
type TableConfig struct {
Rows int // 行数
Cols int // 列数
Width int // 表格总宽度(磅)
ColWidths []int // 各列宽度(磅),如果为空则平均分配
Data [][]string // 初始数据
Emphases [][]int //单元格的样式 1斜体 2粗体
}
TableConfig 表格配置
type TableGrid ¶
type TableGrid struct {
XMLName xml.Name `xml:"w:tblGrid"`
Cols []TableGridCol `xml:"w:gridCol"`
}
TableGrid 表格网格
type TableGridCol ¶
TableGridCol 表格网格列
type TableIndentation ¶
type TableIndentation struct {
XMLName xml.Name `xml:"w:tblInd"`
W string `xml:"w:w,attr"`
Type string `xml:"w:type,attr"`
}
TableIndentation 表格缩进
type TableLayoutConfig ¶
type TableLayoutConfig struct {
Alignment TableAlignment // 表格对齐方式
TextWrap TableTextWrap // 文字环绕类型
Position TablePosition // 定位类型
Positioning *TablePositioning // 定位详细配置(仅在Position为Floating时有效)
}
TableLayoutConfig 表格布局配置
type TableLayoutType ¶
type TableLayoutType struct {
XMLName xml.Name `xml:"w:tblLayout"`
Type string `xml:"w:type,attr"` // fixed, autofit
}
TableLayoutType 表格布局类型
type TableLook ¶
type TableLook struct {
XMLName xml.Name `xml:"w:tblLook"`
Val string `xml:"w:val,attr"`
FirstRow string `xml:"w:firstRow,attr,omitempty"`
LastRow string `xml:"w:lastRow,attr,omitempty"`
FirstCol string `xml:"w:firstColumn,attr,omitempty"`
LastCol string `xml:"w:lastColumn,attr,omitempty"`
NoHBand string `xml:"w:noHBand,attr,omitempty"`
NoVBand string `xml:"w:noVBand,attr,omitempty"`
}
TableLook 表格外观
type TablePageBreakConfig ¶
type TablePageBreakConfig struct {
KeepWithNext bool // 与下一段落保持在一起
KeepLines bool // 保持行在一起
PageBreakBefore bool // 段落前分页
WidowControl bool // 孤行控制
}
TablePageBreakConfig 表格分页配置
type TablePosition ¶
type TablePosition string
TablePosition 表格定位类型
const ( // PositionInline 行内定位(默认) PositionInline TablePosition = "inline" // PositionFloating 浮动定位 PositionFloating TablePosition = "floating" )
type TablePositioning ¶
type TablePositioning struct {
XMLName xml.Name `xml:"w:tblpPr"`
LeftFromText string `xml:"w:leftFromText,attr,omitempty"` // 距离左侧文字的距离
RightFromText string `xml:"w:rightFromText,attr,omitempty"` // 距离右侧文字的距离
TopFromText string `xml:"w:topFromText,attr,omitempty"` // 距离上方文字的距离
BottomFromText string `xml:"w:bottomFromText,attr,omitempty"` // 距离下方文字的距离
VertAnchor string `xml:"w:vertAnchor,attr,omitempty"` // 垂直锚点
HorzAnchor string `xml:"w:horzAnchor,attr,omitempty"` // 水平锚点
TblpXSpec string `xml:"w:tblpXSpec,attr,omitempty"` // 水平对齐规格
TblpYSpec string `xml:"w:tblpYSpec,attr,omitempty"` // 垂直对齐规格
TblpX string `xml:"w:tblpX,attr,omitempty"` // X坐标
TblpY string `xml:"w:tblpY,attr,omitempty"` // Y坐标
}
TablePositioning 表格定位配置
type TableProperties ¶
type TableProperties struct {
XMLName xml.Name `xml:"w:tblPr"`
TableW *TableWidth `xml:"w:tblW,omitempty"`
TableJc *TableJc `xml:"w:jc,omitempty"`
TableLook *TableLook `xml:"w:tblLook,omitempty"`
TableStyle *TableStyle `xml:"w:tblStyle,omitempty"` // 表格样式
TableBorders *TableBorders `xml:"w:tblBorders,omitempty"` // 表格边框
Shd *TableShading `xml:"w:shd,omitempty"` // 表格底纹/背景
TableCellMar *TableCellMargins `xml:"w:tblCellMar,omitempty"` // 表格单元格边距
TableLayout *TableLayoutType `xml:"w:tblLayout,omitempty"` // 表格布局类型
TableInd *TableIndentation `xml:"w:tblInd,omitempty"` // 表格缩进
}
TableProperties 表格属性
type TableRow ¶
type TableRow struct {
XMLName xml.Name `xml:"w:tr"`
Properties *TableRowProperties `xml:"w:trPr,omitempty"`
Cells []TableCell `xml:"w:tc"`
}
TableRow 表格行
type TableRowH ¶
type TableRowH struct {
XMLName xml.Name `xml:"w:trHeight"`
Val string `xml:"w:val,attr,omitempty"`
HRule string `xml:"w:hRule,attr,omitempty"`
}
TableRowH 表格行高
type TableRowProperties ¶
type TableRowProperties struct {
XMLName xml.Name `xml:"w:trPr"`
TableRowH *TableRowH `xml:"w:trHeight,omitempty"`
CantSplit *CantSplit `xml:"w:cantSplit,omitempty"` // 禁止跨页分割
TblHeader *TblHeader `xml:"w:tblHeader,omitempty"` // 标题行重复
}
TableRowProperties 表格行属性
func (*TableRowProperties) SetCantSplit ¶
func (trp *TableRowProperties) SetCantSplit(cantSplit bool)
扩展现有的TableRowProperties结构
func (*TableRowProperties) SetTblHeader ¶
func (trp *TableRowProperties) SetTblHeader(isHeader bool)
type TableRowPropertiesExtended ¶
type TableRowPropertiesExtended struct {
XMLName xml.Name `xml:"w:trPr"`
TableRowH *TableRowH `xml:"w:trHeight,omitempty"`
CantSplit *CantSplit `xml:"w:cantSplit,omitempty"`
TblHeader *TblHeader `xml:"w:tblHeader,omitempty"`
KeepNext *KeepNext `xml:"w:keepNext,omitempty"`
KeepLines *KeepLines `xml:"w:keepLines,omitempty"`
}
扩展TableRowProperties以支持分页控制
type TableShading ¶
type TableShading struct {
XMLName xml.Name `xml:"w:shd"`
Val string `xml:"w:val,attr"` // 底纹样式
Color string `xml:"w:color,attr,omitempty"` // 前景色
Fill string `xml:"w:fill,attr,omitempty"` // 背景色
ThemeFill string `xml:"w:themeFill,attr,omitempty"` // 主题填充色
}
TableShading 表格底纹/背景
type TableStyle ¶
TableStyle 表格样式引用
type TableStyleConfig ¶
type TableStyleConfig struct {
Template TableStyleTemplate // 样式模板
StyleID string // 自定义样式ID
FirstRowHeader bool // 首行作为标题
LastRowTotal bool // 最后一行作为总计
FirstColumnHeader bool // 首列作为标题
LastColumnTotal bool // 最后一列作为总计
BandedRows bool // 交替行颜色
BandedColumns bool // 交替列颜色
}
TableStyleConfig 表格样式配置
type TableStyleTemplate ¶
type TableStyleTemplate string
TableStyleTemplate 表格样式模板
const ( TableStyleTemplateNormal TableStyleTemplate = "TableNormal" // 普通表格 TableStyleTemplateGrid TableStyleTemplate = "TableGrid" // 网格表格 TableStyleTemplateList TableStyleTemplate = "TableList" // 列表表格 TableStyleTemplateColorful1 TableStyleTemplate = "TableColorful1" // 彩色表格1 TableStyleTemplateColorful2 TableStyleTemplate = "TableColorful2" // 彩色表格2 TableStyleTemplateColorful3 TableStyleTemplate = "TableColorful3" // 彩色表格3 TableStyleTemplateColumns1 TableStyleTemplate = "TableColumns1" // 列样式1 TableStyleTemplateColumns2 TableStyleTemplate = "TableColumns2" // 列样式2 TableStyleTemplateColumns3 TableStyleTemplate = "TableColumns3" // 列样式3 TableStyleTemplateRows1 TableStyleTemplate = "TableRows1" // 行样式1 TableStyleTemplateRows2 TableStyleTemplate = "TableRows2" // 行样式2 TableStyleTemplateRows3 TableStyleTemplate = "TableRows3" // 行样式3 TableStyleTemplatePlain1 TableStyleTemplate = "TablePlain1" // 简洁表格1 TableStyleTemplatePlain2 TableStyleTemplate = "TablePlain2" // 简洁表格2 TableStyleTemplatePlain3 TableStyleTemplate = "TablePlain3" // 简洁表格3 )
type TableTextWrap ¶
type TableTextWrap string
TableTextWrap 表格文字环绕类型
const ( // TextWrapNone 无环绕(默认) TextWrapNone TableTextWrap = "none" // TextWrapAround 环绕表格 TextWrapAround TableTextWrap = "around" )
type TableWidth ¶
type TableWidth struct {
XMLName xml.Name `xml:"w:tblW"`
W string `xml:"w:w,attr"`
Type string `xml:"w:type,attr"`
}
TableWidth 表格宽度
type TblHeader ¶
type TblHeader struct {
XMLName xml.Name `xml:"w:tblHeader"`
Val string `xml:"w:val,attr,omitempty"`
}
TblHeader 表格标题行
type Template ¶ added in v1.3.3
type Template struct {
Name string // 模板名称
Content string // 模板内容
BaseDoc *Document // 基础文档
Variables map[string]string // 模板变量
Blocks []*TemplateBlock // 模板块列表
Parent *Template // 父模板(用于继承)
DefinedBlocks map[string]*TemplateBlock // 定义的块映射
}
Template 模板结构
type TemplateAnalysis ¶ added in v1.3.7
type TemplateAnalysis struct {
TemplateName string // 模板名称
Variables map[string]bool // 变量列表
Lists map[string]bool // 列表变量
Conditions map[string]bool // 条件变量
Tables []*TableAnalysis // 表格分析
}
TemplateAnalysis 模板分析结果
func (*TemplateAnalysis) GetRequiredData ¶ added in v1.3.7
func (analysis *TemplateAnalysis) GetRequiredData() *TemplateData
GetRequiredData 获取模板所需的数据结构
type TemplateBlock ¶ added in v1.3.3
type TemplateBlock struct {
Type string // 块类型:variable, if, each, inherit, block, image
Name string // 块名称(block类型使用)
Content string // 块内容
Condition string // 条件(if块使用)
Variable string // 变量名(each块使用)
Children []*TemplateBlock // 子块
Data map[string]interface{} // 块数据
DefaultContent string // 默认内容(用于可选重写)
IsOverridden bool // 是否被重写
}
TemplateBlock 模板块
type TemplateData ¶ added in v1.3.3
type TemplateData struct {
Variables map[string]interface{} // 变量数据
Lists map[string][]interface{} // 列表数据
Conditions map[string]bool // 条件数据
Images map[string]*TemplateImageData // 图片数据
}
TemplateData 模板数据
func NewTemplateData ¶ added in v1.3.3
func NewTemplateData() *TemplateData
NewTemplateData 创建新的模板数据
func (*TemplateData) FromStruct ¶ added in v1.3.3
func (td *TemplateData) FromStruct(data interface{}) error
FromStruct 从结构体生成模板数据
func (*TemplateData) GetCondition ¶ added in v1.3.3
func (td *TemplateData) GetCondition(name string) (bool, bool)
GetCondition 获取条件
func (*TemplateData) GetImage ¶ added in v1.3.9
func (td *TemplateData) GetImage(name string) (*TemplateImageData, bool)
GetImage 获取图片数据
func (*TemplateData) GetList ¶ added in v1.3.3
func (td *TemplateData) GetList(name string) ([]interface{}, bool)
GetList 获取列表
func (*TemplateData) GetVariable ¶ added in v1.3.3
func (td *TemplateData) GetVariable(name string) (interface{}, bool)
GetVariable 获取变量
func (*TemplateData) Merge ¶ added in v1.3.3
func (td *TemplateData) Merge(other *TemplateData)
Merge 合并模板数据
func (*TemplateData) SetCondition ¶ added in v1.3.3
func (td *TemplateData) SetCondition(name string, value bool)
SetCondition 设置条件
func (*TemplateData) SetImage ¶ added in v1.3.9
func (td *TemplateData) SetImage(name, filePath string, config *ImageConfig)
SetImage 设置图片数据(通过文件路径)
func (*TemplateData) SetImageFromData ¶ added in v1.3.9
func (td *TemplateData) SetImageFromData(name string, data []byte, config *ImageConfig)
SetImageFromData 设置图片数据(通过二进制数据)
func (*TemplateData) SetImageWithDetails ¶ added in v1.3.9
func (td *TemplateData) SetImageWithDetails(name, filePath string, data []byte, config *ImageConfig, altText, title string)
SetImageWithDetails 设置图片数据(完整配置)
func (*TemplateData) SetList ¶ added in v1.3.3
func (td *TemplateData) SetList(name string, list []interface{})
SetList 设置列表
func (*TemplateData) SetVariable ¶ added in v1.3.3
func (td *TemplateData) SetVariable(name string, value interface{})
SetVariable 设置变量
func (*TemplateData) SetVariables ¶ added in v1.3.3
func (td *TemplateData) SetVariables(variables map[string]interface{})
SetVariables 批量设置变量
type TemplateEngine ¶ added in v1.3.3
type TemplateEngine struct {
// contains filtered or unexported fields
}
TemplateEngine 模板引擎
func NewTemplateEngine ¶ added in v1.3.3
func NewTemplateEngine() *TemplateEngine
NewTemplateEngine 创建新的模板引擎
func (*TemplateEngine) ClearCache ¶ added in v1.3.3
func (te *TemplateEngine) ClearCache()
ClearCache 清空模板缓存
func (*TemplateEngine) GetTemplate ¶ added in v1.3.3
func (te *TemplateEngine) GetTemplate(name string) (*Template, error)
GetTemplate 获取缓存的模板
func (*TemplateEngine) LoadTemplate ¶ added in v1.3.3
func (te *TemplateEngine) LoadTemplate(name, content string) (*Template, error)
LoadTemplate 从字符串加载模板
func (*TemplateEngine) LoadTemplateFromDocument ¶ added in v1.3.3
func (te *TemplateEngine) LoadTemplateFromDocument(name string, doc *Document) (*Template, error)
LoadTemplateFromDocument 从现有文档创建模板
func (*TemplateEngine) RemoveTemplate ¶ added in v1.3.3
func (te *TemplateEngine) RemoveTemplate(name string)
RemoveTemplate 移除指定模板
func (*TemplateEngine) RenderTemplateToDocument ¶ added in v1.3.4
func (te *TemplateEngine) RenderTemplateToDocument(templateName string, data *TemplateData) (*Document, error)
RenderTemplateToDocument 渲染模板到新文档(新的主要方法)
func (*TemplateEngine) RenderToDocument ¶ added in v1.3.3
func (te *TemplateEngine) RenderToDocument(templateName string, data *TemplateData) (*Document, error)
RenderToDocument 渲染模板到新文档
func (*TemplateEngine) SetBasePath ¶ added in v1.3.3
func (te *TemplateEngine) SetBasePath(path string)
SetBasePath 设置模板基础路径
func (*TemplateEngine) ValidateTemplate ¶ added in v1.3.3
func (te *TemplateEngine) ValidateTemplate(template *Template) error
ValidateTemplate 验证模板语法
type TemplateImageData ¶ added in v1.3.9
type TemplateImageData struct {
FilePath string // 图片文件路径
Data []byte // 图片二进制数据(优先使用)
Config *ImageConfig // 图片配置(大小、位置、样式等)
AltText string // 图片替代文字
Title string // 图片标题
}
TemplateImageData 模板图片数据
type TemplateLogger ¶ added in v1.3.7
type TemplateLogger struct {
// contains filtered or unexported fields
}
TemplateLogger 模板日志记录器
type TemplateRenderer ¶ added in v1.3.7
type TemplateRenderer struct {
// contains filtered or unexported fields
}
TemplateRenderer 专门负责模板渲染的引擎
func NewTemplateRenderer ¶ added in v1.3.7
func NewTemplateRenderer() *TemplateRenderer
NewTemplateRenderer 创建新的模板渲染器
func (*TemplateRenderer) AnalyzeTemplate ¶ added in v1.3.7
func (tr *TemplateRenderer) AnalyzeTemplate(templateName string) (*TemplateAnalysis, error)
AnalyzeTemplate 分析模板结构
func (*TemplateRenderer) LoadTemplateFromFile ¶ added in v1.3.7
func (tr *TemplateRenderer) LoadTemplateFromFile(name, filePath string) (*Template, error)
LoadTemplateFromFile 从文件加载模板
func (*TemplateRenderer) RenderTemplate ¶ added in v1.3.7
func (tr *TemplateRenderer) RenderTemplate(templateName string, data *TemplateData) (*Document, error)
RenderTemplate 渲染模板到新文档
func (*TemplateRenderer) SetLogging ¶ added in v1.3.7
func (tr *TemplateRenderer) SetLogging(enabled bool)
SetLogging 设置是否启用日志记录
type Text ¶
type Text struct {
XMLName xml.Name `xml:"w:t"`
Space string `xml:"xml:space,attr,omitempty"`
Content string `xml:",chardata"`
}
Text 文本内容
type TextDirection ¶
type TextDirection struct {
XMLName xml.Name `xml:"w:textDirection"`
Val string `xml:"w:val,attr"`
}
TextDirection 文字方向
type TextFormat ¶
type TextFormat struct {
Bold bool // 是否粗体
Italic bool // 是否斜体
FontSize int // 字体大小(磅)
FontColor string // 字体颜色(十六进制,如 "FF0000" 表示红色)
FontFamily string // 字体名称(首选字段)
FontName string // 字体名称别名(为兼容早期文档示例/README 中使用的 FontName)
Underline bool // 是否下划线
Strike bool // 删除线
Highlight string //高亮颜色
}
TextFormat 文本格式配置
type ValidationError ¶
ValidationError 验证错误
func NewValidationError ¶
func NewValidationError(field, value, message string) *ValidationError
NewValidationError 创建新的验证错误
type VerticalPosition ¶ added in v1.3.3
type VerticalPosition struct {
XMLName xml.Name `xml:"wp:positionV"`
RelativeFrom string `xml:"relativeFrom,attr"`
Align *PosAlign `xml:"wp:align,omitempty"`
PosOffset *PosOffset `xml:"wp:posOffset,omitempty"`
}
VerticalPosition 垂直位置
type WidowControl ¶ added in v1.5.0
type WidowControl struct {
XMLName xml.Name `xml:"w:widowControl"`
Val string `xml:"w:val,attr,omitempty"`
}
WidowControl 孤行控制
type WrapPolygon ¶ added in v1.3.3
type WrapPolygon struct {
XMLName xml.Name `xml:"wp:wrapPolygon"`
Start *PolygonStart `xml:"wp:start"`
LineTo []PolygonLineTo `xml:"wp:lineTo"`
}
WrapPolygon 环绕多边形
type WrapSquare ¶ added in v1.3.3
type WrapSquare struct {
XMLName xml.Name `xml:"wp:wrapSquare"`
WrapText string `xml:"wrapText,attr,omitempty"`
DistT string `xml:"distT,attr,omitempty"`
DistB string `xml:"distB,attr,omitempty"`
DistL string `xml:"distL,attr,omitempty"`
DistR string `xml:"distR,attr,omitempty"`
}
WrapSquare 四周环绕
type WrapThrough ¶ added in v1.3.3
type WrapThrough struct {
XMLName xml.Name `xml:"wp:wrapThrough"`
WrapText string `xml:"wrapText,attr,omitempty"`
DistL string `xml:"distL,attr,omitempty"`
DistR string `xml:"distR,attr,omitempty"`
WrapPolygon *WrapPolygon `xml:"wp:wrapPolygon,omitempty"`
}
WrapThrough 穿透环绕
type WrapTight ¶ added in v1.3.3
type WrapTight struct {
XMLName xml.Name `xml:"wp:wrapTight"`
WrapText string `xml:"wrapText,attr,omitempty"`
DistL string `xml:"distL,attr,omitempty"`
DistR string `xml:"distR,attr,omitempty"`
WrapPolygon *WrapPolygon `xml:"wp:wrapPolygon,omitempty"`
}
WrapTight 紧密环绕
type WrapTopAndBottom ¶ added in v1.3.3
type WrapTopAndBottom struct {
XMLName xml.Name `xml:"wp:wrapTopAndBottom"`
DistT string `xml:"distT,attr,omitempty"`
DistB string `xml:"distB,attr,omitempty"`
EffectExtent *EffectExtent `xml:"wp:effectExtent,omitempty"`
}
WrapTopAndBottom 上下环绕