document

package
v1.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 26, 2025 License: MIT Imports: 20 Imported by: 0

README

Document 包 API 文档

本文档记录了 pkg/document 包中所有可用的公开方法和功能。

核心类型

Document 文档

文档操作方法

文档创建与加载
文档解析功能重大升级 ✨

Open 方法现在支持完整的文档结构解析,包括:

动态元素解析支持

  • 段落解析 (<w:p>): 完整解析段落内容、属性、运行和格式
  • 表格解析 (<w:tbl>): 支持表格结构、网格、行列、单元格内容
  • 节属性解析 (<w:sectPr>): 页面设置、边距、分栏等属性
  • 扩展性设计: 新的解析架构可轻松添加更多元素类型

解析器特性

  • 流式解析: 使用XML流式解析器,内存效率高,适用于大型文档
  • 结构保持: 完整保留文档元素的原始顺序和层次结构
  • 错误恢复: 智能跳过未知或损坏的元素,确保解析过程稳定
  • 深度解析: 支持嵌套结构(如表格中的段落、段落中的运行等)

解析的内容包括

  • 段落文本内容和所有格式属性(字体、大小、颜色、样式等)
  • 表格完整结构(行列定义、单元格内容、表格属性)
  • 页面设置信息(页面尺寸、方向、边距等)
  • 样式引用和属性继承关系
文档保存与导出
文档内容操作
分页符功能 ✨

WordZero提供多种方式添加分页符(页面分页符):

方法一:文档级分页符

doc := document.New()
doc.AddParagraph("第一页内容")
doc.AddPageBreak()  // 添加分页符
doc.AddParagraph("第二页内容")

方法二:段落内分页符

para := doc.AddParagraph("第一页内容")
para.AddPageBreak()  // 在段落内添加分页符
para.AddFormattedText("第二页内容", nil)

方法三:段前分页

para := doc.AddParagraph("第二章标题")
para.SetPageBreakBefore(true)  // 设置段落前自动分页

分页功能特性

  • 独立分页符: Document.AddPageBreak() 创建独立的分页段落
  • 段落内分页: Paragraph.AddPageBreak() 在当前段落内添加分页符
  • 段前分页: Paragraph.SetPageBreakBefore(true) 设置段落前自动分页
  • 表格分页控制: 支持表格的分页控制设置
标题段落书签功能 ✨

AddHeadingParagraphWithBookmark 方法现在支持为标题段落添加书签:

书签功能特性

  • 自动书签生成: 为标题段落创建唯一的书签标识
  • 灵活命名: 支持自定义书签名称或留空不添加书签
  • 目录兼容: 生成的书签与目录功能完美兼容,支持导航和超链接
  • Word标准: 符合Microsoft Word的书签格式规范

书签生成规则

  • 书签ID自动生成为 bookmark_{元素索引}_{书签名称} 格式
  • 书签开始标记插入在段落之前
  • 书签结束标记插入在段落之后
  • 支持空书签名称以跳过书签创建
样式管理
页面设置 ✨ 新增功能
页眉页脚操作 ✨ 新增功能
目录功能 ✨ 新增功能
脚注与尾注功能 ✨ 新增功能
列表与编号功能 ✨ 新增功能
结构化文档标签 ✨ 新增功能
模板功能 ✨ 新增功能
模板渲染器(推荐使用)✨
模板引擎(底层API)
模板引擎功能特性 ✨

