10 API参考 - ZeroHawkeye/wordZero GitHub Wiki
WordZero API 参考文档
本文档提供 WordZero 库的完整 API 参考,包括所有公共接口、方法、结构体和常量的详细说明。
📋 目录
核心文档操作
Document 结构体
Document
是 WordZero 的核心结构体,代表一个 Word 文档。
创建文档
// New 创建一个新的空白文档
func New() *Document
// Open 打开现有的 Word 文档
func Open(filename string) (*Document, error)
保存文档
// Save 保存文档到指定文件
func (d *Document) Save(filename string) error
参数:
filename
: 保存的文件路径,必须以.docx
结尾
返回值:
error
: 保存失败时返回错误信息
示例:
doc := document.New()
err := doc.Save("example.docx")
if err != nil {
log.Fatal(err)
}
获取样式管理器
// GetStyleManager 获取文档的样式管理器
func (d *Document) GetStyleManager() *style.StyleManager
段落和文本
添加段落
// AddParagraph 添加普通段落
func (d *Document) AddParagraph(text string) *Paragraph
// AddFormattedParagraph 添加格式化段落
func (d *Document) AddFormattedParagraph(text string, format *TextFormat) *Paragraph
// AddHeadingParagraph 添加标题段落
func (d *Document) AddHeadingParagraph(text string, level int) *Paragraph
// AddHeadingParagraphWithBookmark 添加带书签的标题段落
func (d *Document) AddHeadingParagraphWithBookmark(text string, level int, bookmarkName string) *Paragraph
参数:
text
: 段落文本内容format
: 文本格式设置(可选)level
: 标题级别(1-9)bookmarkName
: 书签名称
Paragraph 方法
// SetStyle 设置段落样式
func (p *Paragraph) SetStyle(styleID string)
// SetAlignment 设置段落对齐方式
func (p *Paragraph) SetAlignment(alignment AlignmentType)
// AddRun 添加文本运行
func (p *Paragraph) AddRun(text string) *Run
// AddFormattedRun 添加格式化文本运行
func (p *Paragraph) AddFormattedRun(text string, format *TextFormat) *Run
// SetSpacing 设置段落间距
func (p *Paragraph) SetSpacing(before, after, line float64)
// SetIndentation 设置段落缩进
func (p *Paragraph) SetIndentation(firstLine, left, right float64)
TextFormat 结构体
type TextFormat struct {
FontFamily string // 字体名称
FontSize float64 // 字体大小(磅)
Bold bool // 是否粗体
Italic bool // 是否斜体
Underline bool // 是否下划线
Strike bool // 是否删除线
Color string // 文字颜色(十六进制)
Highlight string // 高亮颜色
Superscript bool // 是否上标
Subscript bool // 是否下标
}
样式系统
StyleManager 方法
// GetStyle 获取指定样式
func (sm *StyleManager) GetStyle(styleID string) *Style
// StyleExists 检查样式是否存在
func (sm *StyleManager) StyleExists(styleID string) bool
// GetAllStyles 获取所有样式
func (sm *StyleManager) GetAllStyles() []*Style
// GetHeadingStyles 获取所有标题样式
func (sm *StyleManager) GetHeadingStyles() []*Style
// CreateCustomStyle 创建自定义样式
func (sm *StyleManager) CreateCustomStyle(config *CustomStyleConfig) (*Style, error)
// GetStyleWithInheritance 获取带继承的样式
func (sm *StyleManager) GetStyleWithInheritance(styleID string) *Style
预定义样式常量
const (
StyleNormal = "Normal" // 普通文本
StyleHeading1 = "Heading1" // 标题 1
StyleHeading2 = "Heading2" // 标题 2
StyleHeading3 = "Heading3" // 标题 3
StyleHeading4 = "Heading4" // 标题 4
StyleHeading5 = "Heading5" // 标题 5
StyleHeading6 = "Heading6" // 标题 6
StyleHeading7 = "Heading7" // 标题 7
StyleHeading8 = "Heading8" // 标题 8
StyleHeading9 = "Heading9" // 标题 9
StyleTitle = "Title" // 文档标题
StyleSubtitle = "Subtitle" // 副标题
StyleEmphasis = "Emphasis" // 强调
StyleStrong = "Strong" // 加粗
StyleCodeChar = "CodeChar" // 代码字符
StyleQuote = "Quote" // 引用
StyleListParagraph = "ListParagraph" // 列表段落
StyleCodeBlock = "CodeBlock" // 代码块
)
表格操作
创建表格
// CreateTable 创建表格(不添加到文档)
func (d *Document) CreateTable(config *TableConfig) *Table
// AddTable 创建并添加表格到文档
func (d *Document) AddTable(config *TableConfig) *Table
TableConfig 结构体
type TableConfig struct {
Rows int // 行数
Cols int // 列数
Width float64 // 表格宽度(磅)
ColumnWidths []float64 // 列宽数组
Headers []string // 表头文本
Data [][]string // 表格数据
Style *TableStyleConfig // 表格样式
}
Table 方法
// SetCellText 设置单元格文本
func (t *Table) SetCellText(row, col int, text string) error
// GetCellText 获取单元格文本
func (t *Table) GetCellText(row, col int) (string, error)
// SetCellFormat 设置单元格格式
func (t *Table) SetCellFormat(row, col int, format *TextFormat) error
// AddRow 添加行
func (t *Table) AddRow() error
// AddColumn 添加列
func (t *Table) AddColumn() error
// DeleteRow 删除行
func (t *Table) DeleteRow(rowIndex int) error
// DeleteColumn 删除列
func (t *Table) DeleteColumn(colIndex int) error
// ApplyTableStyle 应用表格样式
func (t *Table) ApplyTableStyle(config *TableStyleConfig) error
// SetBorders 设置表格边框
func (t *Table) SetBorders(borders *TableBorders) error
页面设置
页面设置方法
// SetPageSettings 设置页面设置
func (d *Document) SetPageSettings(settings *PageSettings) error
// GetPageSettings 获取页面设置
func (d *Document) GetPageSettings() *PageSettings
// SetPageSize 设置页面尺寸
func (d *Document) SetPageSize(size PageSize) error
// SetCustomPageSize 设置自定义页面尺寸
func (d *Document) SetCustomPageSize(width, height float64) error
// SetPageOrientation 设置页面方向
func (d *Document) SetPageOrientation(orientation PageOrientation) error
// SetPageMargins 设置页面边距
func (d *Document) SetPageMargins(top, right, bottom, left float64) error
页面常量
// 页面尺寸
const (
PageSizeA4 PageSize = "A4" // A4 (210mm x 297mm)
PageSizeLetter PageSize = "Letter" // Letter (8.5" x 11")
PageSizeLegal PageSize = "Legal" // Legal (8.5" x 14")
PageSizeA3 PageSize = "A3" // A3 (297mm x 420mm)
PageSizeA5 PageSize = "A5" // A5 (148mm x 210mm)
PageSizeCustom PageSize = "Custom" // 自定义尺寸
)
// 页面方向
const (
OrientationPortrait PageOrientation = "portrait" // 纵向
OrientationLandscape PageOrientation = "landscape" // 横向
)
页眉页脚
// AddHeader 添加页眉
func (d *Document) AddHeader(headerType HeaderFooterType, text string) error
// AddFooter 添加页脚
func (d *Document) AddFooter(footerType HeaderFooterType, text string) error
// AddHeaderWithPageNumber 添加带页码的页眉
func (d *Document) AddHeaderWithPageNumber(headerType HeaderFooterType, text string, showPageNum bool) error
// AddFooterWithPageNumber 添加带页码的页脚
func (d *Document) AddFooterWithPageNumber(footerType HeaderFooterType, text string, showPageNum bool) error
// SetDifferentFirstPage 设置首页不同
func (d *Document) SetDifferentFirstPage(different bool)
图片操作
图片基础操作
// AddImageFromFile 从文件添加图片到文档
func (d *Document) AddImageFromFile(filePath string, config *ImageConfig) (*ImageInfo, error)
// AddImageFromData 从数据添加图片到文档
func (d *Document) AddImageFromData(imageData []byte, fileName string, format ImageFormat, width, height int, config *ImageConfig) (*ImageInfo, error)
参数:
filePath
: 图片文件路径imageData
: 图片字节数据fileName
: 图片文件名format
: 图片格式(PNG、JPEG、GIF)width/height
: 原始图片尺寸(像素)config
: 图片配置
返回值:
*ImageInfo
: 图片信息对象error
: 操作失败时返回错误
图片属性控制
// ResizeImage 调整图片大小
func (d *Document) ResizeImage(imageInfo *ImageInfo, size *ImageSize) error
// SetImagePosition 设置图片位置
func (d *Document) SetImagePosition(imageInfo *ImageInfo, position ImagePosition, offsetX, offsetY float64) error
// SetImageWrapText 设置图片文字环绕
func (d *Document) SetImageWrapText(imageInfo *ImageInfo, wrapText ImageWrapText) error
// SetImageAltText 设置图片替代文字
func (d *Document) SetImageAltText(imageInfo *ImageInfo, altText string) error
// SetImageTitle 设置图片标题
func (d *Document) SetImageTitle(imageInfo *ImageInfo, title string) error
// SetImageAlignment 设置图片对齐方式
func (d *Document) SetImageAlignment(imageInfo *ImageInfo, alignment AlignmentType) error
ImageConfig 结构体
type ImageConfig struct {
Size *ImageSize // 图片大小
Position ImagePosition // 图片位置
Alignment AlignmentType // 图片对齐方式(用于嵌入式图片)
WrapText ImageWrapText // 文字环绕
AltText string // 图片描述(替代文字)
Title string // 图片标题
OffsetX float64 // 水平偏移(毫米)
OffsetY float64 // 垂直偏移(毫米)
}
type ImageSize struct {
Width float64 // 宽度(毫米)
Height float64 // 高度(毫米)
KeepAspectRatio bool // 是否保持长宽比
}
type ImageInfo struct {
ID string // 图片ID
RelationID string // 关系ID
Format ImageFormat // 图片格式
Width int // 原始宽度(像素)
Height int // 原始高度(像素)
Data []byte // 图片数据
Config *ImageConfig // 图片配置
}
图片使用示例
// 基础图片插入
doc := document.New()
// 从文件添加图片
imageInfo, err := doc.AddImageFromFile("path/to/image.jpg", &document.ImageConfig{
Size: &document.ImageSize{
Width: 80.0, // 宽度80毫米
Height: 60.0, // 高度60毫米
},
AltText: "示例图片",
Title: "这是一张示例图片",
})
// 添加浮动图片
floatImageInfo, err := doc.AddImageFromFile("chart.png", &document.ImageConfig{
Size: &document.ImageSize{
Width: 60.0,
Height: 45.0,
},
Position: document.ImagePositionFloatLeft,
WrapText: document.ImageWrapSquare,
AltText: "数据图表",
OffsetX: 2.0,
})
// 动态调整图片属性
err = doc.SetImageAltText(imageInfo, "更新后的替代文字")
err = doc.SetImagePosition(floatImageInfo, document.ImagePositionFloatRight, 3.0, 1.0)
高级功能
目录生成
// GenerateTOC 生成目录
func (d *Document) GenerateTOC(config *TOCConfig) error
// UpdateTOC 更新目录
func (d *Document) UpdateTOC() error
// AddHeadingWithBookmark 添加带书签的标题
func (d *Document) AddHeadingWithBookmark(text string, level int, bookmarkName string) *Paragraph
// AutoGenerateTOC 自动生成目录
func (d *Document) AutoGenerateTOC(config *TOCConfig) error
// GetHeadingCount 获取标题统计
func (d *Document) GetHeadingCount() map[int]int
// ListHeadings 列出所有标题
func (d *Document) ListHeadings() []TOCEntry
脚注和尾注
// AddFootnote 添加脚注
func (d *Document) AddFootnote(text string, footnoteText string) error
// AddEndnote 添加尾注
func (d *Document) AddEndnote(text string, endnoteText string) error
// AddFootnoteToRun 为文本运行添加脚注
func (d *Document) AddFootnoteToRun(run *Run, footnoteText string) error
// SetFootnoteConfig 设置脚注配置
func (d *Document) SetFootnoteConfig(config *FootnoteConfig) error
// GetFootnoteCount 获取脚注数量
func (d *Document) GetFootnoteCount() int
// GetEndnoteCount 获取尾注数量
func (d *Document) GetEndnoteCount() int
列表和编号
// AddListItem 添加列表项
func (d *Document) AddListItem(text string, config *ListConfig) *Paragraph
// AddBulletList 添加项目符号列表
func (d *Document) AddBulletList(text string, level int, bulletType BulletType) *Paragraph
// AddNumberedList 添加编号列表
func (d *Document) AddNumberedList(text string, level int, numType ListType) *Paragraph
// CreateMultiLevelList 创建多级列表
func (d *Document) CreateMultiLevelList(items []ListItem) error
// RestartNumbering 重新开始编号
func (d *Document) RestartNumbering(numID string)
文档属性
// SetDocumentProperties 设置文档属性
func (d *Document) SetDocumentProperties(properties *DocumentProperties) error
// GetDocumentProperties 获取文档属性
func (d *Document) GetDocumentProperties() (*DocumentProperties, error)
// SetTitle 设置文档标题
func (d *Document) SetTitle(title string) error
// SetAuthor 设置文档作者
func (d *Document) SetAuthor(author string) error
// SetSubject 设置文档主题
func (d *Document) SetSubject(subject string) error
// SetKeywords 设置文档关键词
func (d *Document) SetKeywords(keywords string) error
// UpdateStatistics 更新文档统计信息
func (d *Document) UpdateStatistics() error
数据结构
对齐类型
type AlignmentType string
const (
AlignLeft AlignmentType = "left" // 左对齐
AlignCenter AlignmentType = "center" // 居中对齐
AlignRight AlignmentType = "right" // 右对齐
AlignJustify AlignmentType = "justify" // 两端对齐
)
边框样式
type BorderStyle string
const (
BorderStyleNone BorderStyle = "none" // 无边框
BorderStyleSingle BorderStyle = "single" // 单线
BorderStyleThick BorderStyle = "thick" // 粗线
BorderStyleDouble BorderStyle = "double" // 双线
BorderStyleDotted BorderStyle = "dotted" // 点线
BorderStyleDashed BorderStyle = "dashed" // 虚线
BorderStyleDotDash BorderStyle = "dotDash" // 点划线
BorderStyleWave BorderStyle = "wave" // 波浪线
)
列表类型
type ListType string
const (
ListTypeDecimal ListType = "decimal" // 阿拉伯数字
ListTypeLowerLetter ListType = "lowerLetter" // 小写字母
ListTypeUpperLetter ListType = "upperLetter" // 大写字母
ListTypeLowerRoman ListType = "lowerRoman" // 小写罗马数字
ListTypeUpperRoman ListType = "upperRoman" // 大写罗马数字
)
type BulletType string
const (
BulletTypeDisc BulletType = "disc" // 实心圆点
BulletTypeCircle BulletType = "circle" // 空心圆点
BulletTypeSquare BulletType = "square" // 方块
BulletTypeDash BulletType = "dash" // 短横线
)
图片类型
// 图片格式
type ImageFormat string
const (
ImageFormatJPEG ImageFormat = "jpeg" // JPEG格式
ImageFormatPNG ImageFormat = "png" // PNG格式
ImageFormatGIF ImageFormat = "gif" // GIF格式
)
// 图片位置
type ImagePosition string
const (
ImagePositionInline ImagePosition = "inline" // 嵌入式(默认)
ImagePositionFloatLeft ImagePosition = "floatLeft" // 左浮动
ImagePositionFloatRight ImagePosition = "floatRight" // 右浮动
)
// 文字环绕
type ImageWrapText string
const (
ImageWrapNone ImageWrapText = "none" // 无环绕
ImageWrapSquare ImageWrapText = "square" // 四周环绕
ImageWrapTight ImageWrapText = "tight" // 紧密环绕
ImageWrapTopAndBottom ImageWrapText = "topAndBottom" // 上下环绕
)
错误处理
常见错误
var (
ErrInvalidPageSettings = errors.New("invalid page settings")
ErrInvalidTableIndex = errors.New("invalid table index")
ErrInvalidCellIndex = errors.New("invalid cell index")
ErrStyleNotFound = errors.New("style not found")
ErrInvalidFormat = errors.New("invalid format")
)
错误处理最佳实践
// 总是检查错误
doc := document.New()
err := doc.Save("example.docx")
if err != nil {
log.Printf("保存文档失败: %v", err)
return
}
// 使用类型断言检查特定错误
if errors.Is(err, document.ErrInvalidPageSettings) {
// 处理页面设置错误
}
单位转换
WordZero 内部使用 Twips(1/20 磅)作为基本单位,提供以下转换函数:
// 磅转换为 Twips
func PointsToTwips(points float64) int
// Twips 转换为磅
func TwipsToPoints(twips int) float64
// 英寸转换为 Twips
func InchesToTwips(inches float64) int
// 厘米转换为 Twips
func CentimetersToTwips(cm float64) int
// 毫米转换为 Twips
func MillimetersToTwips(mm float64) int
性能注意事项
- 批量操作: 对于大量内容,建议批量添加而不是逐个添加
- 样式重用: 重复使用预定义样式而不是创建多个相似的自定义样式
- 内存管理: 处理大文档时注意内存使用,及时释放不需要的引用
- 文件大小: 避免添加过多的空段落或不必要的格式
版本兼容性
- 支持 Go 1.19+
- 生成的文档兼容 Microsoft Word 2010+
- 支持 Office Open XML (OOXML) 格式
- 兼容 WPS Office
更多详细信息和示例,请参考 示例项目 和 examples 目录。