docx-generator

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

DOCX Generator

DOCX 生成工具

When to Use This Skill

何时使用此技能

Use this skill when:
  • Creating Word documents programmatically from data or specifications
  • Populating branded templates with dynamic content while preserving corporate styling
  • Extracting text, tables, and structure from existing DOCX files for analysis
  • Finding and replacing placeholder text like
    {{TITLE}}
    or
    ${author}
  • Automating document generation workflows (reports, contracts, letters)
Do NOT use this skill when:
  • User wants to open/view documents (use native Word or viewer)
  • Complex mail merge with data sources (use native Word mail merge)
  • Working with older .doc format (DOCX only)
  • PDF output is needed (use pdf-generator skill instead)
在以下场景使用此技能:
  • 根据数据或规范以编程方式创建Word文档
  • 为品牌化模板填充动态内容,同时保留企业样式
  • 从现有DOCX文件中提取文本、表格和结构用于分析
  • 查找并替换
    {{TITLE}}
    ${author}
    这类占位符文本
  • 自动化文档生成工作流(报告、合同、信函)
请勿在以下场景使用此技能:
  • 用户想要打开/查看文档(使用原生Word或查看器)
  • 涉及数据源的复杂邮件合并(使用原生Word邮件合并功能)
  • 处理旧版.doc格式(仅支持DOCX)
  • 需要PDF输出(使用pdf-generator技能)

Prerequisites