变量替换: 支持 {{变量名}} 语法进行动态内容替换 条件语句: 支持 {{#if 条件}}...{{/if}} 语法进行条件渲染 循环语句: 支持 {{#each 列表}}...{{/each}} 语法进行列表渲染 模板继承: 支持 {{extends "基础模板"}} 语法和 {{#block "块名"}}...{{/block}} 块重写机制,实现真正的模板继承

  • 块定义: 在基础模板中定义可重写的内容块
  • 块重写: 在子模板中选择性重写特定块,未重写的块保持父模板默认内容
  • 多级继承: 支持模板的多层继承关系
  • 完整保留: 未重写的块完整保留父模板的默认内容和格式 循环内条件: 完美支持循环内部的条件表达式,如 {{#each items}}{{#if isActive}}...{{/if}}{{/each}} 数据类型支持: 支持字符串、数字、布尔值、对象等多种数据类型 结构体绑定: 支持从Go结构体自动生成模板数据 模板分析: ✨ 新增功能 自动分析模板结构,提取变量、列表、条件和表格信息
  • 结构分析: 识别模板中使用的所有变量、列表和条件
  • 表格分析: 专门分析表格中的模板语法和循环结构
  • 依赖检查: 检查模板的数据依赖关系
  • 示例数据生成: 根据分析结果自动生成示例数据结构 日志记录: ✨ 新增功能 完善的日志系统,支持模板加载、渲染和分析过程的详细记录 数据验证: ✨ 新增功能 自动验证模板数据的完整性和格式正确性 DOCX模板支持: ✨ 新增功能 直接从现有DOCX文件加载模板 页眉页脚模板支持: ✨ 新增功能 完整支持页眉页脚中的模板变量
  • 变量识别: 自动识别页眉页脚中的 {{变量名}} 语法
  • 变量替换: 渲染时自动替换页眉页脚中的模板变量
  • 条件语句: 支持页眉页脚中的条件渲染
  • 模板分析: AnalyzeTemplate 会自动分析页眉页脚中的变量
模板数据操作
模板继承详细使用说明 ✨ 新增功能

模板继承是WordZero模板引擎的高级功能,允许基于现有模板创建扩展模板,通过块定义和重写机制实现模板的复用和扩展。

基础语法

1. 基础模板块定义

// 定义带有可重写块的基础模板
baseTemplate := `{{companyName}} 报告

{{#block "header"}}
默认标题内容
日期:{{reportDate}}
{{/block}}

{{#block "summary"}}
默认摘要内容
{{/block}}

{{#block "main_content"}}
默认主要内容
{{/block}}

{{#block "footer"}}
报告人:{{reporterName}}
{{/block}}`

engine.LoadTemplate("base_report", baseTemplate)

2. 子模板继承和块重写

// 创建继承基础模板的子模板
childTemplate := `{{extends "base_report"}}

{{#block "summary"}}
销售业绩摘要
本月销售目标已达成 {{achievementRate}}%
{{/block}}

{{#block "main_content"}}
详细销售数据:
- 总销售额:{{totalSales}}
- 新增客户:{{newCustomers}}
- 成交订单:{{orders}}
{{/block}}`

engine.LoadTemplate("sales_report", childTemplate)
继承特性

块重写策略

  • 重写的块完全替换父模板中的对应块
  • 未重写的块保持父模板的默认内容
  • 支持选择性重写,灵活性极高

多级继承

// 第一级:基础模板
baseTemplate := `{{#block "document"}}基础文档{{/block}}`

// 第二级:业务模板
businessTemplate := `{{extends "base"}}
{{#block "document"}}
{{#block "business_header"}}业务标题{{/block}}
{{#block "business_content"}}业务内容{{/block}}
{{/block}}`

// 第三级:具体业务模板
salesTemplate := `{{extends "business"}}
{{#block "business_header"}}销售报告{{/block}}
{{#block "business_content"}}销售数据分析{{/block}}`
实际应用示例
func demonstrateTemplateInheritance() {
    engine := document.NewTemplateEngine()
    
    // 基础报告模板
    baseTemplate := `{{companyName}} 工作报告
报告日期:{{reportDate}}

{{#block "summary"}}
默认摘要内容
{{/block}}

{{#block "main_content"}}
默认主要内容
{{/block}}

{{#block "conclusion"}}
默认结论
{{/block}}

{{#block "signature"}}
报告人:{{reporterName}}
部门:{{department}}
{{/block}}`
    
    engine.LoadTemplate("base_report", baseTemplate)
    
    // 销售报告模板(重写部分块)
    salesTemplate := `{{extends "base_report"}}

{{#block "summary"}}
销售业绩摘要
本月销售目标已达成 {{achievementRate}}%
{{/block}}

{{#block "main_content"}}
销售数据分析
- 总销售额:{{totalSales}}
- 新增客户:{{newCustomers}}
- 成交订单:{{orders}}

{{#each channels}}
- {{name}}:{{sales}} ({{percentage}}%)
{{/each}}
{{/block}}`
    
    engine.LoadTemplate("sales_report", salesTemplate)
    
    // 准备数据并渲染
    data := document.NewTemplateData()
    data.SetVariable("companyName", "WordZero科技")
    data.SetVariable("reportDate", "2024年12月01日")
    data.SetVariable("reporterName", "张三")
    data.SetVariable("department", "销售部")
    data.SetVariable("achievementRate", "125")
    data.SetVariable("totalSales", "1,850,000")
    data.SetVariable("newCustomers", "45")
    data.SetVariable("orders", "183")
    
    channels := []interface{}{
        map[string]interface{}{"name": "线上电商", "sales": "742,000", "percentage": "40.1"},
        map[string]interface{}{"name": "直销团队", "sales": "555,000", "percentage": "30.0"},
    }
    data.SetList("channels", channels)
    
    // 渲染并保存(推荐方法)
    doc, _ := engine.RenderTemplateToDocument("sales_report", data)
    doc.Save("sales_report.docx")
}
优势与应用场景

主要优势

  • 代码复用:避免重复定义相同的模板结构
  • 维护性:修改基础模板自动影响所有子模板
  • 灵活性:可选择性重写需要的部分,保留其他默认内容
  • 扩展性:支持多级继承,构建复杂的模板层次结构

典型应用场景

  • 企业报告体系:基础报告模板+各部门专用模板
  • 文档标准化:统一格式的不同类型文档(合同、发票、通知等)
  • 多语言文档:相同结构不同语言的文档模板
  • 品牌一致性:保持企业品牌元素的统一性
图片操作功能 ✨ 新增功能

段落操作方法

段落格式设置
段落格式高级功能 ✨ 新增功能

WordZero现在支持完整的段落格式自定义功能,提供与Microsoft Word相同的高级段落控制选项。

分页控制功能

  • SetKeepWithNext - 确保段落与下一段落保持在同一页,避免标题单独出现在页面底部
  • SetKeepLines - 防止段落被分页拆分,保持段落完整性
  • SetPageBreakBefore - 在段落前强制插入分页符,常用于章节开始

孤行控制

  • SetWidowControl - 防止段落第一行或最后一行单独出现在页面顶部或底部,提升排版质量

大纲级别

  • SetOutlineLevel - 设置段落的大纲级别(0-8),用于文档导航窗格显示和目录生成

综合格式设置

  • SetParagraphFormat - 使用ParagraphFormatConfig结构一次性设置所有段落属性
    • 基础格式:对齐方式、样式
    • 间距设置:行间距、段前段后间距、首行缩进
    • 缩进设置:首行缩进、左右缩进(支持悬挂缩进)
    • 分页控制:与下段保持、行保持、段前分页、孤行控制
    • 大纲级别:0-8级别设置

使用示例

// 方法1:使用单独的方法设置
title := doc.AddParagraph("第一章 概述")
title.SetAlignment(document.AlignCenter)
title.SetKeepWithNext(true)
title.SetPageBreakBefore(true)
title.SetOutlineLevel(0)

// 方法2:使用SetParagraphFormat一次性设置
para := doc.AddParagraph("重要内容")
para.SetParagraphFormat(&document.ParagraphFormatConfig{
    Alignment:       document.AlignJustify,
    Style:           "Normal",
    LineSpacing:     1.5,
    BeforePara:      12,
    AfterPara:       6,
    FirstLineCm:     0.5,
    KeepWithNext:    true,
    KeepLines:       true,
    WidowControl:    true,
    OutlineLevel:    0,
})

应用场景

  • 文档结构化 - 使用大纲级别创建清晰的文档层次结构
  • 专业排版 - 使用分页控制确保标题和内容的关联性
  • 内容保护 - 使用行保持防止重要段落被分页
  • 章节管理 - 使用段前分页实现章节的页面独立性
段落内容操作

文档主体操作方法

元素查询
元素添加

表格操作方法

表格创建
行操作
列操作
单元格操作
单元格文本格式化
单元格合并
单元格特殊属性
表格整体操作
行高设置
表格布局与对齐
行属性设置
表格分页设置
表格样式
边框设置
背景与阴影
单元格图片功能 ✨ 新功能

支持向表格单元格中添加图片:

CellImageConfig - 单元格图片配置
type CellImageConfig struct {
    FilePath        string      // 图片文件路径
    Data            []byte      // 图片二进制数据(与FilePath二选一)
    Format          ImageFormat // 图片格式(当使用Data时需要指定)
    Width           float64     // 图片宽度(毫米),0表示自动
    Height          float64     // 图片高度(毫米),0表示自动
    KeepAspectRatio bool        // 是否保持宽高比
    AltText         string      // 图片替代文字
    Title           string      // 图片标题
}
表格单元格图片使用示例
// 创建表格
table, err := doc.AddTable(&document.TableConfig{
    Rows:  2,
    Cols:  2,
    Width: 8000,
})

// 方式1:从文件添加图片到单元格
imageInfo, err := doc.AddCellImageFromFile(table, 0, 0, "logo.png", 30) // 30mm宽度

// 方式2:从二进制数据添加图片
imageData := []byte{...} // 图片二进制数据
imageInfo, err := doc.AddCellImageFromData(table, 0, 1, imageData, 25) // 25mm宽度

// 方式3:使用完整配置
config := &document.CellImageConfig{
    FilePath:        "product.jpg",
    Width:           50,     // 50mm宽度
    Height:          40,     // 40mm高度
    KeepAspectRatio: false,  // 不保持宽高比
    AltText:         "产品图片",
    Title:           "产品展示",
}
imageInfo, err := doc.AddCellImage(table, 1, 0, config)

注意事项

  • 图片通过 Document 对象的方法添加,因为图片资源需要在文档级别管理
  • 支持 PNG、JPEG、GIF 格式的图片
  • 宽度/高度单位为毫米,设置为0时使用原始尺寸
  • 当设置 KeepAspectRatiotrue 时,只需设置宽度或高度其中之一
单元格遍历迭代器 ✨ 新功能

提供强大的单元格遍历和查找功能:

CellIterator - 单元格迭代器
// 创建迭代器
iterator := table.NewCellIterator()

// 遍历所有单元格
for iterator.HasNext() {
    cellInfo, err := iterator.Next()
    if err != nil {
        break
    }
    fmt.Printf("单元格[%d,%d]: %s\n", cellInfo.Row, cellInfo.Col, cellInfo.Text)
}

// 获取进度
progress := iterator.Progress() // 0.0 - 1.0

// 重置迭代器
iterator.Reset()
ForEach 批量处理
// 遍历所有单元格
err := table.ForEach(func(row, col int, cell *TableCell, text string) error {
    // 处理每个单元格
    return nil
})

// 按行遍历
err := table.ForEachInRow(rowIndex, func(col int, cell *TableCell, text string) error {
    // 处理行中的每个单元格
    return nil
})

// 按列遍历
err := table.ForEachInColumn(colIndex, func(row int, cell *TableCell, text string) error {
    // 处理列中的每个单元格
    return nil
})
范围操作
// 获取指定范围的单元格
cells, err := table.GetCellRange(startRow, startCol, endRow, endCol)
for _, cellInfo := range cells {
    fmt.Printf("单元格[%d,%d]: %s\n", cellInfo.Row, cellInfo.Col, cellInfo.Text)
}
查找功能
// 自定义条件查找
cells, err := table.FindCells(func(row, col int, cell *TableCell, text string) bool {
    return strings.Contains(text, "关键词")
})

// 按文本查找
exactCells, err := table.FindCellsByText("精确匹配", true)
fuzzyCells, err := table.FindCellsByText("模糊", false)
CellInfo 结构
type CellInfo struct {
    Row    int        // 行索引
    Col    int        // 列索引
    Cell   *TableCell // 单元格引用
    Text   string     // 单元格文本
    IsLast bool       // 是否为最后一个单元格
}

工具函数

日志系统
错误处理
域字段工具 ✨ 新增功能

常用配置结构

文本格式
  • TextFormat - 文本格式配置
  • AlignmentType - 对齐类型
  • SpacingConfig - 间距配置
表格配置
  • TableConfig - 表格基础配置
  • CellFormat - 单元格格式
  • RowHeightConfig - 行高配置
  • TableLayoutConfig - 表格布局配置
  • TableStyleConfig - 表格样式配置
  • BorderConfig - 边框配置
  • ShadingConfig - 底纹配置
页面设置配置 ✨ 新增
  • PageSettings - 页面设置配置
  • PageSize - 页面尺寸类型(A4、Letter、Legal、A3、A5、Custom)
  • PageOrientation - 页面方向(Portrait纵向、Landscape横向)
  • SectionProperties - 节属性(包含页面设置信息)
页眉页脚配置 ✨ 新增
  • HeaderFooterType - 页眉页脚类型(Default、First、Even)
  • Header - 页眉结构
  • Footer - 页脚结构
  • HeaderFooterReference - 页眉页脚引用
  • PageNumber - 页码字段
目录配置 ✨ 新增
  • TOCConfig - 目录配置
  • TOCEntry - 目录条目
  • Bookmark - 书签结构
  • BookmarkEnd - 书签结束标记
脚注尾注配置 ✨ 新增
  • FootnoteConfig - 脚注配置
  • FootnoteType - 脚注类型(Footnote脚注、Endnote尾注)
  • FootnoteNumberFormat - 脚注编号格式
  • FootnoteRestart - 脚注重新开始规则
  • FootnotePosition - 脚注位置
  • Footnote - 脚注结构
  • Endnote - 尾注结构
列表编号配置 ✨ 新增
  • ListConfig - 列表配置
  • ListType - 列表类型(Bullet无序、Number有序等)
  • BulletType - 项目符号类型
  • ListItem - 列表项结构
  • Numbering - 编号定义
  • AbstractNum - 抽象编号定义
  • Level - 编号级别
结构化文档标签配置 ✨ 新增
  • SDT - 结构化文档标签
  • SDTProperties - SDT属性
  • SDTContent - SDT内容
域字段配置 ✨ 新增
  • FieldChar - 域字符
  • InstrText - 域指令文本
  • HyperlinkField - 超链接域
  • PageRefField - 页码引用域
图片配置 ✨ 新增
  • ImageConfig - 图片配置
  • ImageSize - 图片尺寸配置
  • ImageFormat - 图片格式(PNG、JPEG、GIF)
  • ImagePosition - 图片位置(inline、floatLeft、floatRight)
  • ImageWrapText - 文字环绕类型(none、square、tight、topAndBottom)
  • ImageInfo - 图片信息结构
  • AlignmentType - 对齐方式(left、center、right、justify)

使用示例

// 创建新文档
doc := document.New()

// ✨ 新增:页面设置示例
// 设置页面为A4横向
doc.SetPageOrientation(document.OrientationLandscape)

// 设置自定义边距(上下左右:25mm)
doc.SetPageMargins(25, 25, 25, 25)

// 设置自定义页面尺寸(200mm x 300mm)
doc.SetCustomPageSize(200, 300)

// 或者使用完整页面设置
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)

// ✨ 新增:页眉页脚示例
// 添加页眉
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("更多说明", "这是尾注内容")

// ✨ 新增:列表示例
// 添加无序列表
doc.AddBulletList("列表项1", 0, document.BulletTypeDot)
doc.AddBulletList("列表项2", 1, document.BulletTypeCircle)

// 添加有序列表
doc.AddNumberedList("编号项1", 0, document.ListTypeNumber)

// ✨ 新增:图片示例
// 从文件添加图片
imageInfo, err := doc.AddImageFromFile("path/to/image.png", &document.ImageConfig{
    Size: &document.ImageSize{
        Width:  100.0, // 100毫米宽度
        Height: 75.0,  // 75毫米高度
    },
    Position: document.ImagePositionInline,
    WrapText: document.ImageWrapNone,
    AltText:  "示例图片",
    Title:    "这是一个示例图片",
})

// 从数据添加图片
imageData := []byte{...} // 图片二进制数据
imageInfo2, err := doc.AddImageFromData(
    imageData,
    "example.png",
    document.ImageFormatPNG,
    200, 150, // 原始像素尺寸
    &document.ImageConfig{
        Size: &document.ImageSize{
            Width:           60.0, // 只设置宽度
            KeepAspectRatio: true, // 保持长宽比
        },
        AltText: "数据图片",
    },
)

// 调整图片大小
err = doc.ResizeImage(imageInfo, &document.ImageSize{
    Width:  80.0,
    Height: 60.0,
})

// 设置图片属性
err = doc.SetImagePosition(imageInfo, document.ImagePositionFloatLeft, 5.0, 0.0)
err = doc.SetImageWrapText(imageInfo, document.ImageWrapSquare)
err = doc.SetImageAltText(imageInfo, "更新的替代文字")
err = doc.SetImageTitle(imageInfo, "更新的标题")

// ✨ 新增:设置图片对齐方式(仅适用于嵌入式图片)
err = doc.SetImageAlignment(imageInfo, document.AlignCenter)  // 居中对齐
err = doc.SetImageAlignment(imageInfo, document.AlignLeft)    // 左对齐
err = doc.SetImageAlignment(imageInfo, document.AlignRight)   // 右对齐
doc.AddNumberedList("第一项", 0, document.ListTypeDecimal)
doc.AddNumberedList("第二项", 0, document.ListTypeDecimal)

// 添加段落
para := doc.AddParagraph("这是一个段落")
para.SetAlignment(document.AlignCenter)

// 创建表格
table := doc.CreateTable(&document.TableConfig{
    Rows:  3,
    Cols:  3,
    Width: 5000,
})

// 设置单元格内容
table.SetCellText(0, 0, "标题")

// 保存文档
doc.Save("example.docx")

注意事项

  1. 所有位置索引都是从0开始
  2. 宽度单位使用磅(pt),1磅 = 20twips
  3. 颜色使用十六进制格式,如 "FF0000" 表示红色
  4. 在操作表格前请确保行列索引有效,否则可能返回错误
  5. 页眉页脚类型包括:Default(默认)、First(首页)、Even(偶数页)
  6. 目录功能需要先添加带书签的标题,然后调用生成目录方法
  7. 脚注和尾注会自动编号,支持多种编号格式和重启规则
  8. 列表支持多级嵌套,最多支持9级缩进
  9. 结构化文档标签主要用于目录等特殊功能的实现
  10. 图片支持PNG、JPEG、GIF格式,会自动嵌入到文档中
  11. 图片尺寸可以用毫米或像素指定,支持保持长宽比的缩放
  12. 图片位置支持嵌入式、左浮动、右浮动等多种布局方式
  13. 图片对齐功能仅适用于嵌入式图片(ImagePositionInline),浮动图片请使用位置控制

Markdown转Word功能 ✨ 新增功能

WordZero现在支持将Markdown文档转换为Word格式,基于goldmark解析引擎实现,提供高质量的转换效果。

Markdown包API
转换器接口
转换方法
配置选项 (ConvertOptions)
  • EnableGFM - 启用GitHub Flavored Markdown支持
  • EnableFootnotes - 启用脚注支持
  • EnableTables - 启用表格支持
  • EnableTaskList - 启用任务列表支持
  • StyleMapping - 自定义样式映射
  • DefaultFontFamily - 默认字体族
  • DefaultFontSize - 默认字体大小
  • ImageBasePath - 图片基础路径
  • EmbedImages - 是否嵌入图片
  • MaxImageWidth - 最大图片宽度(英寸)
  • PreserveLinkStyle - 保留链接样式
  • ConvertToBookmarks - 内部链接转书签
  • GenerateTOC - 生成目录
  • TOCMaxLevel - 目录最大级别
  • PageSettings - 页面设置
  • StrictMode - 严格模式
  • IgnoreErrors - 忽略转换错误
  • ErrorCallback - 错误回调函数
  • ProgressCallback - 进度回调函数
支持的Markdown语法
基础语法
  • 标题 (# ## ### #### ##### ######) - 转换为Word标题样式1-6
  • 段落 - 转换为Word正文段落
  • 粗体 (**文本**) - 转换为粗体格式
  • 斜体 (*文本*) - 转换为斜体格式
  • 行内代码 (`代码`) - 转换为等宽字体
  • 代码块 ( ) - 转换为代码块样式
列表支持
  • 无序列表 (- * +) - 转换为Word项目符号列表
  • 有序列表 (1. 2. 3.) - 转换为Word编号列表
  • 多级列表 - 支持嵌套列表结构
GitHub Flavored Markdown扩展 ✨ 新增
  • 表格 (| 列1 | 列2 |) - 转换为Word表格
    • 支持表头自动识别和样式设置
    • 支持对齐控制(左对齐 :---、居中 :---:、右对齐 ---:
    • 自动设置表格边框和单元格格式
  • 任务列表 (- [x] 已完成 / - [ ] 未完成) - 转换为复选框符号
    • ☑ 表示已完成任务
    • ☐ 表示未完成任务
    • 支持嵌套任务列表
    • 支持混合格式(粗体、斜体、代码等)
其他元素
  • 引用块 (> 引用文本) - 转换为斜体引用样式
  • 分割线 (---) - 转换为水平线
  • 链接 ([文本](URL)) - 转换为蓝色文本(后续支持超链接)
  • 图片 (![alt](src)) - 转换为图片占位符(后续支持图片嵌入)
使用示例
基础字符串转换
import "github.com/ZeroHawkeye/wordZero/pkg/markdown"

// 创建转换器
converter := markdown.NewConverter(markdown.DefaultOptions())

// 转换Markdown字符串
markdownText := `# 标题

这是一个包含**粗体**和*斜体*的段落。

## 子标题

- 列表项1
- 列表项2

> 引用文本

` + "`" + `代码示例` + "`" + `
`

doc, err := converter.ConvertString(markdownText, nil)
if err != nil {
    log.Fatal(err)
}

// 保存Word文档
err = doc.Save("output.docx")
表格和任务列表示例 ✨ 新增
// 启用表格和任务列表功能
options := markdown.DefaultOptions()
options.EnableTables = true
options.EnableTaskList = true

converter := markdown.NewConverter(options)

// 包含表格和任务列表的Markdown
markdownWithTable := `# 项目进度表

## 功能实现状态

| 功能名称 | 状态 | 负责人 |
|:---------|:----:|-------:|
| 表格转换 | ✅ | 张三 |
| 任务列表 | ✅ | 李四 |
| 图片处理 | 🚧 | 王五 |

## 待办事项

- [x] 实现表格转换功能
  - [x] 基础表格支持
  - [x] 对齐方式处理
  - [x] 表头样式设置
- [ ] 完善任务列表功能
  - [x] 复选框显示
  - [ ] 交互功能
- [ ] 图片嵌入支持
  - [ ] PNG格式
  - [ ] JPEG格式

## 备注

> 表格支持**左对齐**、` + "`" + `居中对齐` + "`" + `和***右对齐***三种方式
`

doc, err := converter.ConvertString(markdownWithTable, options)
if err != nil {
    log.Fatal(err)
}

err = doc.Save("project_status.docx")
高级配置示例
// 创建高质量转换配置
options := &markdown.ConvertOptions{
    EnableGFM:         true,
    EnableFootnotes:   true,
    EnableTables:      true,
    GenerateTOC:       true,
    TOCMaxLevel:       3,
    DefaultFontFamily: "Calibri",
    DefaultFontSize:   11.0,
    EmbedImages:       true,
    MaxImageWidth:     6.0,
    PageSettings: &document.PageSettings{
        Size:        document.PageSizeA4,
        Orientation: document.OrientationPortrait,
        MarginTop:   25,
        MarginRight: 20,
        MarginBottom: 25,
        MarginLeft:  20,
    },
    ProgressCallback: func(current, total int) {
        fmt.Printf("转换进度: %d/%d\n", current, total)
    },
}

converter := markdown.NewConverter(options)
文件转换示例
// 单文件转换
err := converter.ConvertFile("input.md", "output.docx", nil)

// 批量文件转换
files := []string{"doc1.md", "doc2.md", "doc3.md"}
err := converter.BatchConvert(files, "output/", options)
自定义样式映射
options := markdown.DefaultOptions()
options.StyleMapping = map[string]string{
    "heading1": "CustomTitle",
    "heading2": "CustomSubtitle", 
    "quote":    "CustomQuote",
    "code":     "CustomCode",
}

converter := markdown.NewConverter(options)

Word转Markdown功能 ✨ 新增功能

WordZero现在支持将Word文档反向转换为Markdown格式,提供完整的双向转换能力。

Word导出器API
导出器接口
导出方法
导出配置选项 (ExportOptions)
  • UseGFMTables - 使用GitHub风味Markdown表格
  • PreserveFootnotes - 保留脚注
  • PreserveLineBreaks - 保留换行符
  • WrapLongLines - 自动换行
  • MaxLineLength - 最大行长度
  • ExtractImages - 导出图片文件
  • ImageOutputDir - 图片输出目录
  • ImageNamePattern - 图片命名模式
  • ImageRelativePath - 使用相对路径
  • PreserveBookmarks - 保留书签
  • ConvertHyperlinks - 转换超链接
  • PreserveCodeStyle - 保留代码样式
  • DefaultCodeLang - 默认代码语言
  • IgnoreUnknownStyles - 忽略未知样式
  • PreserveTOC - 保留目录
  • IncludeMetadata - 包含文档元数据
  • StripComments - 删除注释
  • UseSetext - 使用Setext样式标题
  • BulletListMarker - 项目符号标记
  • EmphasisMarker - 强调标记
  • StrictMode - 严格模式
  • IgnoreErrors - 忽略错误
  • ErrorCallback - 错误回调函数
  • ProgressCallback - 进度回调函数
Word→Markdown转换映射
Word元素 Markdown语法 说明
Heading1-6 # ## ### #### ##### ###### 标题级别对应
粗体 **粗体** 文本格式
斜体 *斜体* 文本格式
删除线 ~~删除线~~ 文本格式
行内代码 `代码` 代码格式
代码块 代码块 代码块
超链接 [链接文本](URL) 链接转换
图片 ![图片](路径) 图片引用
表格 | 表格 | GFM表格格式
无序列表 - 项目 列表项
有序列表 1. 项目 编号列表
引用块 > 引用内容 引用格式
Word转Markdown使用示例
基础文件导出
import "github.com/ZeroHawkeye/wordZero/pkg/markdown"

// 创建导出器
exporter := markdown.NewExporter(markdown.DefaultExportOptions())

// 导出Word文档为Markdown
err := exporter.ExportToFile("document.docx", "output.md", nil)
if err != nil {
    log.Fatal(err)
}
导出为字符串
// 打开Word文档
doc, err := document.Open("document.docx")
if err != nil {
    log.Fatal(err)
}

// 导出为Markdown字符串
exporter := markdown.NewExporter(markdown.DefaultExportOptions())
markdownText, err := exporter.ExportToString(doc, nil)
if err != nil {
    log.Fatal(err)
}

fmt.Println(markdownText)
高质量导出配置
// 高质量导出配置
options := &markdown.ExportOptions{
    UseGFMTables:      true,              // 使用GFM表格
    ExtractImages:     true,              // 导出图片
    ImageOutputDir:    "./images",        // 图片目录
    PreserveFootnotes: true,              // 保留脚注
    IncludeMetadata:   true,              // 包含元数据
    ConvertHyperlinks: true,              // 转换超链接
    PreserveCodeStyle: true,              // 保留代码样式
    UseSetext:         false,             // 使用ATX标题
    BulletListMarker:  "-",              // 使用短横线
    EmphasisMarker:    "*",              // 使用星号
    ProgressCallback: func(current, total int) {
        fmt.Printf("导出进度: %d/%d\n", current, total)
    },
}

exporter := markdown.NewExporter(options)
err := exporter.ExportToFile("complex_document.docx", "output.md", options)
批量导出示例
// 批量导出Word文档
files := []string{"doc1.docx", "doc2.docx", "doc3.docx"}

options := &markdown.ExportOptions{
    ExtractImages:     true,
    ImageOutputDir:    "extracted_images/",
    UseGFMTables:      true,
    ProgressCallback: func(current, total int) {
        fmt.Printf("批量导出进度: %d/%d\n", current, total)
    },
}

exporter := markdown.NewExporter(options)
err := exporter.BatchExport(files, "markdown_output/", options)

双向转换器 ✨ 统一接口

双向转换器API
双向转换使用示例
自动转换
import "github.com/ZeroHawkeye/wordZero/pkg/markdown"

// 创建双向转换器
converter := markdown.NewBidirectionalConverter(
    markdown.HighQualityOptions(),        // Markdown→Word选项
    markdown.HighQualityExportOptions(),  // Word→Markdown选项
)

// 自动检测文件类型并转换
err := converter.AutoConvert("input.docx", "output.md")     // Word→Markdown
err = converter.AutoConvert("input.md", "output.docx")     // Markdown→Word
配置独立的转换方向
// Markdown转Word配置
mdToWordOpts := &markdown.ConvertOptions{
    EnableGFM:         true,
    EnableTables:      true,
    GenerateTOC:       true,
    DefaultFontFamily: "Calibri",
    DefaultFontSize:   11.0,
}

// Word转Markdown配置
wordToMdOpts := &markdown.ExportOptions{
    UseGFMTables:      true,
    ExtractImages:     true,
    ImageOutputDir:    "./images",
    PreserveFootnotes: true,
    ConvertHyperlinks: true,
}

// 创建双向转换器
converter := markdown.NewBidirectionalConverter(mdToWordOpts, wordToMdOpts)

// 执行转换
err := converter.AutoConvert("document.docx", "document.md")
技术特性
架构设计
  • goldmark集成 - 使用高性能的goldmark解析引擎
  • AST遍历 - 基于抽象语法树的转换处理
  • API复用 - 充分复用现有WordZero document API
  • 向后兼容 - 不影响现有document包功能
性能优势
  • 流式处理 - 支持大型文档的流式转换
  • 内存效率 - 优化的内存使用模式
  • 并发支持 - 批量转换支持并发处理
  • 错误恢复 - 智能错误处理和恢复机制
扩展性
  • 插件架构 - 支持自定义渲染器扩展
  • 配置驱动 - 丰富的配置选项支持不同需求
  • 样式系统 - 灵活的样式映射和自定义能力
  • 回调机制 - 进度和错误回调支持
注意事项
  1. 兼容性 - 基于CommonMark 0.31.2标准,与GitHub Markdown高度兼容
  2. 图片处理 - 当前版本图片转换为占位符,完整图片支持在规划中
  3. 表格支持已完善 - 支持完整的GFM表格语法,包括对齐控制和表头样式
  4. 任务列表已实现 - 支持任务复选框,显示为Unicode符号(☑/☐)
  5. 链接处理 - 当前转换为蓝色文本,超链接功能在开发中
  6. 样式映射 - 可通过StyleMapping自定义Markdown元素到Word样式的映射
  7. 错误处理 - 建议在生产环境中启用错误回调,监控转换质量
  8. 性能考虑 - 批量转换大量文件时建议分批处理,避免内存压力
  9. 编码支持 - 完全支持UTF-8编码,包括中文等多字节字符
  10. 配置要求 - 表格和任务列表功能需要在ConvertOptions中显式启用
  11. 向后兼容 - 新功能不会影响现有的document包API,保持完全兼容

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

Constants

This section is empty.

Variables

View Source
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")
)

预定义错误类型

View Source
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"), "")
)

模板相关错误

View Source
var (
	// ErrInvalidPageSettings 无效的页面设置
	ErrInvalidPageSettings = errors.New("invalid page settings")
)

页面设置相关错误

Functions

func Debug

func Debug(msg string)

Debug 全局调试日志

func Debugf

func Debugf(format string, args ...interface{})

Debugf 全局调试日志

func Error

func Error(msg string)

Error 全局错误日志

func Errorf

func Errorf(format string, args ...interface{})

Errorf 全局错误日志

func Info

func Info(msg string)

Info 全局信息日志

func Infof

func Infof(format string, args ...interface{})

Infof 全局信息日志

func SetGlobalLevel

func SetGlobalLevel(level LogLevel)

SetGlobalLevel 设置全局日志级别

func SetGlobalOutput

func SetGlobalOutput(output io.Writer)

SetGlobalOutput 设置全局日志输出

func Warn

func Warn(msg string)

Warn 全局警告日志

func Warnf

func Warnf(format string, args ...interface{})

Warnf 全局警告日志

func WrapError

func WrapError(operation string, err error) error

WrapError 包装错误,添加操作上下文

func WrapErrorWithContext

func WrapErrorWithContext(operation string, err error, context string) error

WrapErrorWithContext 包装错误,添加操作和上下文信息

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 AvLst added in v1.3.3

type AvLst struct {
	XMLName xml.Name `xml:"a:avLst"`
}

AvLst 调整值列表

type Blip added in v1.3.3

type Blip struct {
	XMLName xml.Name `xml:"a:blip"`
	Embed   string   `xml:"r:embed,attr"`
}

Blip 二进制图片

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) AddElement

func (b *Body) AddElement(element interface{})

AddElement 添加元素到文档主体

func (*Body) GetParagraphs

func (b *Body) GetParagraphs() []*Paragraph

GetParagraphs 获取所有段落

func (*Body) GetTables

func (b *Body) GetTables() []*Table

GetTables 获取所有表格

func (*Body) MarshalXML

func (b *Body) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML 自定义XML序列化,按照元素顺序输出

type BodyElement

type BodyElement interface {
	ElementType() string
}

BodyElement 文档主体元素接口

type Bold

type Bold struct {
	XMLName xml.Name `xml:"w:b"`
}

Bold 粗体

type BoldCs added in v1.3.6

type BoldCs struct {
	XMLName xml.Name `xml:"w:bCs"`
}

BoldCs 复杂脚本粗体

type BookmarkEnd

type BookmarkEnd struct {
	XMLName xml.Name `xml:"w:bookmarkEnd"`
	ID      string   `xml:"w:id,attr"`
}

BookmarkEnd 书签结束

func (*BookmarkEnd) ElementType

func (b *BookmarkEnd) ElementType() string

ElementType 返回书签结束元素类型

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 CPText

type CPText struct {
	Text string `xml:",chardata"`
}

CPText CP命名空间文本元素

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) HasNext

func (iter *CellIterator) HasNext() bool

HasNext 检查是否还有下一个单元格

func (*CellIterator) Next

func (iter *CellIterator) Next() (*CellInfo, error)

Next 获取下一个单元格信息

func (*CellIterator) Progress

func (iter *CellIterator) Progress() float64

Progress 获取迭代进度(0.0-1.0)

func (*CellIterator) Reset

func (iter *CellIterator) Reset()

Reset 重置迭代器到开始位置

func (*CellIterator) Total

func (iter *CellIterator) Total() int

Total 获取总单元格数量

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 Color

type Color struct {
	XMLName xml.Name `xml:"w:color"`
	Val     string   `xml:"w:val,attr"`
}

Color 颜色

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 DCDate

type DCDate struct {
	XSIType string    `xml:"xsi:type,attr"`
	Date    time.Time `xml:",chardata"`
}

DCDate DC命名空间日期元素

type DCText

type DCText struct {
	Text string `xml:",chardata"`
}

DCText DC命名空间文本元素

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 DocPart

type DocPart struct {
	XMLName xml.Name `xml:"w:docPart"`
	Val     string   `xml:"w:val,attr"`
}

DocPart 文档部件

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

type DocPartUnique struct {
	XMLName xml.Name `xml:"w:docPartUnique"`
}

DocPartUnique 文档部件唯一标识

type Document

type Document struct {
	// 文档的主要内容
	Body *Body
	// contains filtered or unexported fields
}

Document 表示一个Word文档

func New

func New() *Document

New 创建一个新的Word文档

func Open

func Open(filename string) (*Document, error)

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

func (d *Document) AddEndnote(text string, endnoteText string) error

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

func (d *Document) AddFootnote(text string, footnoteText string) error

AddFootnote 添加脚注

func (*Document) AddFootnoteToRun

func (d *Document) AddFootnoteToRun(run *Run, footnoteText string) error

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

func (d *Document) AddHeadingParagraph(text string, level int) *Paragraph

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

func (d *Document) AddHeadingWithBookmark(text string, level int, bookmarkName string) *Paragraph

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

func (d *Document) AddNumberedList(text string, level int, numType ListType) *Paragraph

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

func (d *Document) AddParagraph(text string) *Paragraph

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

func (d *Document) AutoGenerateTOC(config *TOCConfig) error

AutoGenerateTOC 自动生成目录,检测现有文档中的标题

func (*Document) ClearDocGrid added in v1.3.8

func (d *Document) ClearDocGrid() error

ClearDocGrid 清除文档网格设置

func (*Document) CreateMultiLevelList

func (d *Document) CreateMultiLevelList(items []ListItem) error

CreateMultiLevelList 创建多级列表

func (*Document) CreateTOCSDT

func (d *Document) CreateTOCSDT(title string, maxLevel int) *SDT

CreateTOCSDT 创建目录SDT结构

func (*Document) CreateTable

func (d *Document) CreateTable(config *TableConfig) (*Table, error)

CreateTable 创建一个新表格 参数:

  • config: 表格配置

返回:

  • *Table: 创建的表格对象
  • error: 如果配置无效则返回错误

func (*Document) GenerateTOC

func (d *Document) GenerateTOC(config *TOCConfig) error

GenerateTOC 生成目录

func (*Document) GetDocumentProperties

func (d *Document) GetDocumentProperties() (*DocumentProperties, error)

GetDocumentProperties 获取文档属性

func (*Document) GetEndnoteCount

func (d *Document) GetEndnoteCount() int

GetEndnoteCount 获取尾注数量

func (*Document) GetFootnoteCount

func (d *Document) GetFootnoteCount() int

GetFootnoteCount 获取脚注数量

func (*Document) GetHeadingCount

func (d *Document) GetHeadingCount() map[int]int

GetHeadingCount 获取文档中标题的数量,用于调试

func (*Document) GetPageSettings

func (d *Document) GetPageSettings() *PageSettings

GetPageSettings 获取当前文档的页面设置

func (*Document) GetParts added in v1.3.3

func (d *Document) GetParts() map[string][]byte

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

func (d *Document) ListHeadings() []TOCEntry

ListHeadings 列出文档中所有的标题,用于调试

func (*Document) RemoveElementAt added in v1.5.0

func (d *Document) RemoveElementAt(index int) bool

RemoveElementAt 根据元素索引删除元素(包括段落、表格等)。

参数 index 是要删除的元素在文档主体中的索引(从0开始)。 如果索引超出范围,此方法会返回错误。

返回值表示是否成功删除元素。

示例:

doc := document.New()
doc.AddParagraph("段落")
doc.AddTable(&document.TableConfig{Rows: 2, Cols: 2})
doc.RemoveElementAt(0)  // 删除第一个元素(段落)

func (*Document) RemoveEndnote

func (d *Document) RemoveEndnote(endnoteID string) error

RemoveEndnote 删除指定尾注

func (*Document) RemoveFootnote

func (d *Document) RemoveFootnote(footnoteID string) error

RemoveFootnote 删除指定脚注

func (*Document) RemoveParagraph added in v1.5.0

func (d *Document) RemoveParagraph(paragraph *Paragraph) bool

RemoveParagraph 从文档中删除指定的段落。

参数 paragraph 是要删除的段落对象。 如果段落不存在于文档中,此方法不会产生任何效果。

返回值表示是否成功删除段落。

示例:

doc := document.New()
para := doc.AddParagraph("要删除的段落")
doc.RemoveParagraph(para)

func (*Document) RemoveParagraphAt added in v1.5.0

func (d *Document) RemoveParagraphAt(index int) bool

RemoveParagraphAt 根据索引删除段落。

参数 index 是要删除的段落在所有段落中的索引(从0开始)。 如果索引超出范围,此方法会返回错误。

返回值表示是否成功删除段落。

示例:

doc := document.New()
doc.AddParagraph("第一段")
doc.AddParagraph("第二段")
doc.RemoveParagraphAt(0)  // 删除第一段

func (*Document) ResizeImage added in v1.3.3

func (d *Document) ResizeImage(imageInfo *ImageInfo, size *ImageSize) error

ResizeImage 调整图片大小

func (*Document) RestartNumbering

func (d *Document) RestartNumbering(numID string)

RestartNumbering 重新开始编号

func (*Document) Save

func (d *Document) Save(filename string) error

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) SetAuthor

