en Basic Features - ZeroHawkeye/wordZero GitHub Wiki

Basic Features

This chapter introduces the basic features of WordZero, including document creation, paragraph addition, text formatting, and basic style application.

📋 Document Creation and Saving

Creating a New Document

package main

import (
    "github.com/ZeroHawkeye/wordZero/pkg/document"
)

func main() {
    // Create a new empty document
    doc := document.New()
    
    // Or create a document with default styles
    // doc := document.NewWithDefaultStyles()
}

Saving Documents

WordZero provides two ways to save documents:

// Method 1: Save to specified file
err := doc.SaveToFile("my-document.docx")
if err != nil {
    log.Printf("Save failed: %v", err)
}

// Method 2: Use Save method (recommended)
err := doc.Save("my-document.docx")
if err != nil {
    log.Printf("Save failed: %v", err)
}

⚠️ Note: Ensure the output directory exists. WordZero will not automatically create directories.

📝 Paragraph Operations

Adding Basic Paragraphs

// Add simple text paragraph
para := doc.AddParagraph("This is a paragraph")

// Add empty paragraph
emptyPara := doc.AddParagraph("")

Adding Styled Paragraphs

import "github.com/ZeroHawkeye/wordZero/pkg/style"

// Add title paragraph
title := doc.AddParagraph("Document Title")
title.SetStyle(style.StyleTitle)

// Add subtitle
subtitle := doc.AddParagraph("Document Subtitle")
subtitle.SetStyle(style.StyleSubtitle)

// Add body paragraph
content := doc.AddParagraph("This is body content")
content.SetStyle(style.StyleNormal)

🎨 Text Formatting

Basic Text Formatting

WordZero supports various text formats through the TextFormat structure:

// Add formatted text to paragraph
para := doc.AddParagraph("")

// Normal text
para.AddFormattedText("Normal text", nil)

// Bold text
para.AddFormattedText("Bold", &document.TextFormat{
    Bold: true,
})

// Italic text
para.AddFormattedText("Italic", &document.TextFormat{
    Italic: true,
})

// Underlined text
para.AddFormattedText("Underlined", &document.TextFormat{
    Underline: true,
})

// Colored text (red)
para.AddFormattedText("Red text", &document.TextFormat{
    FontColor: "FF0000",
})

Combined Formatting

// Bold + Italic + Colored
para.AddFormattedText("Combined format", &document.TextFormat{
    Bold:      true,
    Italic:    true,
    FontColor: "0000FF", // Blue
})

Font Settings

// Set font and size
para.AddFormattedText("Different font", &document.TextFormat{
    FontName: "Times New Roman",
    FontSize: 14,
})

📋 Complete Example

Here's a complete example demonstrating basic features:

package main

import (
    "fmt"
    "log"
    "os"
    "path/filepath"
    
    "github.com/ZeroHawkeye/wordZero/pkg/document"
    "github.com/ZeroHawkeye/wordZero/pkg/style"
)

