### Run All Examples Source: https://github.com/mmonterroca/docxgo/blob/master/examples/VALIDATION_RESULTS.md Execute all example scripts located in the 'examples' directory. Ensure you are in the 'examples' directory before running. ```bash cd examples ./run_all_examples.sh ``` -------------------------------- ### Install docxgo Source: https://github.com/mmonterroca/docxgo/blob/master/README.md Install the docxgo library using go get. Ensure you have Go 1.21 or higher. ```bash go get github.com/mmonterroca/docxgo/v2 ``` -------------------------------- ### Run All Theme Examples Source: https://github.com/mmonterroca/docxgo/blob/master/examples/13_themes/README.md Executes all theme demonstration examples sequentially using a provided script. This will generate multiple documents. ```bash cd examples/13_themes ./run_all.sh ``` -------------------------------- ### Run All Examples - Generate Documents Source: https://github.com/mmonterroca/docxgo/blob/master/examples/README.md Execute all provided examples to generate .docx files. The generated documents will be placed in their respective example directories. ```bash ./run_all_examples.sh ``` -------------------------------- ### Run Custom Theme Example Source: https://github.com/mmonterroca/docxgo/blob/master/examples/13_themes/CUSTOM_THEMES_GUIDE.md Execute the custom theme example script to see theme approaches in action. ```bash # Clone and modify example go run custom_theme_example.go ``` -------------------------------- ### Run Table of Contents Example Source: https://github.com/mmonterroca/docxgo/blob/master/examples/03_toc/README.md Navigate to the example directory and execute the Go program to generate the DOCX file with a Table of Contents. ```bash cd examples/03_toc go run . ``` -------------------------------- ### Build Individual Example Source: https://github.com/mmonterroca/docxgo/blob/master/examples/VALIDATION_RESULTS.md Compile a specific example into an executable file before running it. This allows for creating standalone binaries of the examples. ```bash cd examples/01_basic go build -o example ./example ``` -------------------------------- ### Install docxgo CLI Source: https://github.com/mmonterroca/docxgo/blob/master/docs/CLI_GUIDE.md Install the docxgo CLI binary using go install. This command fetches the latest version and installs it globally. ```bash go install github.com/mmonterroca/docxgo/v2/cmd/docxgo@latest ``` -------------------------------- ### Run Individual Example Source: https://github.com/mmonterroca/docxgo/blob/master/examples/VALIDATION_RESULTS.md Execute a single example by navigating to its directory and running the main Go program. This is useful for testing specific functionalities. ```bash cd examples/01_basic go run main.go ``` -------------------------------- ### Run Theme System Example Source: https://github.com/mmonterroca/docxgo/blob/master/examples/README.md Execute the Go program to showcase the theme system. This example demonstrates applying preset and custom themes to generated documents. ```bash cd 13_themes && go run main.go ``` -------------------------------- ### Run Individual Theme Examples Source: https://github.com/mmonterroca/docxgo/blob/master/examples/13_themes/README.md Demonstrates how to run specific theme examples individually by navigating to their directories and executing the main Go program. This allows for focused testing of each theme type. ```bash # Main theme demonstration cd 01_main && go run main.go && cd .. # Custom theme cloning example cd 02_custom_theme && go run main.go && cd .. # External themes package example cd 03_external_themes && go run main.go && cd .. # Technical architecture showcase cd 04_tech_architecture && go run main.go && cd .. ``` -------------------------------- ### Run Main Themes Example Source: https://github.com/mmonterroca/docxgo/blob/master/examples/13_themes/README.md Command to navigate to the main themes example directory and run the Go program. This generates multiple DOCX files showcasing different preset themes. ```bash cd examples/13_themes/01_main go run main.go ``` -------------------------------- ### Run External Themes Example Source: https://github.com/mmonterroca/docxgo/blob/master/examples/13_themes/CUSTOM_THEMES_GUIDE.md Execute the external themes example script to demonstrate using external theme packages. ```bash # External themes example go run external_example.go ``` -------------------------------- ### Run Custom Theme Example Source: https://github.com/mmonterroca/docxgo/blob/master/examples/13_themes/README.md Command to navigate to the custom theme example directory and run the Go program. This generates DOCX files using cloned and custom-built themes. ```bash cd examples/13_themes/02_custom_theme go run main.go ``` -------------------------------- ### Install go-docx v2 Source: https://github.com/mmonterroca/docxgo/blob/master/docs/V2_API_GUIDE.md Install the latest version of go-docx v2 using go get. Ensure your Go version is 1.20 or higher. ```bash go get github.com/mmonterroca/docxgo/v2@latest ``` -------------------------------- ### Quick Test - Verify Compilation Source: https://github.com/mmonterroca/docxgo/blob/master/examples/README.md Run this script to quickly verify that all examples compile successfully. It tests all 15 working examples and reports the results. ```bash ./test_all.sh ``` -------------------------------- ### Run External Themes Example Source: https://github.com/mmonterroca/docxgo/blob/master/examples/13_themes/README.md Command to navigate to the external themes example directory and run the Go program. This demonstrates using themes provided by an external package. ```bash cd examples/13_themes/03_external_themes go run main.go ``` -------------------------------- ### Running Paragraph Border Test Example Source: https://github.com/mmonterroca/docxgo/blob/master/docs/PARAGRAPH_BORDERS.md Navigate to the test directory and run the Go program to see paragraph border examples in action. ```bash cd examples/13_themes/test_borders go run main.go ``` -------------------------------- ### Running the Example Source: https://github.com/mmonterroca/docxgo/blob/master/examples/05_styles/README.md Execute the main Go program to generate a DOCX file demonstrating style management. ```bash go run main.go ``` -------------------------------- ### Install docxgo v2.4.0 Source: https://github.com/mmonterroca/docxgo/blob/master/RELEASE_NOTES_v2.4.0.md Use this command to install the specific v2.4.0 version of the docxgo library. ```bash go get github.com/mmonterroca/docxgo/v2@v2.4.0 ``` -------------------------------- ### Run Technical Architecture Example Source: https://github.com/mmonterroca/docxgo/blob/master/examples/13_themes/README.md Command to navigate to the technical architecture example directory and run the Go program. This generates DOCX files with advanced features like PlantUML diagrams and syntax highlighting. ```bash cd examples/13_themes/04_tech_architecture go run main.go ``` -------------------------------- ### Install Golangci-Lint v2.x Locally Source: https://github.com/mmonterroca/docxgo/blob/master/.golangci-lint-version.md Instructions for installing a specific version of Golangci-Lint locally on macOS using Homebrew or by downloading a specific version script. ```bash # macOS (Homebrew) - installs latest v2.x brew install golangci-lint # Linux/macOS - specific version curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v2.5.0 # Verify installation golangci-lint --version ``` -------------------------------- ### Run Mail Merge Example Source: https://github.com/mmonterroca/docxgo/blob/master/examples/README.md Execute the Go program to demonstrate the mail merge functionality. This example uses a template engine to populate placeholders in documents. ```bash cd 14_mail_merge && go run main.go ``` -------------------------------- ### document.create RPC Request Example Source: https://github.com/mmonterroca/docxgo/blob/master/docs/CLI_GUIDE.md Example of a request to create a new Word document with specified options, content, and output format. ```json { "id": 1, "method": "document.create", "params": { "options": { "title": "My Report", "author": "Jane Smith", "pageSize": "A4", "margins": "normal", "theme": "Corporate" }, "content": [ { "type": "paragraph", "style": "Heading1", "runs": [{ "text": "Introduction" }] }, { "type": "paragraph", "runs": [ { "text": "This is " }, { "text": "bold", "bold": true }, { "text": " text." } ] } ], "output": "buffer" } } ``` -------------------------------- ### Example: Inline Image Source: https://github.com/mmonterroca/docxgo/blob/master/docs/V2_DESIGN.md Demonstrates how to add an inline image to a document with default sizing. ```go package main import ( "log" "github.com/signintech/docxgo/docx" ) func main() { doc := docx.New() // Create a sample image file (e.g., "sample.png") // ... code to create sample image ... // Add an inline image img, err := docx.NewImage("image1", "sample.png") if err != nil { log.Fatalf("Error creating image: %v", err) } ddoc.AddParagraph(&docx.Paragraph{Content: []docx.Content{img}}) err = doc.Save("inline_image.docx") if err != nil { log.Fatalf("Error saving document: %v", err) } log.Println("Document with inline image created successfully.") } ``` -------------------------------- ### Add Godoc Examples for Errors Source: https://github.com/mmonterroca/docxgo/blob/master/docs/ERROR_HANDLING.md Illustrates how to add usage examples to godoc for custom error types, demonstrating how to create and potentially check specific error conditions. ```go // Example: // // err := errors.InvalidArgument("Table.Row", "index", -1, // "row index out of bounds") // // // Error message: // // "operation=Table.Row | code=VALIDATION_ERROR | ... ``` -------------------------------- ### Example: Image Sized in Inches Source: https://github.com/mmonterroca/docxgo/blob/master/docs/V2_DESIGN.md Demonstrates adding an image with dimensions specified in inches. ```go package main import ( "log" "github.com/signintech/docxgo/docx" ) func main() { doc := docx.New() // Create a sample image file (e.g., "sample.png") // ... code to create sample image ... // Add an image sized in inches size := docx.ImageSize{Width: 2, Height: 1, Unit: "inches"} // 2 inches wide, 1 inch high img, err := docx.NewImageWithSize("image3", "sample.png", size) if err != nil { log.Fatalf("Error creating image: %v", err) } ddoc.AddParagraph(&docx.Paragraph{Content: []docx.Content{img}}) err = doc.Save("inches_sized_image.docx") if err != nil { log.Fatalf("Error saving document: %v", err) } log.Println("Document with inches sized image created successfully.") } ``` -------------------------------- ### Expected Output of Document Showcase Example Source: https://github.com/mmonterroca/docxgo/blob/master/examples/12_read_and_modify/README.md This snippet shows the expected console output when running the document showcase example, detailing the steps of creating, reading, inspecting, modifying, and saving a .docx file. ```text 📝 Step 1: Creating comprehensive showcase document... ✅ Created: 12_showcase_original.docx 📖 Step 2: Reading the document back... ✅ Document loaded successfully 🔍 Step 3: Inspecting document content... 📊 Document statistics: • Paragraphs: 25 • Tables: 1 📝 First 3 paragraphs: 1. "Document Showcase - All Features" 2. "This document demonstrates all capabilities of go-docx v2" 3. "" 📋 First table: • Rows: 4 • Columns: 3 ✏️ Step 4: Modifying the document... → Modifying existing paragraphs... → Modifying existing table... → Adding new section... ✅ Modifications applied 💾 Step 5: Saving modified document as '12_modified_document.docx'... ✅ Saved: 12_modified_document.docx 🎉 Complete! Compare the original and modified documents to see the changes. Generated files: 📄 12_showcase_original.docx (original showcase) 📄 12_modified_document.docx (modified version) ``` -------------------------------- ### Get and Apply External Theme Source: https://github.com/mmonterroca/docxgo/blob/master/examples/13_themes/CUSTOM_THEMES_GUIDE.md Fetch the published theme package using 'go get' and apply it to a new document instance. Ensure the import path matches the published module. ```go import "github.com/yourname/my-docx-themes" doc := docx.NewDocument() mydocxthemes.MyAwesomeTheme.ApplyTo(doc) ``` -------------------------------- ### Example: Custom Sized Image (Pixels) Source: https://github.com/mmonterroca/docxgo/blob/master/docs/V2_DESIGN.md Shows how to add an inline image with specific pixel dimensions. ```go package main import ( "log" "github.com/signintech/docxgo/docx" ) func main() { doc := docx.New() // Create a sample image file (e.g., "sample.png") // ... code to create sample image ... // Add an image with custom pixel dimensions size := docx.ImageSize{Width: 300, Height: 200, Unit: "pixels"} img, err := docx.NewImageWithSize("image2", "sample.png", size) if err != nil { log.Fatalf("Error creating image: %v", err) } ddoc.AddParagraph(&docx.Paragraph{Content: []docx.Content{img}}) err = doc.Save("custom_sized_image.docx") if err != nil { log.Fatalf("Error saving document: %v", err) } log.Println("Document with custom sized image created successfully.") } ``` -------------------------------- ### Get Document Info via RPC with Shell Source: https://github.com/mmonterroca/docxgo/blob/master/docs/CLI_GUIDE.md Perform multi-step workflows like opening and inspecting a document using 'docxgo rpc'. This example demonstrates sending multiple JSON requests in sequence. ```bash printf '{"id":1,"method":"document.open","params":{"filePath":"/path/to/doc.docx"}}\n{"id":2,"method":"document.inspect","params":{"documentId":"doc-1"}}\n' \ | docxgo rpc 2>/dev/null ``` -------------------------------- ### Verify docxgo Installation Source: https://github.com/mmonterroca/docxgo/blob/master/docs/CLI_GUIDE.md Verify that the docxgo CLI has been installed correctly by checking its version. This command should output the installed version number. ```bash docxgo version # 2.0.0-beta ``` -------------------------------- ### document.setMetadata RPC Request Example Source: https://github.com/mmonterroca/docxgo/blob/master/docs/CLI_GUIDE.md Example of a request to update the metadata of a document using its session ID. ```json { "id": 1, "method": "document.setMetadata", "params": { "documentId": "doc-1", "title": "Updated Report Title", "creator": "John Doe" } } ``` -------------------------------- ### Create and Configure a Custom Theme Source: https://github.com/mmonterroca/docxgo/blob/master/examples/13_themes/README.md Demonstrates how to create a new custom theme, configure its colors and fonts, and then apply it to a document builder. Ensure all required theme properties are set for a complete theme. ```go import "github.com/mmonterroca/docxgo/themes" import "github.com/mmonterroca/docxgo/domain" import "github.com/mmonterroca/docxgo" customTheme := themes.NewTheme( "my-theme", "My Custom Theme", "A theme tailored for my organization", ) // Configure colors colors := themes.ThemeColors{ Primary: domain.Color{R: 100, G: 100, B: 200}, Secondary: domain.Color{R: 150, G: 150, B: 250}, // ... configure all colors } customTheme = customTheme.WithColors(colors) // Configure fonts fonts := themes.ThemeFonts{ Body: "Georgia", Heading: "Helvetica", BodySize: 24, // 12pt // ... } customTheme = customTheme.WithFonts(fonts) // Use your custom theme builder := docx.NewDocumentBuilder( docx.WithTheme(customTheme), ) ``` -------------------------------- ### document.validate RPC Request Example Source: https://github.com/mmonterroca/docxgo/blob/master/docs/CLI_GUIDE.md Example of a request to validate the structure of a document using its session ID. ```json { "id": 1, "method": "document.validate", "params": { "documentId": "doc-1" } } ``` -------------------------------- ### document.inspect RPC Request Example Source: https://github.com/mmonterroca/docxgo/blob/master/docs/CLI_GUIDE.md Example of a request to inspect a document and retrieve its metadata, text, and structural information. ```json { "id": 1, "method": "document.inspect", "params": { "documentId": "doc-1" } } ``` -------------------------------- ### Quick Start: Direct Domain API Source: https://github.com/mmonterroca/docxgo/blob/master/docs/V2_API_GUIDE.md Demonstrates creating a document, adding a paragraph with a styled run, and saving the document using the Direct Domain API. ```go package main import ( "log" docx "github.com/mmonterroca/docxgo/v2" ) func main() { // Create document doc := docx.NewDocument() // Add paragraph para, err := doc.AddParagraph() if err != nil { log.Fatal(err) } // Add run with text run, err := para.AddRun() if err != nil { log.Fatal(err) } run.SetText("Hello, World!") run.SetBold(true) run.SetSize(28) // 14pt (size is in half-points) run.SetColor(docx.Red) // Save if err := doc.SaveAs("hello.docx"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Quick Start: Builder Pattern Source: https://github.com/mmonterroca/docxgo/blob/master/docs/V2_API_GUIDE.md Demonstrates creating a document with a title and author, adding a styled paragraph, and saving the document using the Builder Pattern. ```go package main import ( "log" docx "github.com/mmonterroca/docxgo/v2" ) func main() { // Create builder with options builder := docx.NewDocumentBuilder( docx.WithTitle("My Document"), docx.WithAuthor("John Doe"), ) // Add content with fluent API builder.AddParagraph(). Text("Hello, World!"). Bold(). FontSize(14). Color(docx.Red). Alignment(docx.AlignmentCenter). End() // Build and validate doc, err := builder.Build() if err != nil { log.Fatal(err) } // Save if err := doc.SaveAs("hello.docx"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### document.open RPC Request Example Source: https://github.com/mmonterroca/docxgo/blob/master/docs/CLI_GUIDE.md Example of a request to open an existing .docx document, either from a file path or base64 content. ```json { "id": 1, "method": "document.open", "params": { "filePath": "/path/to/existing.docx" } } ``` -------------------------------- ### Add Introduction Section Source: https://github.com/mmonterroca/docxgo/blob/master/coverage.html Demonstrates creating a document introduction with a main heading and a subheading, each with a descriptive paragraph. ```Go func addIntroduction(doc domain.Document) { // Heading 1 h1, _ := doc.AddParagraph() h1.SetStyle(domain.StyleIDHeading1) h1Run, _ := h1.AddRun() h1Run.AddText("1. Introduction") // Paragraph intro, _ := doc.AddParagraph() intro.SetStyle(domain.StyleIDNormal) introRun, _ := intro.AddRun() introRun.AddText("This document demonstrates the advanced features available in go-docx v2. It showcases sections, headers, footers, fields, and comprehensive style management.") doc.AddParagraph() // Heading 2 h2, _ := doc.AddParagraph() h2.SetStyle(domain.StyleIDHeading2) h2Run, _ := h2.AddRun() h2Run.AddText("1.1 Purpose") purpose, _ := doc.AddParagraph() purpose.SetStyle(domain.StyleIDNormal) purposeRun, _ := purpose.AddRun() purposeRun.AddText("The goal is to provide a complete example that developers can reference when building professional documents programmatically.") doc.AddParagraph() } ``` -------------------------------- ### v2 API Example: Direct API for Document Creation Source: https://github.com/mmonterroca/docxgo/blob/master/docs/V2_API_GUIDE.md Illustrates creating a document, adding a paragraph and run, and setting text properties (text, bold, color, size) directly using the v2 Direct API. Errors are handled immediately. ```go import docx "github.com/mmonterroca/docxgo/v2" doc := docx.NewDocument() para, _ := doc.AddParagraph() run, _ := para.AddRun() run.SetText("Hello") run.SetBold(true) run.SetColor(docx.Red) run.SetSize(28) // 14pt in half-points doc.SaveAs("output.docx") ``` -------------------------------- ### Conventional Commit Examples Source: https://github.com/mmonterroca/docxgo/blob/master/CONTRIBUTING.md Examples of commit messages following the Conventional Commits specification. These illustrate how to format different types of changes. ```bash git commit -m "feat: add HYPERLINK field support" git commit -m "fix: prevent empty RunProperties XML elements" git commit -m "docs: update TOC examples in README" git commit -m "test: add coverage for bookmark generation" ``` -------------------------------- ### v1: Basic Page Size Setup Source: https://github.com/mmonterroca/docxgo/blob/master/MIGRATION.md In v1, page size was set using basic methods. Direct section access was not available. ```go // v1 had basic page size methods doc.WithA4Page() doc.WithLetterPage() // No direct section access ``` -------------------------------- ### document.save RPC Request Example Source: https://github.com/mmonterroca/docxgo/blob/master/docs/CLI_GUIDE.md Example of a request to save or re-export a document using its session ID. Can specify output format and file path. ```json { "id": 1, "method": "document.save", "params": { "documentId": "doc-1", "output": "file", "filePath": "/path/to/new_output.docx" } } ``` -------------------------------- ### Initialize DocumentBuilder with Options Source: https://github.com/mmonterroca/docxgo/blob/master/coverage.html Shows how to initialize a new DocumentBuilder with custom default settings using functional options. ```go builder := docx.NewDocumentBuilder( docx.WithDefaultFont("Arial"), docx.WithPageSize(docx.A4), ) ``` -------------------------------- ### Create Document with Preset Theme Source: https://github.com/mmonterroca/docxgo/blob/master/examples/13_themes/README.md Demonstrates creating a new document and applying a preset theme like 'Corporate'. Ensure the docxgo and themes packages are imported. ```go import ( docx "github.com/mmonterroca/docxgo/v2" "github.com/mmonterroca/docxgo/themes" ) // Create a document with a theme builder := docx.NewDocumentBuilder( docx.WithTheme(themes.Corporate), ) builder.AddParagraph(). Text("Hello, World!"). End() doc, _ := builder.Build() doc.SaveAs("output.docx") ``` -------------------------------- ### Create Document Builder with Options Source: https://github.com/mmonterroca/docxgo/blob/master/coverage.html Initializes a new document builder with various configuration options. Use options like WithTitle, WithAuthor, and WithDefaultFont to customize the document. ```go builder := docx.NewDocumentBuilder( docx.WithTitle("Builder Pattern Demo"), docx.WithAuthor("go-docx v2"), docx.WithDefaultFont("Calibri"), docx.WithDefaultFontSize(22), // 11pt = 22 half-points docx.WithPageSize(docx.A4), docx.WithMargins(docx.NormalMargins), ) ``` -------------------------------- ### Create a Basic Document Source: https://github.com/mmonterroca/docxgo/blob/master/docs/V2_DESIGN.md Generates a simple .docx file with a centered, bold, and large-font 'Hello, World!' paragraph. Saves the document as 'hello.docx'. ```go doc := docx.NewDocument() doc.AddParagraph(). Text("Hello, World!"). FontSize(16). Bold(). Center(). End() finalDoc, _ := doc.Build() finalDoc.SaveAs("hello.docx") ``` -------------------------------- ### Example: Error Wrapping with Context Source: https://github.com/mmonterroca/docxgo/blob/master/docs/ERROR_HANDLING.md This example illustrates how to wrap errors with context using fmt.Errorf and %w. It adds information about the operation that failed, allowing for easier debugging. ```go func (zw *ZipWriter) WriteDocument(serializer *serializer.DocumentSerializer) error { if err := zw.writeContentTypes(); err != nil { return fmt.Errorf("write content types: %w", err) } if err := zw.writeMainDocument(); err != nil { return fmt.Errorf("write main document: %w", err) } return nil } ``` -------------------------------- ### Create a Custom Theme Source: https://github.com/mmonterroca/docxgo/blob/master/themes/README.md Initialize a new theme with a unique ID, name, and description. Define custom colors, fonts, spacing, and heading styles to brand your documents. ```go customTheme := themes.NewTheme( "my-brand", "My Brand Theme", "Custom theme for company branding", ) // Define colors colors := themes.ThemeColors{ Primary: domain.Color{R: 0, G: 102, B: 204}, // Brand blue Secondary: domain.Color{R: 51, G: 153, B: 255}, // Light blue Accent: domain.Color{R: 255, G: 102, B: 0}, // Brand orange Background: domain.Color{R: 255, G: 255, B: 255}, Text: domain.Color{R: 33, G: 33, B: 33}, TextLight: domain.Color{R: 117, G: 117, B: 117}, Heading: domain.Color{R: 0, G: 102, B: 204}, Muted: domain.Color{R: 230, G: 230, B: 230}, Success: domain.Color{R: 0, G: 180, B: 0}, Warning: domain.Color{R: 255, G: 180, B: 0}, Error: domain.Color{R: 220, G: 0, B: 0}, } customTheme = customTheme.WithColors(colors) // Define fonts fonts := themes.ThemeFonts{ Body: "Open Sans", Heading: "Montserrat", Monospace: "Fira Code", BodySize: 22, // 11pt SmallSize: 18, // 9pt } customTheme = customTheme.WithFonts(fonts) // Define spacing spacing := themes.ThemeSpacing{ ParagraphBefore: 0, ParagraphAfter: 200, // 10pt LineSpacing: 240, // Single HeadingBefore: 320, // 16pt HeadingAfter: 160, // 8pt SectionSpacing: 480, // 24pt } customTheme = customTheme.WithSpacing(spacing) // Define heading styles headings := themes.ThemeHeadings{ H1Size: 36, // 18pt H2Size: 30, // 15pt H3Size: 26, // 13pt H1Bold: true, H2Bold: true, H3Bold: false, H1Uppercase: false, UseColor: true, } customTheme = customTheme.WithHeadings(headings) // Note: WithHeadings not yet implemented ``` -------------------------------- ### Initialize Document Builder with Custom Options Source: https://github.com/mmonterroca/docxgo/blob/master/coverage.html Demonstrates initializing a new document builder with various custom options like title, author, subject, default font, font size, page size, and margins. ```Go // Create document builder with custom options builder := docx.NewDocumentBuilder( docx.WithTitle("Product Catalog"), docx.WithAuthor("ACME Corporation"), docx.WithSubject("Q1 2024 Product Lineup"), docx.WithDefaultFont("Arial"), docx.WithDefaultFontSize(22), // 11pt = 22 half-points docx.WithPageSize(docx.Letter), docx.WithMargins(docx.NormalMargins), ) ``` -------------------------------- ### Create and Format a Simple Table Source: https://github.com/mmonterroca/docxgo/blob/master/coverage.html Demonstrates how to create a 3x3 table with headers and data, applying bold formatting and cell shading. ```Go // Create a simple 3x3 table builder.AddTable(3, 3). Row(0). Cell(0).Text("Header 1").Bold().End(). Cell(1).Text("Header 2").Bold().End(). Cell(2).Text("Header 3").Bold().End(). End(). Row(1). Cell(0).Text("Row 1, Col 1").End(). Cell(1).Text("Row 1, Col 2").End(). Cell(2).Text("Row 1, Col 3").End(). End(). Row(2). Cell(0).Text("Row 2, Col 1").End(). Cell(1).Text("Row 2, Col 2").Shading(docx.Blue).End(). Cell(2).Text("Row 2, Col 3").End(). End(). End() ``` -------------------------------- ### Start docxgo RPC Mode Source: https://github.com/mmonterroca/docxgo/blob/master/docs/CLI_GUIDE.md Start the docxgo CLI in RPC mode to handle multiple newline-delimited JSON requests from stdin and write responses to stdout. The process remains active. ```bash docxgo rpc ``` -------------------------------- ### Basic Document Creation with Builder Pattern Source: https://github.com/mmonterroca/docxgo/blob/master/examples/README.md Demonstrates document creation with a fluent builder API, including options for title, author, font, margins, and fluent paragraph building with mixed formatting. Also shows simple table creation and the use of predefined color constants. ```bash cd 01_basic && go run main.go ``` -------------------------------- ### Tolerated Header Error Example Source: https://github.com/mmonterroca/docxgo/blob/master/docs/TROUBLESHOOTING_DOCX_VALIDATION.md An example of a 'tblLook in Headers' error that is typically tolerated by Microsoft Word. This error relates to attributes from newer Word versions not being recognized by older schema validators. ```text The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:firstRow' attribute is not declared. Part: /word/headerX.xml ``` -------------------------------- ### Create a New Theme from Scratch Source: https://github.com/mmonterroca/docxgo/blob/master/examples/13_themes/CUSTOM_THEMES_GUIDE.md Build a completely new theme by defining its ID, name, description, colors, fonts, and spacing. This method offers full control over the theme's appearance. ```go package main import ( "github.com/mmonterroca/docxgo/domain" "github.com/mmonterroca/docxgo/themes" ) func main() { // Create new theme brandTheme := themes.NewTheme( "my-brand", // Internal ID "My Brand Theme", // Display name "Custom brand colors" // Description ) // Define all colors colors := themes.ThemeColors{ Primary: domain.Color{R: 0, G: 102, B: 204}, Secondary: domain.Color{R: 51, G: 153, B: 255}, Accent: domain.Color{R: 255, G: 102, B: 0}, Background: domain.Color{R: 255, G: 255, B: 255}, Text: domain.Color{R: 33, G: 33, B: 33}, TextLight: domain.Color{R: 117, G: 117, B: 117}, Heading: domain.Color{R: 0, G: 102, B: 204}, Muted: domain.Color{R: 230, G: 230, B: 230}, Success: domain.Color{R: 0, G: 180, B: 0}, Warning: domain.Color{R: 255, G: 180, B: 0}, Error: domain.Color{R: 220, G: 0, B: 0}, } brandTheme = brandTheme.WithColors(colors) // Define fonts fonts := themes.ThemeFonts{ Body: "Open Sans", Heading: "Montserrat", Monospace: "Fira Code", BodySize: 22, // 11pt (sizes are in half-points) SmallSize: 18, // 9pt } brandTheme = brandTheme.WithFonts(fonts) // Define spacing (in twips: 1/1440 inch, 20 twips = 1pt) spacing := themes.ThemeSpacing{ ParagraphBefore: 0, ParagraphAfter: 200, // 10pt LineSpacing: 260, // 1.3x line height HeadingBefore: 320, // 16pt HeadingAfter: 160, // 8pt SectionSpacing: 480, // 24pt } brandTheme = brandTheme.WithSpacing(spacing) // Use it doc := docx.NewDocument() brandTheme.ApplyTo(doc) } ``` -------------------------------- ### Create and Build a Document Source: https://github.com/mmonterroca/docxgo/blob/master/coverage.html Demonstrates how to create a new document builder, add a formatted paragraph, and then build and save the document. Handles potential errors during the build process. ```go builder := docx.NewDocumentBuilder() builder.AddParagraph(). Text("Hello, World!"). Bold(). FontSize(14). End() doc, err := builder.Build() if err != nil { log.Fatal(err) } doc.SaveAs("output.docx") ``` -------------------------------- ### Create New Document Source: https://github.com/mmonterroca/docxgo/blob/master/coverage.html Initializes a new, empty Word document with default settings and an empty body. This is the starting point for document creation. ```go // NewDocument creates a new empty Word document. // The document is created with default settings and an empty body. // // Example: // // doc := docx.NewDocument() // para, _ := doc.AddParagraph() // run, _ := para.AddRun() // run.AddText("Hello, World!") // doc.SaveToFile("hello.docx") func NewDocument() domain.Document { return core.NewDocument() } ``` -------------------------------- ### Run External Template Mail Merge Example Source: https://github.com/mmonterroca/docxgo/blob/master/examples/README.md Execute the Go program to demonstrate using an external Word document as a mail merge template. This example supports custom delimiters and preserves formatting. ```bash cd 15_external_template && go run main.go ``` -------------------------------- ### v1 API Example: Creating and Formatting Text Source: https://github.com/mmonterroca/docxgo/blob/master/docs/V2_API_GUIDE.md This snippet shows how to create a new document, add a paragraph, add text to a run, and apply formatting like bold, color, and size using the legacy v1 API. ```go import "github.com/fumiama/go-docx" doc := docx.New() para := doc.AddParagraph() run := para.AddText("Hello") run.Bold().Color("FF0000").Size("28") doc.WriteTo(file) ``` -------------------------------- ### Get Indentation Source: https://github.com/mmonterroca/docxgo/blob/master/coverage.html Retrieves the indentation settings for a paragraph. ```go // Indentation returns the paragraph indentation. func (ps *paragraphStyle) Indentation() domain.Indentation { ps.mu.RLock() defer ps.mu.RUnlock() return ps.indentation } ``` -------------------------------- ### Update Document Creation (v1 vs v2) Source: https://github.com/mmonterroca/docxgo/blob/master/MIGRATION.md Illustrates the different methods for creating a new document in v1 and v2. ```go // v1 doc := docx.New() // or doc := docx.New().WithDefaultTheme() // v2 doc := core.NewDocument() ``` -------------------------------- ### BuilderError Get Method Source: https://github.com/mmonterroca/docxgo/blob/master/coverage.html Retrieves the captured error from BuilderError. ```go // Get returns the captured error (may be nil). func (b *BuilderError) Get() error { return b.err } ``` -------------------------------- ### Create Simple Document (v1 API) Source: https://github.com/mmonterroca/docxgo/blob/master/MIGRATION.md Demonstrates creating a basic document with a single paragraph and text using the v1 API. ```go func createDocV1() error { doc := docx.New() para := doc.AddParagraph() para.AddText("Hello World").Bold().Size("24") f, _ := os.Create("output.docx") defer f.Close() doc.WriteTo(f) return nil } ``` -------------------------------- ### Get Paragraph Indentation Source: https://github.com/mmonterroca/docxgo/blob/master/coverage.html Returns the indentation settings for the paragraph. ```go // Indent returns the paragraph's indentation settings. func (p *paragraph) Indent() domain.Indentation { return p.indent ``` -------------------------------- ### Create a Go Module for Themes Source: https://github.com/mmonterroca/docxgo/blob/master/examples/13_themes/CUSTOM_THEMES_GUIDE.md Initialize a new Go module for your custom docxgo themes. This sets up the project structure for publishing. ```bash mkdir my-docx-themes cd my-docx-themes go mod init github.com/yourname/my-docx-themes ``` -------------------------------- ### Get Image ID Source: https://github.com/mmonterroca/docxgo/blob/master/coverage.html Returns the unique identifier for the image. ```go // ID returns the unique image ID. func (img *docxImage) ID() string { return img.id } ``` -------------------------------- ### Functional Options for Configuration Source: https://github.com/mmonterroca/docxgo/blob/master/docs/V2_DESIGN.md Demonstrates the functional options pattern for configuring document creation. This allows for flexible and readable initialization of `Config` structs by passing options to `NewDocument`. ```go package docx type Config struct { DefaultFont string DefaultFontSize int PageSize PageSize Margins Margins StrictValidation bool Logger Logger } type Option func(*Config) // WithDefaultFont sets the default font func WithDefaultFont(font string) Option { return func(c *Config) { c.DefaultFont = font } } // WithPageSize sets the page size func WithPageSize(size PageSize) Option { return func(c *Config) { c.PageSize = size } } // WithStrictValidation enables strict validation func WithStrictValidation() Option { return func(c *Config) { c.StrictValidation = true } } // Usage: doc := docx.NewDocument( docx.WithDefaultFont("Calibri"), docx.WithPageSize(docx.A4), docx.WithStrictValidation(), ) ``` -------------------------------- ### Get Table Width Source: https://github.com/mmonterroca/docxgo/blob/master/coverage.html Retrieves the current width configuration of the table. ```go func (t *table) Width() domain.TableWidth { return t.width } ``` -------------------------------- ### Remove v1 and Add v2 Dependencies Source: https://github.com/mmonterroca/docxgo/blob/master/MIGRATION.md Use 'go get' to remove the old v1 dependency and add the new v2 dependency. ```bash # Remove v1 go get github.com/fumiama/go-docx@none # Add v2 go get github.com/mmonterroca/docxgo/v2@latest ``` -------------------------------- ### Get All Table Rows Source: https://github.com/mmonterroca/docxgo/blob/master/coverage.html Returns a copy of all rows currently in the table. ```go func (t *table) Rows() []domain.TableRow { rows := make([]domain.TableRow, len(t.rows)) copy(rows, t.rows) return rows } ``` -------------------------------- ### Get Field Property Source: https://github.com/mmonterroca/docxgo/blob/master/coverage.html Retrieves the value of a specific field property. ```go func (f *docxField) GetProperty(key string) (string, bool) { f.mu.RLock() defer f.mu.RUnlock() value, ok := f.properties[key] return value, ok } ``` -------------------------------- ### Get Document Metadata Source: https://github.com/mmonterroca/docxgo/blob/master/coverage.html Returns the document's metadata object. ```go // Metadata returns the document's metadata. func (d *document) Metadata() *domain.Metadata { return d.metadata } ``` -------------------------------- ### Apply a Preset Theme to an Existing Document Source: https://github.com/mmonterroca/docxgo/blob/master/examples/13_themes/README.md Demonstrates how to open an existing DOCX file and apply a different preset theme to it, then save the restyled document. This allows for quick style updates. ```go // Open an existing document doc, _ := docx.OpenDocument("existing.docx") // Apply a theme themes.Modern.ApplyTo(doc) // Save with new styling doc.SaveAs("restyled.docx") ``` -------------------------------- ### Get Line Spacing Source: https://github.com/mmonterroca/docxgo/blob/master/coverage.html Retrieves the current line spacing value for a paragraph. ```go // LineSpacing returns the line spacing value. func (ps *paragraphStyle) LineSpacing() int { ps.mu.RLock() defer ps.mu.RUnlock() return ps.lineSpacing } ``` -------------------------------- ### Create Document with Options using Builder Pattern Source: https://github.com/mmonterroca/docxgo/blob/master/examples/v2_README.md Demonstrates creating a new document with custom title, default font, and page size using the Builder Pattern. This is the recommended approach for most use cases. ```Go package main import docx "github.com/mmonterroca/docxgo/v2" func main() { // Create document with options doc, err := docx.NewDocumentBuilder( docx.WithTitle("My Document"), docx.WithDefaultFont("Arial", 11), docx.WithPageSize(docx.PageSizeA4), ).Build() // Add content using fluent API doc.AddParagraph(). Text("Hello, World!"). Bold(). Color(docx.Blue). FontSize(14). Alignment(docx.AlignmentCenter). End() // Save doc.SaveToFile("output.docx") } ``` -------------------------------- ### Get Table Cell Borders Source: https://github.com/mmonterroca/docxgo/blob/master/coverage.html Retrieves the border settings for the table cell. ```go // Borders returns the cell borders. func (c *tableCell) Borders() domain.TableBorders { return c.borders } ``` -------------------------------- ### Main Document Flow Source: https://github.com/mmonterroca/docxgo/blob/master/examples/07_advanced/README.md Illustrates the main sequence of function calls for setting up a document, including header, footer, cover page, ToC, introduction, features, examples, and conclusion. ```go // Main flow setupHeader(header) setupFooter(footer) addCoverPage(doc) addTableOfContents(doc) addIntroduction(doc) addFeatures(doc) addExamples(doc) addConclusion(doc) ``` -------------------------------- ### Run Read and Modify Documents Example Source: https://github.com/mmonterroca/docxgo/blob/master/examples/README.md Execute the Go program to demonstrate reading and modifying .docx files. This involves a complete read/modify/write workflow. ```bash cd 12_read_and_modify && go run main.go ``` -------------------------------- ### Get Table Alignment Source: https://github.com/mmonterroca/docxgo/blob/master/coverage.html Retrieves the current horizontal alignment setting for the table. ```go func (t *table) Alignment() domain.Alignment { return t.alignment } ``` -------------------------------- ### Get Table Column Count Source: https://github.com/mmonterroca/docxgo/blob/master/coverage.html Returns the number of columns defined for the table. ```go func (t *table) ColumnCount() int { return t.cols } ``` -------------------------------- ### Publish Theme to GitHub Source: https://github.com/mmonterroca/docxgo/blob/master/examples/13_themes/CUSTOM_THEMES_GUIDE.md Initialize a Git repository, commit your theme files, set up a remote origin, and push to GitHub. Tagging is recommended for versioning. ```bash git init git add . git commit -m "Initial commit" git remote add origin https://github.com/yourname/my-docx-themes git push -u origin main git tag v1.0.0 git push --tags ``` -------------------------------- ### Get Paragraph Alignment Source: https://github.com/mmonterroca/docxgo/blob/master/coverage.html Returns the current horizontal alignment setting for the paragraph. ```go // Alignment returns the paragraph's horizontal alignment. func (p *paragraph) Alignment() domain.Alignment { return p.alignment ``` -------------------------------- ### v2 API Example: Builder Pattern for Document Creation Source: https://github.com/mmonterroca/docxgo/blob/master/docs/V2_API_GUIDE.md Demonstrates creating a document, adding a paragraph with formatted text (bold, color, font size) using the v2 Builder pattern. Errors are accumulated and handled during the Build() phase. ```go import docx "github.com/mmonterroca/docxgo/v2" builder := docx.NewDocumentBuilder() builder.AddParagraph(). Text("Hello"). Bold(). Color(docx.Red). FontSize(14). End() doc, _ := builder.Build() doc.SaveAs("output.docx") ``` -------------------------------- ### Get Image Format Source: https://github.com/mmonterroca/docxgo/blob/master/coverage.html Returns the format of the image (e.g., JPEG, PNG). ```go // Format returns the image format. func (img *docxImage) Format() domain.ImageFormat { return img.format } ``` -------------------------------- ### Basic Document Creation and Writing Source: https://github.com/mmonterroca/docxgo/blob/master/coverage.html Demonstrates the fundamental process of creating a new Word document, adding a paragraph with text, and writing the document content to a memory buffer. ```go // Command test_write demonstrates basic document creation and writing using go-docx. package main import ( "bytes" "fmt" "github.com/mmonterroca/docxgo/internal/core" ) func main() { // Create document doc := core.NewDocument() para, _ := doc.AddParagraph() run, _ := para.AddRun() if err := run.SetText("Hello, World!"); err != nil { fmt.Printf("Error setting text: %v\n", err) return } // Write to buffer var buf bytes.Buffer if _, err := doc.WriteTo(&buf); err != nil { fmt.Printf("Error: %v\n", err) return } fmt.Printf("Generated .docx file: %d bytes\n", buf.Len()) fmt.Println("Success! File written to memory") } ``` -------------------------------- ### Get Document Style Manager Source: https://github.com/mmonterroca/docxgo/blob/master/coverage.html Returns the style manager associated with this document. ```go // StyleManager returns the style manager for this document. func (d *document) StyleManager() domain.StyleManager { return d.styleManager } ``` -------------------------------- ### Get Default Section Source: https://github.com/mmonterroca/docxgo/blob/master/examples/06_sections/README.md Retrieve the default section of a document to begin configuration. ```go section, err := doc.DefaultSection() if err != nil { log.Fatal(err) } ``` -------------------------------- ### Create a Simple Document Source: https://github.com/mmonterroca/docxgo/blob/master/docs/README.md Use DocumentBuilder to create a new document and add a basic paragraph. Save the document to a file. ```go // See: V2_API_GUIDE.md - Quick Start builder := docx.NewDocumentBuilder() builder.AddParagraph().Text("Hello, World!").End() doc, _ := builder.Build() doc.SaveAs("hello.docx") ``` -------------------------------- ### Create a Calendar-Style Table Layout Source: https://github.com/mmonterroca/docxgo/blob/master/coverage.html Shows how to create a 7x7 table and use cell merging to simulate a monthly calendar layout, including a header for the month and day names. ```Go now := time.Now() builder.AddTable(7, 7). Style(domain.TableStyleMediumShading). Row(0). Cell(0).Text(now.Format("January 2006")).Bold().Merge(7, 1).End(). End(). Row(1). Cell(0).Text("Sun").Bold().End(). Cell(1).Text("Mon").Bold().End(). Cell(2).Text("Tue").Bold().End(). Cell(3).Text("Wed").Bold().End(). Cell(4).Text("Thu").Bold().End(). Cell(5).Text("Fri").Bold().End(). Cell(6).Text("Sat").Bold().End(). End(). Row(2). Cell(0).Text("").End(). Cell(1).Text("").End(). Cell(2).Text("1").End(). Cell(3).Text("2").End(). Cell(4).Text("3").End(). Cell(5).Text("4").End(). Cell(6).Text("5").End(). End(). Row(3). Cell(0).Text("6").End(). Cell(1).Text("7").End(). Cell(2).Text("8").End(). Cell(3).Text("9").End(). Cell(4).Text("10").End(). Cell(5).Text("11").End(). Cell(6).Text("12").End(). End(). Row(4). Cell(0).Text("13").End(). Cell(1).Text("14").End(). Cell(2).Text("15").End(). Cell(3).Text("16").End(). Cell(4).Text("17").End(). Cell(5).Text("18").End(). Cell(6).Text("19").End(). End(). Row(5). Cell(0).Text("20").End(). Cell(1).Text("21").End(). Cell(2).Text("22").End(). Cell(3).Text("23").End(). Cell(4).Text("24").End(). Cell(5).Text("25").End(). Cell(6).Text("26").End(). End(). Row(6). Cell(0).Text("27").End(). Cell(1).Text("28").End(). Cell(2).Text("29").End(). Cell(3).Text("30").End(). Cell(4).Text("31").End(). Cell(5).Text("").End(). Cell(6).Text("").End(). End(). End() ```