func (d *Document) SetAuthor(author string) error

SetAuthor 设置文档作者

func (*Document) SetCategory

func (d *Document) SetCategory(category string) error

SetCategory 设置文档类别

func (*Document) SetCustomPageSize

func (d *Document) SetCustomPageSize(width, height float64) error

SetCustomPageSize 设置自定义页面大小(毫米)

func (*Document) SetDescription

func (d *Document) SetDescription(description string) error

SetDescription 设置文档描述

func (*Document) SetDifferentFirstPage

func (d *Document) SetDifferentFirstPage(different bool)

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

func (d *Document) SetGutterWidth(width float64) error

SetGutterWidth 设置装订线宽度(毫米)

func (*Document) SetHeaderFooterDistance

func (d *Document) SetHeaderFooterDistance(header, footer float64) error

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

func (d *Document) SetImageAltText(imageInfo *ImageInfo, altText string) error

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

func (d *Document) SetImageTitle(imageInfo *ImageInfo, title string) error

SetImageTitle 设置图片标题

func (*Document) SetImageWrapText added in v1.3.3

func (d *Document) SetImageWrapText(imageInfo *ImageInfo, wrapText ImageWrapText) error

SetImageWrapText 设置图片文字环绕

func (*Document) SetKeywords

func (d *Document) SetKeywords(keywords string) error