前置条件

  • Deno installed (https://deno.land/)
  • Input DOCX files for template-based operations
  • JSON specification for scratch generation
  • 已安装Deno(https://deno.land/)
  • 用于模板操作的输入DOCX文件
  • 用于从头创建的JSON规范

Quick Start

快速开始

Two Modes of Operation

两种操作模式

  1. Template Mode: Modify existing branded templates
    • Analyze template to find placeholders
    • Replace
      {{PLACEHOLDERS}}
      with actual content
  2. Scratch Mode: Create documents from nothing using JSON specifications
  1. 模板模式:修改现有品牌化模板
    • 分析模板以找到占位符
    • {{PLACEHOLDERS}}
      替换为实际内容
  2. 从头创建模式:使用JSON规范从零开始创建文档

Instructions

操作步骤

Mode 1: Template-Based Generation

模式1:基于模板的生成

Step 1a: Analyze the Template

步骤1a:分析模板

Extract text inventory to understand what can be replaced:
bash
deno run --allow-read scripts/analyze-template.ts corporate-template.docx > inventory.json
Output (inventory.json):
json
{
  "filename": "corporate-template.docx",
  "paragraphCount": 25,
  "tableCount": 2,
  "imageCount": 1,
  "paragraphs": [
    {
      "index": 0,
      "style": "Title",
      "fullText": "{{DOCUMENT_TITLE}}",
      "runs": [
        { "text": "{{DOCUMENT_TITLE}}", "bold": true, "fontSize": 28 }
      ]
    }
  ],
  "placeholders": [
    { "tag": "{{DOCUMENT_TITLE}}", "location": "paragraph", "paragraphIndex": 0 },
    { "tag": "{{AUTHOR}}", "location": "footer-default", "paragraphIndex": 0 },
    { "tag": "${date}", "location": "table", "tableIndex": 0, "cellLocation": "R1C2" }
  ]
}
提取文本清单以了解可替换内容:
bash
deno run --allow-read scripts/analyze-template.ts corporate-template.docx > inventory.json
输出(inventory.json):
json
{
  "filename": "corporate-template.docx",
  "paragraphCount": 25,
  "tableCount": 2,
  "imageCount": 1,
  "paragraphs": [
    {
      "index": 0,
      "style": "Title",
      "fullText": "{{DOCUMENT_TITLE}}",
      "runs": [
        { "text": "{{DOCUMENT_TITLE}}", "bold": true, "fontSize": 28 }
      ]
    }
  ],
  "placeholders": [
    { "tag": "{{DOCUMENT_TITLE}}", "location": "paragraph", "paragraphIndex": 0 },
    { "tag": "{{AUTHOR}}", "location": "footer-default", "paragraphIndex": 0 },
    { "tag": "${date}", "location": "table", "tableIndex": 0, "cellLocation": "R1C2" }
  ]
}

Step 1b: Create Replacement Specification

步骤1b:创建替换规范

Create
replacements.json
:
json
{
  "textReplacements": [
    { "tag": "{{DOCUMENT_TITLE}}", "value": "Q4 2024 Financial Report" },
    { "tag": "{{AUTHOR}}", "value": "Finance Department" },
    { "tag": "${date}", "value": "December 15, 2024" },
    { "tag": "{{COMPANY}}", "value": "Acme Corporation" }
  ],
  "includeHeaders": true,
  "includeFooters": true
}
创建
replacements.json
json
{
  "textReplacements": [
    { "tag": "{{DOCUMENT_TITLE}}", "value": "Q4 2024 Financial Report" },
    { "tag": "{{AUTHOR}}", "value": "Finance Department" },
    { "tag": "${date}", "value": "December 15, 2024" },
    { "tag": "{{COMPANY}}", "value": "Acme Corporation" }
  ],
  "includeHeaders": true,
  "includeFooters": true
}

Step 1c: Generate Output

步骤1c:生成输出文件

bash
deno run --allow-read --allow-write scripts/generate-from-template.ts \
  corporate-template.docx replacements.json output.docx
bash
deno run --allow-read --allow-write scripts/generate-from-template.ts \
  corporate-template.docx replacements.json output.docx

Mode 2: From-Scratch Generation

模式2:从头创建文档

Step 2a: Create Specification

步骤2a:创建规范

Create
spec.json
:
json
{
  "title": "Quarterly Report",
  "creator": "Finance Team",
  "styles": {
    "defaultFont": "Calibri",
    "defaultFontSize": 11
  },
  "sections": [
    {
      "header": {
        "paragraphs": [
          { "text": "Acme Corporation", "alignment": "right" }
        ]
      },
      "footer": {
        "paragraphs": [
          { "text": "Confidential", "alignment": "center" }
        ]
      },
      "content": [
        {
          "text": "Q4 2024 Financial Report",
          "heading": 1,
          "alignment": "center"
        },
        {
          "runs": [
            { "text": "Executive Summary: ", "bold": true },
            { "text": "This report provides an overview of our financial performance for Q4 2024." }
          ]
        },
        { "pageBreak": true },
        {
          "text": "Revenue Breakdown",
          "heading": 2
        },
        {
          "rows": [
            {
              "cells": [
                { "content": [{ "text": "Category" }], "shading": "DDDDDD" },
                { "content": [{ "text": "Amount" }], "shading": "DDDDDD" },
                { "content": [{ "text": "Change" }], "shading": "DDDDDD" }
              ],
              "isHeader": true
            },
            {
              "cells": [
                { "content": [{ "text": "Product Sales" }] },
                { "content": [{ "text": "$1,250,000" }] },
                { "content": [{ "text": "+15%" }] }
              ]
            },
            {
              "cells": [
                { "content": [{ "text": "Services" }] },
                { "content": [{ "text": "$750,000" }] },
                { "content": [{ "text": "+8%" }] }
              ]
            }
          ],
          "width": 100,
          "borders": true
        }
      ]
    }
  ]
}
创建
spec.json
json
{
  "title": "Quarterly Report",
  "creator": "Finance Team",
  "styles": {
    "defaultFont": "Calibri",
    "defaultFontSize": 11
  },
  "sections": [
    {
      "header": {
        "paragraphs": [
          { "text": "Acme Corporation", "alignment": "right" }
        ]
      },
      "footer": {
        "paragraphs": [
          { "text": "Confidential", "alignment": "center" }
        ]
      },
      "content": [
        {
          "text": "Q4 2024 Financial Report",
          "heading": 1,
          "alignment": "center"
        },
        {
          "runs": [
            { "text": "Executive Summary: ", "bold": true },
            { "text": "This report provides an overview of our financial performance for Q4 2024." }
          ]
        },
        { "pageBreak": true },
        {
          "text": "Revenue Breakdown",
          "heading": 2
        },
        {
          "rows": [
            {
              "cells": [
                { "content": [{ "text": "Category" }], "shading": "DDDDDD" },
                { "content": [{ "text": "Amount" }], "shading": "DDDDDD" },
                { "content": [{ "text": "Change" }], "shading": "DDDDDD" }
              ],
              "isHeader": true
            },
            {
              "cells": [
                { "content": [{ "text": "Product Sales" }] },
                { "content": [{ "text": "$1,250,000" }] },
                { "content": [{ "text": "+15%" }] }
              ]
            },
            {
              "cells": [
                { "content": [{ "text": "Services" }] },
                { "content": [{ "text": "$750,000" }] },
                { "content": [{ "text": "+8%" }] }
              ]
            }
          ],
          "width": 100,
          "borders": true
        }
      ]
    }
  ]
}

Step 2b: Generate Document

步骤2b:生成文档

bash
deno run --allow-read --allow-write scripts/generate-scratch.ts spec.json output.docx
bash
deno run --allow-read --allow-write scripts/generate-scratch.ts spec.json output.docx

Examples

示例

Example 1: Contract Generation

示例1:合同生成

Scenario: Generate contracts from a branded template.
Steps:
bash
undefined
场景:从品牌化模板生成合同。
步骤
bash
undefined

1. Analyze template for replaceable content

1. 分析模板以获取可替换内容

deno run --allow-read scripts/analyze-template.ts contract-template.docx --pretty
deno run --allow-read scripts/analyze-template.ts contract-template.docx --pretty

2. Create replacements.json with client data

2. 创建包含客户数据的replacements.json

3. Generate contract

3. 生成合同

deno run --allow-read --allow-write scripts/generate-from-template.ts
contract-template.docx replacements.json acme-contract.docx
undefined
deno run --allow-read --allow-write scripts/generate-from-template.ts
contract-template.docx replacements.json acme-contract.docx
undefined

Example 2: Report with Tables

示例2:带表格的报告

Scenario: Generate a data report with tables and formatting.
spec.json:
json
{
  "title": "Sales Report",
  "sections": [{
    "content": [
      { "text": "Monthly Sales Report", "heading": 1 },
      { "text": "January 2025", "heading": 2 },
      {
        "runs": [
          { "text": "Total Sales: ", "bold": true },
          { "text": "$125,000", "color": "2E7D32" }
        ]
      }
    ]
  }]
}
场景:生成包含表格和格式的数据报告。
spec.json
json
{
  "title": "Sales Report",
  "sections": [{
    "content": [
      { "text": "Monthly Sales Report", "heading": 1 },
      { "text": "January 2025", "heading": 2 },
      {
        "runs": [
          { "text": "Total Sales: ", "bold": true },
          { "text": "$125,000", "color": "2E7D32" }
        ]
      }
    ]
  }]
}

Example 3: Letter with Headers/Footers

示例3:带页眉/页脚的信函

Scenario: Create a formal letter with letterhead.
spec.json:
json
{
  "sections": [{
    "header": {
      "paragraphs": [
        { "text": "ACME CORPORATION", "alignment": "center", "runs": [{"text": "ACME CORPORATION", "bold": true, "fontSize": 16}] },
        { "text": "123 Business Ave, City, ST 12345", "alignment": "center" }
      ]
    },
    "content": [
      { "text": "December 15, 2024", "alignment": "right" },
      { "text": "" },
      { "text": "Dear Valued Customer," },
      { "text": "" },
      { "text": "Thank you for your continued business..." },
      { "text": "" },
      { "text": "Sincerely," },
      { "text": "John Smith" },
      { "runs": [{ "text": "CEO", "italic": true }] }
    ],
    "footer": {
      "paragraphs": [
        { "text": "www.acme.com | contact@acme.com", "alignment": "center" }
      ]
    }
  }]
}
场景:创建带有信头的正式信函。
spec.json
json
{
  "sections": [{
    "header": {
      "paragraphs": [
        { "text": "ACME CORPORATION", "alignment": "center", "runs": [{"text": "ACME CORPORATION", "bold": true, "fontSize": 16}] },
        { "text": "123 Business Ave, City, ST 12345", "alignment": "center" }
      ]
    },
    "content": [
      { "text": "December 15, 2024", "alignment": "right" },
      { "text": "" },
      { "text": "Dear Valued Customer," },
      { "text": "" },
      { "text": "Thank you for your continued business..." },
      { "text": "" },
      { "text": "Sincerely," },
      { "text": "John Smith" },
      { "runs": [{ "text": "CEO", "italic": true }] }
    ],
    "footer": {
      "paragraphs": [
        { "text": "www.acme.com | contact@acme.com", "alignment": "center" }
      ]
    }
  }]
}

Script Reference

脚本参考

ScriptPurposePermissions
analyze-template.ts
Extract text, tables, placeholders from DOCX
--allow-read
generate-from-template.ts
Replace placeholders in templates
--allow-read --allow-write
generate-scratch.ts
Create DOCX from JSON specification
--allow-read --allow-write
脚本用途权限
analyze-template.ts
从DOCX中提取文本、表格、占位符
--allow-read
generate-from-template.ts
替换模板中的占位符
--allow-read --allow-write
generate-scratch.ts
根据JSON规范创建DOCX
--allow-read --allow-write

Specification Reference

规范参考

Paragraph Options

段落选项

PropertyTypeDescription
text
stringSimple text content
runs
arrayFormatted text runs (for mixed formatting)
heading
1-6Heading level
alignment
string
left
,
center
,
right
,
justify
bullet
booleanBulleted list item
numbering
booleanNumbered list item
spacing
object
before
,
after
,
line
spacing
indent
object
left
,
right
,
firstLine
indentation
pageBreakBefore
booleanInsert page break before paragraph
属性类型描述
text
string简单文本内容
runs
array格式化文本段(用于混合格式)
heading
1-6标题级别
alignment
string
left
center
right
justify
bullet
boolean项目符号列表项
numbering
boolean编号列表项
spacing
object
before
after
line
间距
indent
object
left
right
firstLine
缩进
pageBreakBefore
boolean在段落前插入分页符

Text Run Options

文本段选项

PropertyTypeDescription
text
stringText content
bold
booleanBold formatting
italic
booleanItalic formatting
underline
booleanUnderline formatting
strike
booleanStrikethrough
fontSize
numberFont size in points
font
stringFont family name
color
stringText color (hex, no #)
highlight
stringHighlight color
superScript
booleanSuperscript
subScript
booleanSubscript
属性类型描述
text
string文本内容
bold
boolean粗体格式
italic
boolean斜体格式
underline
boolean下划线格式
strike
boolean删除线
fontSize
number字体大小(磅)
font
string字体家族名称
color
string文本颜色(十六进制,无#)
highlight
string高亮颜色
superScript
boolean上标
subScript
boolean下标

Table Options

表格选项

PropertyTypeDescription
rows
arrayArray of row specifications
width
numberTable width as percentage
borders
booleanShow table borders
属性类型描述
rows
array行规范数组
width
number表格宽度(百分比)
borders
boolean显示表格边框

Hyperlink Options

超链接选项

PropertyTypeDescription
text
stringLink text
url
stringTarget URL
bold
booleanBold formatting
italic
booleanItalic formatting
属性类型描述
text
string链接文本
url
string目标URL
bold
boolean粗体格式
italic
boolean斜体格式

Common Issues and Solutions

常见问题与解决方案

Issue: Placeholders not being replaced

问题:占位符未被替换

Symptoms: Output DOCX still contains
{{PLACEHOLDER}}
tags.
Solution:
  1. Run
    analyze-template.ts
    to verify exact tag text
  2. Tags may be split across XML runs - the script consolidates these automatically
  3. Ensure
    includeHeaders
    and
    includeFooters
    are true if placeholders are there
症状:输出的DOCX仍包含
{{PLACEHOLDER}}
标签。
解决方案
  1. 运行
    analyze-template.ts
    验证标签文本是否完全匹配
  2. 标签可能被拆分到XML段中 - 脚本会自动合并这些情况
  3. 如果占位符在页眉/页脚中,确保
    includeHeaders
    includeFooters
    设置为true

Issue: Formatting lost after replacement

问题:替换后格式丢失

Symptoms: Replaced text doesn't match original formatting.
Solution:
  • Text replacement preserves the formatting of the original placeholder
  • Ensure placeholder is formatted the way you want the final text to appear
症状:替换后的文本与原格式不匹配。
解决方案
  • 文本替换会保留原占位符的格式
  • 确保占位符的格式与最终文本所需的格式一致

Issue: Images not appearing

问题:图片未显示

Symptoms: Image elements are blank in output.
Solution:
  1. Use paths relative to the spec.json file location
  2. Verify image file exists and is readable
  3. Check supported formats: PNG, JPEG, GIF
症状:输出中的图片元素为空。
解决方案
  1. 使用相对于spec.json文件位置的路径
  2. 验证图片文件存在且可读取
  3. 检查支持的格式:PNG、JPEG、GIF

Issue: Table cell content incorrect

问题:表格单元格内容不正确

Symptoms: Table cells have wrong content or formatting.
Solution:
  • Each cell's
    content
    must be an array of paragraph specifications
  • Use
    shading
    for background color,
    verticalAlign
    for alignment
症状:表格单元格内容或格式错误。
解决方案
  • 每个单元格的
    content
    必须是段落规范数组
  • 使用
    shading
    设置背景色,
    verticalAlign
    设置对齐方式

Limitations

限制

  • DOCX only: Does not support legacy .doc format
  • No track changes: Cannot add or process track changes
  • No comments: Cannot add document comments
  • No macros: Cannot include VBA macros
  • Basic numbering: Limited support for complex numbering schemes
  • Text run splitting: Word may split text across XML elements; script handles common cases
  • 仅支持DOCX:不支持旧版.doc格式
  • 无修订功能:无法添加或处理修订标记
  • 无批注功能:无法添加文档批注
  • 无宏支持:无法包含VBA宏
  • 基础编号:对复杂编号方案的支持有限
  • 文本段拆分:Word可能将文本拆分到XML元素中;脚本可处理常见情况

Related Skills

相关技能

  • pptx-generator: For creating PowerPoint presentations
  • xlsx-generator: For creating Excel spreadsheets
  • pdf-generator: For creating PDF documents
  • pptx-generator:用于创建PowerPoint演示文稿
  • xlsx-generator:用于创建Excel电子表格
  • pdf-generator:用于创建PDF文档