wordZero Documentation

repository·main·Indexed 20 days ago

https://github.com/zerx-lab/wordzero

A high-performance, pure Go library for creating, reading, and modifying Word (.docx) documents. It supports modern OOXML specifications and provides a zero-dependency alternative for document processing, featuring a template engine with support for variable replacement, conditional statements, and nested loops, as well as advanced paragraph formatting and image persistence.

Tokens
24.6K
Snippets
56
Records
91
Agent score
69%

What's inside wordZero

  1. Overview of WordZero features

    main

    WordZero is a high-performance library for DOCX document operations.

    Implemented Features

    • Document Operations: Create, read, save, and parse DOCX documents.
    • Text Formatting: Control fonts, sizes, colors, bold, italic, and more.
    • Style System: Access 18 predefined styles or implement custom styles.
    • Paragraph Management: Alignment, spacing, indentation, and deletion (by index or element).
    • Table Functionality: Complete table operations, styling, and cell iterators.
    • Page Settings: Manage page size, margins, headers, and footers.
    • Advanced Features: Table of contents generation, footnotes/endnotes, list numbering, and a template engine with inheritance support.
    • Image Features: Insertion, size adjustment, and position settings.
    • Markdown to Word: High-quality conversion from Markdown to Word using goldmark.
    • Document Pagination: Support for page break insertion.

    Planned Features

    • Table sorting and advanced operations
    • Bookmarks and cross-references
    • Document comments and revisions
    • Graphics drawing functionality
    • Multi-language and internationalization support
  2. Core features of wordZero

    main

    wordZero is a high-performance library for DOCX document manipulation. Its core capabilities include:

    • Document Operations: Create, read, save, and parse DOCX documents.
    • Text Formatting: Control fonts, sizes, colors, bold, italics, and more.
    • Style System: Access 18 predefined styles or implement custom styles.
    • Paragraph Management: Full support for alignment, spacing, indentation, page breaks, line/widow/orphan control, and outline levels. Includes paragraph deletion by index or element.
    • Tables: Complete table operations, style settings, and cell iterators.
    • Page Settings: Manage page dimensions, margins, headers, and footers.
    • Advanced Features: Table of contents generation, footnotes/endnotes, list numbering, and a template engine with inheritance support.
    • Images: Insert, resize, and position images.
    • Markdown Conversion: High-quality Markdown to Word conversion powered by goldmark.
    • Pagination: Support for inserting page breaks and managing multi-page structures.
  3. Supported template syntax for DOCX templates

    main

    When creating a .docx template, use the following syntax to define dynamic content:

    Variable Replacement

    Use {{variableName}} to define placeholders:

    Customer Name: {{customerName}}
    Phone: {{phone}}

    Conditional Statements

    Use {{#if condition}}...{{/if}} to show/hide content based on boolean data:

    {{#if isVip}}
    🎖️ Valued VIP Customer
    {{/if}}

    Loops

    Use {{#each list}}...{{/each}} to iterate over arrays or slices:

    {{#each items}}
    {{@index}}. {{name}} - {{price}}元
    {{/each}}

    Loop Context Variables

    Inside an {{#each}} block, you can use:

    • {{this}}: The current item's value.
    • {{@index}}: The current index (starting from 0).
    • {{@first}}: Boolean, true if it is the first item.
    • {{@last}}: Boolean, true if it is the last item.
  4. Understand the wordZero project structure

    main

    The repository is organized into the following key directories:

    • pkg/: Contains the core library code.
      • pkg/document/: Document manipulation logic.
      • pkg/style/: Style management system.
    • examples/: Practical usage examples.
    • test/: Integration tests.
    • benchmark/: Performance benchmarking tools.
    • docs/: Documentation assets and logos.
    • wordZero.wiki/: Full project documentation.
  5. Understand the performance test configuration and metrics

    main

    To ensure fairness, all language tests use a standardized number of iterations for specific document operations:

    Test ItemIterationsDescription
    Basic Document Creation50Creates a document with basic text
    Complex Formatting30Creates a document with various formatting
    Table Operations20Creates a 10x5 table
    Large Table Processing10Creates a 100x10 table
    Large Documents5Creates a document with 1000+ paragraphs and tables
    Memory Usage Test10Tests memory consumption

    Recorded Metrics

    Each test records the following performance indicators:

    • avgTime: Average execution time across all iterations.
    • minTime: The fastest execution time recorded.
    • maxTime: The slowest execution time recorded.
    • iterations: The total number of test runs.
  6. Implement Template Inheritance

    main

    WordZero supports advanced template inheritance using {{extends "base_template"}} and {{#block "block_name"}}...{{/block}} syntax. This allows you to define a base structure and selectively override specific parts in child templates.

    Key Concepts:

    • Block Definition: In the base template, wrap content in {{#block "name"}} to make it overridable.
    • Block Overriding: In the child template, use {{#block "name"}} to provide new content for that specific section. Unspecified blocks retain their parent's content.
    • Multi-level Inheritance: Templates can inherit from other templates that themselves inherit from a base.
    // 1. Base Template
    baseTemplate := `
    {{#block "header"}}
    Default Header
    {{/block}}
    {{#block "body"}}
    Default Body
    {{/block}}`
    
    // 2. Child Template
    childTemplate := `
    {{extends "base_template"}}
    
    {{#block "header"}}
    Custom Child Header
    {{/block}}` // Only 'header' is overridden; 'body' remains default.
  7. Control paragraph pagination and layout

    main

    WordZero provides several methods to control how paragraphs behave during page breaks and document navigation:

    • SetKeepWithNext(bool): Ensures the paragraph stays on the same page as the following paragraph.
    • SetKeepLines(bool): Prevents a paragraph from being split across two pages.
    • SetPageBreakBefore(bool): Forces a page break immediately before the paragraph.
    • SetWidowControl(bool): Enables widow/orphan control to improve typesetting quality.
    • SetOutlineLevel(int): Sets the outline level for document navigation and hierarchy.
  8. Math formula support in Markdown to Word

    main

    The converter supports LaTeX-style math formulas, which are rendered in Word using the Cambria Math font.

    • Inline formulas: Wrap with single dollar signs, e.g., $E = mc^2$.
    • Block formulas: Wrap with double dollar signs, e.g., $$ x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} $$.

    Supported LaTeX syntax includes Greek letters (\alpha, \beta), operators (\times, \pm), superscripts/subscripts (x^2, x_i), fractions (\frac{a}{b}), square roots (\sqrt{x}), and more.

  9. Understand WordZero project structure

    main

    The project is organized into several key directories:

    • pkg/: Contains the core library code.
      • pkg/document/: Document operation features.
      • pkg/style/: Style management system.
    • examples/: Usage examples for various features.
    • test/: Integration tests.
    • benchmark/: Performance benchmarks.
    • docs/: Documentation and branding assets (logos).
    • wordZero.wiki/: Complete documentation source.
    wordZero/
    ├── pkg/                    # Core library code
    │   ├── document/          # Document operation features
    │   └── style/             # Style management system
    ├── examples/              # Usage examples
    ├── test/                  # Integration tests
    ├── benchmark/             # Performance benchmarks
    ├── docs/                  # Documentation and assets
    └── wordZero.wiki/         # Complete documentation
  10. Technical implementation of image persistence

    main

    The wordZero library ensures image persistence during document modification through several key mechanisms:

    • Relationship Parsing: The library parses the word/_rels/document.xml.rels file when opening documents to identify and preserve existing image and resource relationships via parseDocumentRelationships().
    • ID Management: To prevent conflicts when adding new media, the library uses updateNextImageID() to update the image ID counter based on existing images.
    • Enhanced Loading: Both Open() and OpenFromMemory() methods have been enhanced to ensure that image relationships are preserved throughout the document lifecycle.
  11. Core types in the Document package

    main

    The pkg/document package provides the fundamental structures for manipulating Word documents. The primary types are:

    • Document: The core structure representing a complete Word document.
    • Body: Represents the main body content of the document.
    • Paragraph: Represents a paragraph structure within the document.
    • Table: Represents a table structure within the document.
  12. How the Style Management System works

    main

    The WordZero style system is built around two main components:

    1. StyleManager: The core engine that handles low-level style operations, including loading predefined styles, adding/removing styles, and managing the inheritance tree.
    2. QuickStyleAPI: A high-level wrapper around the StyleManager designed for ease of use. It simplifies common tasks like creating custom styles via configuration objects and querying style information by type.

    Developers can use StyleManager for fine-grained control or QuickStyleAPI for rapid document styling.

    // Create the core manager
    styleManager := style.NewStyleManager()
    
    // Create the high-level API (recommended for most users)
    quickAPI := style.NewQuickStyleAPI(styleManager)