SetKeywords 设置文档关键字

func (*Document) SetPageMargins

func (d *Document) SetPageMargins(top, right, bottom, left float64) error

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

func (d *Document) SetPageSize(size PageSize) error

SetPageSize 设置页面大小

func (*Document) SetSubject

func (d *Document) SetSubject(subject string) error

SetSubject 设置文档主题

func (*Document) SetTOCStyle

func (d *Document) SetTOCStyle(level int, style *TextFormat) error

SetTOCStyle 设置目录样式

func (*Document) SetTitle

func (d *Document) SetTitle(title string) error

SetTitle 设置文档标题

func (*Document) ToBytes

func (d *Document) ToBytes() ([]byte, error)

ToBytes 将文档转换为字节数组

func (*Document) UpdateStatistics

func (d *Document) UpdateStatistics() error

UpdateStatistics 更新文档统计信息

func (*Document) UpdateTOC

func (d *Document) UpdateTOC() error

UpdateTOC 更新目录

type DocumentError

type DocumentError struct {
	Operation string // 操作名称
	Cause     error  // 原因
	Context   string // 上下文信息
}

DocumentError 文档操作错误

func NewDocumentError

func NewDocumentError(operation string, cause error, context string) *DocumentError

NewDocumentError 创建新的文档错误

func (*DocumentError) Error