func main() {
    fmt.Println("WordZero Basic Features Demo")
    
    // 1. Create new document
    doc := document.New()
    
    // 2. Add document title
    title := doc.AddParagraph("WordZero User Guide")
    title.SetStyle(style.StyleTitle)
    
    // 3. Add subtitle
    subtitle := doc.AddParagraph("A Simple and Powerful Go Library for Word Document Manipulation")
    subtitle.SetStyle(style.StyleSubtitle)
    
    // 4. Add chapter headings
    chapter1 := doc.AddParagraph("Chapter 1: Getting Started")
    chapter1.SetStyle(style.StyleHeading1)
    
    section1 := doc.AddParagraph("1.1 Installation")
    section1.SetStyle(style.StyleHeading2)
    
    subsection1 := doc.AddParagraph("1.1.1 Go Module Installation")
    subsection1.SetStyle(style.StyleHeading3)
    
    // 5. Add body content
    normalText := "WordZero is a Word document manipulation library specifically designed for Go. It provides a clean API that makes it easy to create, edit, and save Word documents."
    normalPara := doc.AddParagraph(normalText)
    normalPara.SetStyle(style.StyleNormal)
    
    // 6. Add code block
    codeTitle := doc.AddParagraph("Code Example")
    codeTitle.SetStyle(style.StyleHeading3)
    
    codeExample := `go get github.com/ZeroHawkeye/wordZero

// Usage example
import "github.com/ZeroHawkeye/wordZero/pkg/document"

doc := document.New()
doc.AddParagraph("Hello, WordZero!")
doc.Save("example.docx")`
    
    codePara := doc.AddParagraph(codeExample)
    codePara.SetStyle(style.StyleCodeBlock)
    
    // 7. Add quote
    quoteText := "Simple API design is the core philosophy of WordZero. We believe that powerful functionality should not come at the cost of complex usage."
    quotePara := doc.AddParagraph(quoteText)
    quotePara.SetStyle(style.StyleQuote)
    
    // 8. Add mixed format text
    mixedPara := doc.AddParagraph("")
    mixedPara.AddFormattedText("WordZero supports various text formats: ", nil)
    mixedPara.AddFormattedText("bold", &document.TextFormat{Bold: true})
    mixedPara.AddFormattedText(", ", nil)
    mixedPara.AddFormattedText("italic", &document.TextFormat{Italic: true})
    mixedPara.AddFormattedText(", ", nil)
    mixedPara.AddFormattedText("colored text", &document.TextFormat{FontColor: "FF0000"})
    mixedPara.AddFormattedText(" and ", nil)
    mixedPara.AddFormattedText("different fonts", &document.TextFormat{
        FontName: "Times New Roman", 
        FontSize: 14,
    })
    mixedPara.AddFormattedText(".", nil)
    
    // 9. Create simple list
    listTitle := doc.AddParagraph("Key WordZero Features:")
    listTitle.SetStyle(style.StyleNormal)
    
    features := []string{
        "• Clean and easy-to-use API design",
        "• Complete style system support", 
        "• OOXML specification compliance",
        "• No external dependencies",
        "• Cross-platform compatibility",
    }
    
    for _, feature := range features {
        featurePara := doc.AddParagraph(feature)
        featurePara.SetStyle(style.StyleListParagraph)
    }
    
    // 10. Ensure output directory exists and save
    outputFile := "docs/basic_example.docx"
    outputDir := filepath.Dir(outputFile)
    
    if err := os.MkdirAll(outputDir, 0755); err != nil {
        outputFile = "basic_example.docx"
    }
    
    err := doc.Save(outputFile)
    if err != nil {
        log.Printf("Failed to save document: %v", err)
        return
    }
    
    fmt.Printf("✅ Document created successfully! Saved to: %s\n", outputFile)
}

🎯 Common Style Reference

WordZero provides the following predefined styles:

Style Constant Purpose Characteristics
style.StyleTitle Document title Large font, centered, bold
style.StyleSubtitle Subtitle Medium font, centered
style.StyleHeading1 Level 1 heading Large font, bold
style.StyleHeading2 Level 2 heading Medium font, bold
style.StyleHeading3 Level 3 heading Normal font, bold
style.StyleNormal Body text Default formatting
style.StyleQuote Quote Italic, indented
style.StyleCodeBlock Code block Monospace font
style.StyleListParagraph List paragraph Suitable for list items

💡 Best Practices

  1. Style First: Use predefined styles rather than manual formatting
  2. Error Handling: Always check error return values for save operations
  3. Directory Management: Ensure output directory exists before saving
  4. File Naming: Use meaningful filenames with .docx extension

⚠️ Common Issues

Document Save Failure

  • Check if output directory exists and has write permissions
  • Ensure filename uses .docx extension
  • Check if target file is open in another application

Styles Not Applied

  • Ensure correct style constants are used
  • Check if style is applied after adding text

Next Steps

After mastering the basic features, you can continue learning:


Continue to the next chapter to learn more advanced features!