func (e *DocumentError) Error() string

Error 实现error接口

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

type EndnoteNumFmt struct {
	XMLName xml.Name `xml:"w:numFmt"`
	Val     string   `xml:"w:val,attr"`
}

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

type EndnoteNumStart struct {
	XMLName xml.Name `xml:"w:numStart"`
	Val     string   `xml:"w:val,attr"`
}

EndnoteNumStart 尾注起始编号

type EndnotePos added in v1.3.3

type EndnotePos struct {
	XMLName xml.Name `xml:"w:pos"`
	Val     string   `xml:"w:val,attr"`
}

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 FillRect added in v1.3.3

type FillRect struct {
	XMLName xml.Name `xml:"a:fillRect"`
}

FillRect 填充矩形

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 FontSize

type FontSize struct {
	XMLName xml.Name `xml:"w:sz"`
	Val     string   `xml:"w:val,attr"`
}

FontSize 字体大小

type FontSizeCs added in v1.3.6

type FontSizeCs struct {
	XMLName xml.Name `xml:"w:szCs"`
	Val     string   `xml:"w:val,attr"`
}

FontSizeCs 复杂脚本字体大小

type Footer struct {
	XMLName     xml.Name     `xml:"w:ftr"`
	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"`
}

Footer 页脚结构

type FooterReference

type FooterReference struct {
	XMLName xml.Name `xml:"w:footerReference"`
	Type    string   `xml:"w:type,attr"`
	ID      string   `xml:"r:id,attr"`
}

FooterReference 页脚引用

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

type FootnoteNumFmt struct {
	XMLName xml.Name `xml:"w:numFmt"`
	Val     string   `xml:"w:val,attr"`
}

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

type FootnoteNumStart struct {
	XMLName xml.Name `xml:"w:numStart"`
	Val     string   `xml:"w:val,attr"`
}

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

type FootnotePos struct {
	XMLName xml.Name `xml:"w:pos"`
	Val     string   `xml:"w:val,attr"`
}

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 GridSpan

type GridSpan struct {
	XMLName xml.Name `xml:"w:gridSpan"`
	Val     string   `xml:"w:val,attr"`
}

GridSpan 网格跨度(列合并)

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 {
	Text      string        // 文本内容
	Format    *TextFormat   // 文本格式配置
	Alignment AlignmentType // 对齐方式
}

HeaderFooterConfig 页眉页脚配置

type HeaderFooterReference

type HeaderFooterReference struct {
	XMLName xml.Name `xml:"w:headerReference"`
	Type    string   `xml:"w:type,attr"`
	ID      string   `xml:"r:id,attr"`
}

HeaderFooterReference 页眉页脚引用

type HeaderFooterType

type HeaderFooterType string

HeaderFooterType 页眉页脚类型

const (
	// HeaderFooterTypeDefault 默认页眉页脚
	HeaderFooterTypeDefault HeaderFooterType = "default"
	// HeaderFooterTypeFirst 首页页眉页脚
	HeaderFooterTypeFirst HeaderFooterType = "first"
	// HeaderFooterTypeEven 偶数页页眉页脚
	HeaderFooterTypeEven HeaderFooterType = "even"
)

type HideMark

type HideMark struct {
	XMLName xml.Name `xml:"w:hideMark"`
	Val     string   `xml:"w:val,attr,omitempty"`
}

HideMark 隐藏标记

type Highlight added in v1.3.6

type Highlight struct {
	XMLName xml.Name `xml:"w:highlight"`
	Val     string   `xml:"w:val,attr"`
}

Highlight 背景色

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 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 ILevel

type ILevel struct {
	XMLName xml.Name `xml:"w:ilvl"`
	Val     string   `xml:"w:val,attr"`
}

ILevel 编号级别

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 Italic

type Italic struct {
	XMLName xml.Name `xml:"w:i"`
}

Italic 斜体

type ItalicCs added in v1.3.6

type ItalicCs struct {
	XMLName xml.Name `xml:"w:iCs"`
}

ItalicCs 复杂脚本斜体

type Justification

type Justification struct {
	XMLName xml.Name `xml:"w:jc"`
	Val     string   `xml:"w:val,attr,omitempty"`
}

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 LevelJc

type LevelJc struct {
	XMLName xml.Name `xml:"w:lvlJc"`
	Val     string   `xml:"w:val,attr"`
}

LevelJc 级别对齐

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 LevelText

type LevelText struct {
	XMLName xml.Name `xml:"w:lvlText"`
	Val     string   `xml:"w:val,attr"`
}

LevelText 级别文本

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 LogLevel

type LogLevel int

LogLevel 日志级别

const (
	// LogLevelDebug 调试级别
	LogLevelDebug LogLevel = iota
	// LogLevelInfo 信息级别
	LogLevelInfo
	// LogLevelWarn 警告级别
	LogLevelWarn
	// LogLevelError 错误级别
	LogLevelError
	// LogLevelSilent 静默级别
	LogLevelSilent
)

func (LogLevel) String

func (l LogLevel) String() string

String 返回日志级别的字符串表示

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

Logger 日志记录器

func NewLogger

func NewLogger(level LogLevel, output io.Writer) *Logger

NewLogger 创建新的日志记录器

func (*Logger) Debug

func (l *Logger) Debug(msg string)

Debug 输出调试日志

func (*Logger) Debugf

func (l *Logger) Debugf(format string, args ...interface{})

Debugf 输出调试日志

func (*Logger) Error

func (l *Logger) Error(msg string)

Error 输出错误日志

func (*Logger) Errorf

func (l *Logger) Errorf(format string, args ...interface{})

Errorf 输出错误日志

func (*Logger) Info

func (l *Logger) Info(msg string)

Info 输出信息日志

func (*Logger) Infof

func (l *Logger) Infof(format string, args ...interface{})

Infof 输出信息日志

func (*Logger) SetLevel

func (l *Logger) SetLevel(level LogLevel)

SetLevel 设置日志级别

func (*Logger) SetOutput

func (l *Logger) SetOutput(output io.Writer)

SetOutput 设置输出目标

func (*Logger) Warn

func (l *Logger) Warn(msg string)

Warn 输出警告日志

func (*Logger) Warnf

func (l *Logger) Warnf(format string, args ...interface{})

Warnf 输出警告日志

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 NoWrap

type NoWrap struct {
	XMLName xml.Name `xml:"w:noWrap"`
	Val     string   `xml:"w:val,attr,omitempty"`
}

NoWrap 禁止换行

type NumFmt

type NumFmt struct {
	XMLName xml.Name `xml:"w:numFmt"`
	Val     string   `xml:"w:val,attr"`
}

NumFmt 编号格式

type NumID

type NumID struct {
	XMLName xml.Name `xml:"w:numId"`
	Val     string   `xml:"w:val,attr"`
}

NumID 编号ID

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 Off added in v1.3.3

type Off struct {
	XMLName xml.Name `xml:"a:off"`
	X       string   `xml:"x,attr"`
	Y       string   `xml:"y,attr"`
}

Off 偏移

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

type OutlineLevel struct {
	XMLName xml.Name `xml:"w:outlineLvl"`
	Val     string   `xml:"w:val,attr"`
}

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)
	Footer  string   `xml:"w:footer,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
	FooterDistance 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

func (p *Paragraph) AddInlineMath(ommlContent string)

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) ElementType

func (p *Paragraph) ElementType() string

ElementType 返回段落元素类型

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

func (p *Paragraph) SetBold(bold bool)

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

func (p *Paragraph) SetColor(color string)

SetColor 设置段落中所有文本的颜色。

参数 color 是十六进制颜色值,如 "FF0000"(红色)、"0000FF"(蓝色)等。 颜色值不需要 "#" 前缀,如果包含会自动移除。 传入空字符串将移除颜色设置。

示例:

para := doc.AddParagraph("这是红色文本")
para.SetColor("FF0000")

func (*Paragraph) SetFontFamily added in v1.5.0

func (p *Paragraph) SetFontFamily(name string)

SetFontFamily 设置段落中所有文本的字体。

参数 name 是字体名称,如 "Arial"、"Times New Roman"、"微软雅黑" 等。

示例:

para := doc.AddParagraph("这是自定义字体文本")
para.SetFontFamily("微软雅黑")

func (*Paragraph) SetFontSize added in v1.5.0

func (p *Paragraph) SetFontSize(size int)

SetFontSize 设置段落中所有文本的字体大小。

参数 size 是字体大小(磅),如 12、14、16 等。 传入 0 或负数将移除字体大小设置。

示例:

para := doc.AddParagraph("这是大号文本")
para.SetFontSize(16)

func (*Paragraph) SetHighlight added in v1.5.0

func (p *Paragraph) SetHighlight(color string)

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

func (p *Paragraph) SetIndentation(firstLineCm, leftCm, rightCm float64)

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

func (p *Paragraph) SetItalic(italic bool)

SetItalic 设置段落中所有文本的斜体效果。

参数 italic 表示是否启用斜体。 当设置为 true 时,将对段落中所有运行应用斜体效果。 当设置为 false 时,将移除所有运行的斜体效果。

示例:

para := doc.AddParagraph("这是斜体文本")
para.SetItalic(true)

func (*Paragraph) SetKeepLines added in v1.5.0

func (p *Paragraph) SetKeepLines(keep bool)

SetKeepLines 设置段落中的所有行保持在同一页。

此方法用于防止段落在分页时被拆分到多个页面, 确保段落的所有行都显示在同一页上。

参数:

  • keep: true表示启用该属性,false表示禁用

示例:

// 确保整个段落不被分页
para := doc.AddParagraph("这是一个重要的段落,需要保持完整显示。")
para.SetKeepLines(true)

func (*Paragraph) SetKeepWithNext added in v1.5.0

func (p *Paragraph) SetKeepWithNext(keep bool)

SetKeepWithNext 设置段落与下一段落保持在同一页。

此方法用于确保当前段落和下一段落不会被分页符分隔, 常用于标题和正文的组合,或需要保持连续性的内容。

参数:

  • keep: true表示启用该属性,false表示禁用

示例:

// 标题与下一段保持在一起
title := doc.AddParagraph("第一章 概述")
title.SetKeepWithNext(true)
doc.AddParagraph("本章介绍...")  // 这段内容会与标题保持在同一页

func (*Paragraph) SetOutlineLevel added in v1.5.0

func (p *Paragraph) SetOutlineLevel(level int)

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

func (p *Paragraph) SetPageBreakBefore(pageBreak bool)

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

func (p *Paragraph) SetSnapToGrid(snapToGrid bool)

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

func (p *Paragraph) SetStrike(strike bool)

SetStrike 设置段落中所有文本的删除线效果。

参数 strike 表示是否启用删除线。 当设置为 true 时,将对段落中所有运行应用删除线效果。 当设置为 false 时,将移除所有运行的删除线效果。

示例:

para := doc.AddParagraph("这是删除线文本")
para.SetStrike(true)

func (*Paragraph) SetStyle

func (p *Paragraph) SetStyle(styleID string)

SetStyle 设置段落的样式。

参数 styleID 是要应用的样式ID,如 "Heading1"、"Normal" 等。 此方法会设置段落的样式引用,确保段落使用指定的样式。

示例:

para := doc.AddParagraph("这是一个段落")
para.SetStyle("Heading2")  // 设置为二级标题样式

func (*Paragraph) SetUnderline added in v1.5.0

func (p *Paragraph) SetUnderline(underline bool)

SetUnderline 设置段落中所有文本的下划线效果。

参数 underline 表示是否启用下划线。 当设置为 true 时,将对段落中所有运行应用单线下划线效果。 当设置为 false 时,将移除所有运行的下划线效果。

示例:

para := doc.AddParagraph("这是下划线文本")
para.SetUnderline(true)

func (*Paragraph) SetWidowControl added in v1.5.0

func (p *Paragraph) SetWidowControl(control bool)

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

type ParagraphStyle struct {
	XMLName xml.Name `xml:"w:pStyle"`
	Val     string   `xml:"w:val,attr"`
}

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 PosAlign added in v1.3.3

type PosAlign struct {
	XMLName xml.Name `xml:"wp:align"`
	Value   string   `xml:",chardata"`
}

PosAlign 位置对齐

type PosOffset added in v1.3.3

type PosOffset struct {
	XMLName xml.Name `xml:"wp:posOffset"`
	Value   string   `xml:",chardata"`
}

PosOffset 位置偏移

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

func (r *Run) MarshalXML(e *xml.Encoder, start xml.StartElement) error

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

func (sdt *SDT) AddTOCEntry(text string, level int, pageNum int, entryID string)

AddTOCEntry 向目录SDT添加条目

func (*SDT) ElementType

func (s *SDT) ElementType() string

ElementType 返回SDT元素类型

func (*SDT) FinalizeTOCSDT

func (sdt *SDT) FinalizeTOCSDT()

FinalizeTOCSDT 完成目录SDT构建

type SDTColor

type SDTColor struct {
	XMLName xml.Name `xml:"w15:color"`
	Val     string   `xml:"w:val,attr"`
}

SDTColor 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 SDTID

type SDTID struct {
	XMLName xml.Name `xml:"w:id"`
	Val     string   `xml:"w:val,attr"`
}

SDTID 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"`
	FooterReferences []*FooterReference       `xml:"w:footerReference,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 Start

type Start struct {
	XMLName xml.Name `xml:"w:start"`
	Val     string   `xml:"w:val,attr"`
}

Start 起始编号

type Stretch added in v1.3.3

type Stretch struct {
	XMLName  xml.Name  `xml:"a:stretch"`
	FillRect *FillRect `xml:"a:fillRect"`
}

Stretch 拉伸

type Strike added in v1.3.6

type Strike struct {
	XMLName xml.Name `xml:"w:strike"`
}

Strike 删除线

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 目录配置

func DefaultTOCConfig

func DefaultTOCConfig() *TOCConfig

DefaultTOCConfig 返回默认目录配置

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 Tab

type Tab struct {
	XMLName xml.Name `xml:"w:tab"`
}

Tab 制表符

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

func (t *Table) AddCellParagraph(row, col int, text string) (*Paragraph, error)

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

func (t *Table) AppendColumn(data []string, width int) error

AppendColumn 在表格末尾添加列

func (*Table) AppendRow

func (t *Table) AppendRow(data []string) error

AppendRow 在表格末尾添加行

func (*Table) ApplyTableStyle

func (t *Table) ApplyTableStyle(config *TableStyleConfig) error

ApplyTableStyle 应用表格样式

func (*Table) ClearCellContent

func (t *Table) ClearCellContent(row, col int) error

ClearCellContent 清空单元格内容但保留格式

func (*Table) ClearCellFormat

func (t *Table) ClearCellFormat(row, col int) error

ClearCellFormat 清空单元格格式但保留内容

func (*Table) ClearCellParagraphs added in v1.5.0

func (t *Table) ClearCellParagraphs(row, col int) error

ClearCellParagraphs 清空单元格中的所有段落,只保留一个空段落 参数:

  • row: 行索引(从0开始)
  • col: 列索引(从0开始)

返回:

  • error: 如果索引无效则返回错误

func (*Table) ClearTable

func (t *Table) ClearTable()

ClearTable 清空表格内容(保留结构)

func (*Table) CopyTable

func (t *Table) CopyTable() *Table

CopyTable 复制表格

func (*Table) CreateCustomTableStyle

func (t *Table) CreateCustomTableStyle(styleID, styleName string,
	borderConfig *TableBorderConfig,
	shadingConfig *ShadingConfig,
	firstRowBold bool) error

CreateCustomTableStyle 创建自定义表格样式

func (*Table) DeleteColumn

func (t *Table) DeleteColumn(colIndex int) error

DeleteColumn 删除指定列

func (*Table) DeleteColumns

func (t *Table) DeleteColumns(startIndex, endIndex int) error

DeleteColumns 删除指定范围的列

func (*Table) DeleteRow

func (t *Table) DeleteRow(rowIndex int) error

DeleteRow 删除指定行

func (*Table) DeleteRows

func (t *Table) DeleteRows(startIndex, endIndex int) error

DeleteRows 删除指定范围的行

func (*Table) ElementType

func (t *Table) ElementType() string

ElementType 返回表格元素类型

func (*Table) FindCells

func (t *Table) FindCells(predicate func(row, col int, cell *TableCell, text string) bool) ([]*CellInfo, error)

FindCells 查找满足条件的单元格

func (*Table) FindCellsByText

func (t *Table) FindCellsByText(searchText string, exactMatch bool) ([]*CellInfo, error)

FindCellsByText 根据文本内容查找单元格

func (*Table) ForEach

func (t *Table) ForEach(fn func(row, col int, cell *TableCell, text string) error) error

ForEach 遍历所有单元格,对每个单元格执行指定函数

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) GetCell

func (t *Table) GetCell(row, col int) (*TableCell, error)

GetCell 获取指定位置的单元格

func (*Table) GetCellFormat

func (t *Table) GetCellFormat(row, col int) (*CellFormat, error)

GetCellFormat 获取单元格格式信息

func (*Table) GetCellParagraphs added in v1.5.0

func (t *Table) GetCellParagraphs(row, col int) ([]Paragraph, error)

GetCellParagraphs 获取单元格中的所有段落 参数:

  • row: 行索引(从0开始)
  • col: 列索引(从0开始)

返回:

  • []Paragraph: 单元格中的所有段落
  • error: 如果索引无效则返回错误

func (*Table) GetCellRange

func (t *Table) GetCellRange(startRow, startCol, endRow, endCol int) ([]*CellInfo, error)

GetCellRange 获取指定范围内的所有单元格

func (*Table) GetCellText

func (t *Table) GetCellText(row, col int) (string, error)

GetCellText 获取单元格文本

func (*Table) GetCellTextDirection

func (t *Table) GetCellTextDirection(row, col int) (CellTextDirection, error)

GetCellTextDirection 获取单元格文字方向

func (*Table) GetColumnCount

func (t *Table) GetColumnCount() int

GetColumnCount 获取表格列数

func (*Table) GetMergedCellInfo

func (t *Table) GetMergedCellInfo(row, col int) (map[string]interface{}, error)

GetMergedCellInfo 获取合并单元格信息

func (*Table) GetNestedTables added in v1.5.0

func (t *Table) GetNestedTables(row, col int) ([]Table, error)

GetNestedTables 获取单元格中的所有嵌套表格 参数:

  • row: 行索引(从0开始)
  • col: 列索引(从0开始)

返回:

  • []Table: 单元格中的所有嵌套表格
  • error: 如果索引无效则返回错误

func (*Table) GetRowCount

func (t *Table) GetRowCount() int

GetRowCount 获取表格行数

func (*Table) GetRowHeight

func (t *Table) GetRowHeight(rowIndex int) (*RowHeightConfig, error)

GetRowHeight 获取行高配置

func (*Table) GetTableBreakInfo

func (t *Table) GetTableBreakInfo() map[string]interface{}

GetTableBreakInfo 获取表格分页信息

func (*Table) GetTableLayout

func (t *Table) GetTableLayout() *TableLayoutConfig

GetTableLayout 获取表格布局配置

func (*Table) InsertColumn

func (t *Table) InsertColumn(position int, data []string, width int) error

InsertColumn 在指定位置插入列

func (*Table) InsertRow

func (t *Table) InsertRow(position int, data []string) error

InsertRow 在指定位置插入行

func (*Table) IsCellMerged

func (t *Table) IsCellMerged(row, col int) (bool, error)

IsCellMerged 检查单元格是否被合并

func (*Table) IsRowHeader

func (t *Table) IsRowHeader(rowIndex int) (bool, error)

IsRowHeader 检查行是否为标题行

func (*Table) IsRowKeepTogether

func (t *Table) IsRowKeepTogether(rowIndex int) (bool, error)

IsRowKeepTogether 检查行是否禁止跨页分割

func (*Table) MergeCellsHorizontal

func (t *Table) MergeCellsHorizontal(row, startCol, endCol int) error

MergeCellsHorizontal 水平合并单元格(合并列)

func (*Table) MergeCellsRange

func (t *Table) MergeCellsRange(startRow, endRow, startCol, endCol int) error

MergeCellsRange 合并单元格区域(多行多列)

func (*Table) MergeCellsVertical

func (t *Table) MergeCellsVertical(startRow, endRow, col int) error

MergeCellsVertical 垂直合并单元格(合并行)

func (*Table) NewCellIterator

func (t *Table) NewCellIterator() *CellIterator

NewCellIterator 创建新的单元格迭代器

func (*Table) RemoveCellBorders

func (t *Table) RemoveCellBorders(row, col int) error

RemoveCellBorders 移除单元格边框

func (*Table) RemoveTableBorders

func (t *Table) RemoveTableBorders() error

RemoveTableBorders 移除表格边框

func (*Table) SetAlternatingRowColors

func (t *Table) SetAlternatingRowColors(evenRowColor, oddRowColor string) error

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

func (t *Table) SetCellPadding(row, col int, padding int) error

SetCellPadding 设置单元格内边距

func (*Table) SetCellShading

func (t *Table) SetCellShading(row, col int, config *ShadingConfig) error

SetCellShading 设置单元格背景

func (*Table) SetCellText

func (t *Table) SetCellText(row, col int, text string) error

SetCellText 设置单元格文本

func (*Table) SetCellTextDirection

func (t *Table) SetCellTextDirection(row, col int, direction CellTextDirection) error

SetCellTextDirection 设置单元格文字方向

func (*Table) SetHeaderRows

func (t *Table) SetHeaderRows(startRow, endRow int) error

SetHeaderRows 设置表格标题行范围

func (*Table) SetRowAsHeader

func (t *Table) SetRowAsHeader(rowIndex int, isHeader bool) error

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

func (t *Table) SetRowKeepTogether(rowIndex int, keepTogether bool) error

SetRowKeepTogether 设置行禁止跨页分割

func (*Table) SetRowKeepWithNext

func (t *Table) SetRowKeepWithNext(rowIndex int, keepWithNext bool) error

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 设置表格背景

func (*Table) UnmergeCells

func (t *Table) UnmergeCells(row, col int) error

UnmergeCells 取消单元格合并

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

func (tc *TableCell) MarshalXML(e *xml.Encoder, start xml.StartElement) error

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

type TableCellSpace struct {
	W    string `xml:"w:w,attr"`
	Type string `xml:"w:type,attr"`
}

TableCellSpace 表格单元格空间

type TableCellSpaceCell

type TableCellSpaceCell struct {
	W    string `xml:"w:w,attr"`
	Type string `xml:"w:type,attr"`
}

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

type TableGridCol struct {
	XMLName xml.Name `xml:"w:gridCol"`
	W       string   `xml:"w:w,attr,omitempty"`
}

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 TableJc

type TableJc struct {
	XMLName xml.Name `xml:"w:jc"`
	Val     string   `xml:"w:val,attr"`
}

TableJc 表格对齐

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

type TableStyle struct {
	XMLName xml.Name `xml:"w:tblStyle"`
	Val     string   `xml:"w:val,attr"`
}

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 Tabs

type Tabs struct {
	XMLName xml.Name `xml:"w:tabs"`
	Tabs    []TabDef `xml:"w:tab"`
}

Tabs 制表符设置

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) Clear added in v1.3.3

func (td *TemplateData) Clear()

Clear 清空模板数据

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 TitlePage

type TitlePage struct {
	XMLName xml.Name `xml:"w:titlePg"`
}

TitlePage 首页不同设置

type Underline added in v1.3.6

type Underline struct {
	XMLName xml.Name `xml:"w:u"`
	Val     string   `xml:"w:val,attr,omitempty"`
}

Underline 下划线

type VAlign

type VAlign struct {
	XMLName xml.Name `xml:"w:vAlign"`
	Val     string   `xml:"w:val,attr"`
}

VAlign 垂直对齐

type VMerge

type VMerge struct {
	XMLName xml.Name `xml:"w:vMerge"`
	Val     string   `xml:"w:val,attr,omitempty"`
}

VMerge 垂直合并(行合并)

type ValidationError

type ValidationError struct {
	Field   string // 字段名
	Value   string // 错误值
	Message string // 错误消息
}

ValidationError 验证错误

func NewValidationError

func NewValidationError(field, value, message string) *ValidationError

NewValidationError 创建新的验证错误

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error 实现error接口

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 WrapNone added in v1.3.3

type WrapNone struct {
	XMLName xml.Name `xml:"wp:wrapNone"`
}

WrapNone 无环绕

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 上下环绕

type Xfrm added in v1.3.3

type Xfrm struct {
	XMLName xml.Name `xml:"a:xfrm"`
	Off     *Off     `xml:"a:off,omitempty"`
	Ext     *Ext     `xml:"a:ext"`
}

Xfrm 变换

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL