### Example Import Grouping Source: https://github.com/unidoc/unioffice/wiki/UniOffice-Developer-Guide An example demonstrating the recommended import grouping style with specific packages. ```go import ( "errors" "io/ioutil" "strings" "golang.org/x/text/unicode/norm" "github.com/unidoc/unioffice/color" "github.com/unidoc/unioffice/common" "github.com/unidoc/unioffice/measurement" "github.com/unidoc/unioffice/presentation" "github.com/unidoc/unioffice/schema/soo/dml" ) ``` -------------------------------- ### License Setup Source: https://context7.com/unidoc/unioffice/llms.txt Before using any document operations, set the metered API key. Without a valid license, the library will not save or read documents. ```APIDOC ## License Setup Set the metered API key before using any document operation. Without a valid license the library will refuse to save or read documents. ```go import "github.com/unidoc/unioffice/v2/common/license" func init() { // Metered key from https://cloud.unidoc.io (free tier) if err := license.SetMeteredKey("your-api-key-here"); err != nil { panic(err) } } ``` ``` -------------------------------- ### Correct Blank Line Usage in Function Source: https://github.com/unidoc/unioffice/wiki/UniOffice-Developer-Guide Demonstrates correct placement of blank lines within a function block, avoiding them at the start. ```go func x() { return } // and func x() { if 2 > 1 { return } } ``` -------------------------------- ### Open and Edit an Existing Word Document Source: https://context7.com/unidoc/unioffice/llms.txt Opens an existing .docx file for reading or editing. The example demonstrates iterating through paragraphs and runs to extract text, and then modifying the content of the first paragraph. Remember to close the document after operations. ```go package main import ( "fmt" "github.com/unidoc/unioffice/v2/common/license" "github.com/unidoc/unioffice/v2/document" "log" ) func main() { _ = license.SetMeteredKey("your-api-key") doc, err := document.Open("existing.docx") if err != nil { log.Fatal(err) } defer doc.Close() // Iterate paragraphs and extract text for _, para := range doc.Paragraphs() { for _, run := range para.Runs() { fmt.Print(run.Text()) } fmt.Println() } // Edit: replace all runs in first paragraph if len(doc.Paragraphs()) > 0 { p := doc.Paragraphs()[0] for _, r := range p.Runs() { r.ClearContent() r.SetText("Replaced text") break } } if err := doc.SaveToFile("modified.docx"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Set unioffice License Key Source: https://context7.com/unidoc/unioffice/llms.txt Set the metered API key before using any document operation. Without a valid license, the library will refuse to save or read documents. This setup is typically done in an init function. ```go import "github.com/unidoc/unioffice/v2/common/license" func init() { // Metered key from https://cloud.unidoc.io (free tier) if err := license.SetMeteredKey("your-api-key-here"); err != nil { panic(err) } } ``` -------------------------------- ### Add Slide from Layout - Go Source: https://context7.com/unidoc/unioffice/llms.txt Adds a new slide to a presentation using a predefined layout from a template. Requires opening a template file and getting a layout by name. ```go package main import ( "github.com/unidoc/unioffice/v2/common/license" "github.com/unidoc/unioffice/v2/presentation" "github.com/unidoc/unioffice/v2/schema/soo/pml" "log" ) func main() { _ = license.SetMeteredKey("your-api-key") prs, err := presentation.OpenTemplate("template.pptx") if err != nil { log.Fatal(err) } defer prs.Close() // Get layout by name layout, err := prs.GetLayoutByName("Title and Content") if err != nil { log.Fatal(err) } slide, err := prs.AddDefaultSlideWithLayout(layout) if err != nil { log.Fatal(err) } // Fill title placeholder title, err := slide.GetPlaceholder(pml.ST_PlaceholderTypeTitle) if err == nil { title.SetText("Quarterly Results") } // Fill body placeholder body, err := slide.GetPlaceholder(pml.ST_PlaceholderTypeBody) if err == nil { body.Clear() p := body.AddParagraph() p.AddRun().SetText("• Revenue: $1.2M") p2 := body.AddParagraph() p2.AddRun().SetText("• Growth: +15%") } if err := prs.SaveToFile("from_template.pptx"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Iterator Declaration Source: https://github.com/unidoc/unioffice/wiki/UniOffice-Developer-Guide Example of a loop iterator where the initial value matters. ```go for i := 0; i < 20; i++ { ... } ``` -------------------------------- ### Extract Text from Presentation - Go Source: https://context7.com/unidoc/unioffice/llms.txt Extracts all text content from a presentation file, organizing it by slide and preserving spatial order. Also provides an option to get all text as a single string. ```go package main import ( "fmt" "github.com/unidoc/unioffice/v2/common/license" "github.com/unidoc/unioffice/v2/presentation" "log" ) func main() { _ = license.SetMeteredKey("your-api-key") prs, err := presentation.Open("presentation.pptx") if err != nil { log.Fatal(err) } defer prs.Close() extracted := prs.ExtractText() for i, slideText := range extracted.Slides { fmt.Printf("=== Slide %d ===\n", i+1) for _, item := range slideText.Items { if item.Text != "" { fmt.Printf(" %s\n", item.Text) } } } // Or get all text as a single string: fmt.Println("\nAll text:") fmt.Println(extracted.Text()) } ``` -------------------------------- ### Godoc Comment Example for Go Functions Source: https://github.com/unidoc/unioffice/wiki/UniOffice-Developer-Guide Exported names in Go should have godoc-styled comments. When referencing a variable within the comment, enclose the variable name in backticks. ```go // CopySheet copies the existing sheet at index `ind` and puts its copy with the name `copiedSheetName`. func (wb *Workbook) CopySheet(ind int, copiedSheetName string) (Sheet, error) { ``` -------------------------------- ### Create or Open a Presentation (.pptx) Source: https://context7.com/unidoc/unioffice/llms.txt Creates a new blank presentation or opens an existing .pptx file. The presentation manages slides, masters, and layouts. Ensure you have a valid license key set. ```go package main import ( "github.com/unidoc/unioffice/v2/common/license" "github.com/unidoc/unioffice/v2/presentation" "github.com/unidoc/unioffice/v2/measurement" "log" ) func main() { _ = license.SetMeteredKey("your-api-key") prs := presentation.New() defer prs.Close() // Add a slide slide := prs.AddSlide() // Add a text box tb := slide.AddTextBox() tb.Properties().SetWidth(8 * measurement.Inch) tb.Properties().SetHeight(1.5 * measurement.Inch) tb.Properties().SetPosition(1*measurement.Inch, 1*measurement.Inch) para := tb.AddParagraph() run := para.AddRun() run.Properties().SetBold(true) run.Properties().SetSize(36 * measurement.Point) run.SetText("Welcome to unioffice Presentations") // Body text box body := slide.AddTextBox() body.Properties().SetWidth(8 * measurement.Inch) body.Properties().SetHeight(4 * measurement.Inch) body.Properties().SetPosition(1*measurement.Inch, 3*measurement.Inch) bp := body.AddParagraph() bp.AddRun().SetText("Create .pptx files programmatically with Go.") if err := prs.SaveToFile("presentation.pptx"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Create and Save Spreadsheet with Formulas Source: https://context7.com/unidoc/unioffice/llms.txt Creates a new XLSX workbook, adds sheets, populates cells with data and formulas, and saves the file. Also demonstrates opening an existing workbook. Requires a license key. ```go package main import ( "fmt" "github.com/unidoc/unioffice/v2/common/license" "github.com/unidoc/unioffice/v2/spreadsheet" "log" ) func main() { _ = license.SetMeteredKey("your-api-key") // Create new workbook wb := spreadsheet.New() defer wb.Close() sheet := wb.AddSheet() sheet.SetName("Sales") // Set column headers headers := []string{"Product", "Q1", "Q2", "Q3", "Q4", "Total"} row := sheet.AddRow() for i, h := range headers { cell := row.AddCell() cell.SetString(h) _ = i } // Set data rows data := [][]interface{}{ {"Widget A", 1500.0, 1800.0, 2100.0, 2400.0}, {"Widget B", 800.0, 950.0, 1100.0, 1300.0}, } for _, rowData := range data { r := sheet.AddRow() for j, v := range rowData { c := r.AddCell() switch val := v.(type) { case string: c.SetString(val) case float64: c.SetNumber(val) } // Add formula for Total column if j == 4 { totalCell := r.AddCell() // Formula references B through E of this row // e.g., =SUM(B2:E2) totalCell.SetFormulaRaw(fmt.Sprintf("SUM(B%d:E%d)", r.RowNumber(), r.RowNumber())) } } } if err := wb.SaveToFile("sales.xlsx"); err != nil { log.Fatal(err) } // Open existing existing, err := spreadsheet.Open("sales.xlsx") if err != nil { log.Fatal(err) } defer existing.Close() fmt.Println("Sheets:", existing.SheetCount()) } ``` -------------------------------- ### Run Tests with Options Source: https://github.com/unidoc/unioffice/blob/master/README.md Explains how to use the `run_test.sh` script for testing, including options to save baselines, run in verbose mode, or target specific tests. ```bash # Save a baseline, updates all the test result (if required). -s # Run the test in verbose mode. -v # Run a specific test name. For example -t AddImage would be running a TestAddImage test. -t or --testname [test name] ``` -------------------------------- ### Run Go Vet Source: https://github.com/unidoc/unioffice/wiki/UniOffice-Developer-Guide Check the UniOffice project for suspicious constructs and potential errors using the go vet tool. Ensure no issues are reported. ```bash go vet github.com/unidoc/unioffice/... ``` -------------------------------- ### Go File License Header Source: https://github.com/unidoc/unioffice/wiki/UniOffice-Developer-Guide Ensure each Go file begins with the specified license header, followed by the package declaration. This is a mandatory requirement for all source files. ```go // Copyright 2017 FoxyUtils ehf. All rights reserved. // // Use of this source code is governed by the terms of the Affero GNU General // Public License version 3.0 as published by the Free Software Foundation and // appearing in the file LICENSE included in the packaging of this file. A // commercial license can be purchased by contacting sales@baliance.com. package ... ``` -------------------------------- ### Set Presentation Slide Size in Go Source: https://context7.com/unidoc/unioffice/llms.txt Demonstrates setting slide dimensions using predefined constants or custom EMU values. Ensure a license key is set before creating a presentation. ```go package main import ( "github.com/unidoc/unioffice/v2/common/license" "github.com/unidoc/unioffice/v2/presentation" "log" ) func main() { _ = license.SetMeteredKey("your-api-key") prs := presentation.New() defer prs.Close() // Set to 16:9 widescreen (default) prs.SlideSize().SetSize(presentation.SlideScreenSize16x9) // Or custom size using EMU (1 inch = 914400 EMU) // custom := presentation.NewSlideScreenSizeWithValue(9144000, 5143500) // 10x5.625 inches // prs.SlideSize().SetSize(custom) slide := prs.AddSlide() tb := slide.AddTextBox() tb.Properties().SetPosition(0, 0) tb.AddParagraph().AddRun().SetText("16:9 slide") if err := prs.SaveToFile("sized.pptx"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Fill Out Form Fields Source: https://context7.com/unidoc/unioffice/llms.txt Opens documents containing form fields and fills them programmatically. Ensure the document 'form_template.docx' exists and contains form fields. The license key must be set. ```go package main import ( "fmt" "github.com/unidoc/unioffice/v2/common/license" "github.com/unidoc/unioffice/v2/document" "log" ) func main() { _ = license.SetMeteredKey("your-api-key") doc, err := document.Open("form_template.docx") if err != nil { log.Fatal(err) } defer doc.Close() for _, field := range doc.FormFields() { fmt.Printf("Field: %s, Type: %v\n", field.Name(), field.Type()) switch field.Type() { case document.FormFieldTypeText: field.SetValue("John Doe") case document.FormFieldTypeCheckBox: field.SetChecked(true) case document.FormFieldTypeDropDown: field.SetValue("Option1") } } if err := doc.SaveToFile("form_filled.docx"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Run Go Tests Source: https://github.com/unidoc/unioffice/wiki/UniOffice-Developer-Guide Execute all tests within the UniOffice project to ensure they pass. This command should be run regularly to maintain code stability. ```bash go test -v github.com/unidoc/unioffice/... ``` -------------------------------- ### Access Raw XML for Document Customization in Go Source: https://context7.com/unidoc/unioffice/llms.txt Shows how to directly manipulate underlying OOXML structures using the `X()` method for advanced document customization, such as setting background color or complex run properties. Requires importing schema types. ```go package main import ( "github.com/unidoc/unioffice/v2/common/license" "github.com/unidoc/unioffice/v2/document" "github.com/unidoc/unioffice/v2/color" "github.com/unidoc/unioffice/v2/schema/soo/wml" "log" ) func main() { _ = license.SetMeteredKey("your-api-key") doc := document.New() defer doc.Close() // Set document background color via raw XML access doc.X().Background = wml.NewCT_Background() doc.X().Background.ColorAttr = &wml.ST_HexColor{} doc.X().Background.ColorAttr.ST_HexColorRGB = color.RGB(30, 30, 60).AsRGBString() // Access raw paragraph XML para := doc.AddParagraph() run := para.AddRun() run.SetText("Document with custom background") // Access raw CT_R to set a less-common property rawRun := run.X() if rawRun.RPr == nil { rawRun.RPr = wml.NewCT_RPr() } rawRun.RPr.Cs = wml.NewCT_OnOff() // complex script font if err := doc.SaveToFile("raw_xml.docx"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Standard Import Grouping Style Source: https://github.com/unidoc/unioffice/wiki/UniOffice-Developer-Guide Recommended style for organizing import statements, separating standard library, external, and internal packages. ```go import ( // standard library imports // external dependency imports // unioffice public imports // unioffice internal imports ) ``` -------------------------------- ### Naked Return (Avoid) Source: https://github.com/unidoc/unioffice/wiki/UniOffice-Developer-Guide Avoid using naked returns as they make the return statement less explicit. ```go func x() (err error) { return } ``` -------------------------------- ### Add Tables to a Document Source: https://context7.com/unidoc/unioffice/llms.txt Creates a table with configurable rows, cells, borders, and cell formatting. Ensure the license key is set before creating a new document. ```go package main import ( "github.com/unidoc/unioffice/v2/common/license" "github.com/unidoc/unioffice/v2/document" "github.com/unidoc/unioffice/v2/color" "github.com/unidoc/unioffice/v2/measurement" "github.com/unidoc/unioffice/v2/schema/soo/wml" "log" ) func main() { _ = license.SetMeteredKey("your-api-key") doc := document.New() defer doc.Close() table := doc.AddTable() table.Properties().SetWidthPercent(100) headers := []string{"Name", "Age", "City"} rows := [][]string{ {"Alice", "30", "New York"}, {"Bob", "25", "London"}, {"Carol", "35", "Tokyo"}, } // Header row headerRow := table.AddRow() for _, h := range headers { cell := headerRow.AddCell() cell.Properties().SetShading(wml.ST_ShdSolid, color.FromHex("4472C4"), color.Auto) p := cell.AddParagraph() run := p.AddRun() run.Properties().SetBold(true) run.Properties().Color().SetRGBHex("FFFFFF") run.SetText(h) } // Data rows for _, rowData := range rows { row := table.AddRow() for _, cellText := range rowData { cell := row.AddCell() p := cell.AddParagraph() p.AddRun().SetText(cellText) } } // Set borders table.Properties().Borders().SetAll(wml.ST_BorderSingle, color.Black, 1*measurement.Point) if err := doc.SaveToFile("table.docx"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Create or open a workbook Source: https://context7.com/unidoc/unioffice/llms.txt Creates a new `*Workbook` or opens an existing `.xlsx` file for editing. ```APIDOC ## Spreadsheet (XLSX) — `github.com/unidoc/unioffice/v2/spreadsheet` ### `spreadsheet.New()` / `spreadsheet.Open()` — Create or open a workbook Creates a new `*Workbook` or opens an existing `.xlsx` file for editing. ### Usage Example ```go package main import ( "fmt" "github.com/unidoc/unioffice/v2/common/license" "github.com/unidoc/unioffice/v2/spreadsheet" "log" ) func main() { _ = license.SetMeteredKey("your-api-key") // Create new workbook wb := spreadsheet.New() defer wb.Close() sheet := wb.AddSheet() sheet.SetName("Sales") // Set column headers headers := []string{"Product", "Q1", "Q2", "Q3", "Q4", "Total"} row := sheet.AddRow() for i, h := range headers { cell := row.AddCell() cell.SetString(h) _ = i } // Set data rows data := [][]interface{}{ {"Widget A", 1500.0, 1800.0, 2100.0, 2400.0}, {"Widget B", 800.0, 950.0, 1100.0, 1300.0}, } for _, rowData := range data { r := sheet.AddRow() for j, v := range rowData { c := r.AddCell() switch val := v.(type) { case string: c.SetString(val) case float64: c.SetNumber(val) } // Add formula for Total column if j == 4 { totalCell := r.AddCell() // Formula references B through E of this row // e.g., =SUM(B2:E2) totalCell.SetFormulaRaw(fmt.Sprintf("SUM(B%d:E%d)", r.RowNumber(), r.RowNumber())) } } } if err := wb.SaveToFile("sales.xlsx"); err != nil { log.Fatal(err) } // Open existing existing, err := spreadsheet.Open("sales.xlsx") if err != nil { log.Fatal(err) } defer existing.Close() fmt.Println("Sheets:", existing.SheetCount()) } ``` ``` -------------------------------- ### Check Test Coverage Source: https://github.com/unidoc/unioffice/wiki/UniOffice-Developer-Guide Assess the test coverage for the UniOffice project using the go test -cover command. Aim for 90% coverage and ensure no regressions from the base branch. ```bash go test -cover github.com/unidoc/unioffice/... ``` -------------------------------- ### Add Headers, Footers, and Page Numbers to Document Source: https://context7.com/unidoc/unioffice/llms.txt Adds headers and footers with automatic page number fields to each document section. Ensure to set a valid license key. ```go package main import ( "github.com/unidoc/unioffice/v2/common/license" "github.com/unidoc/unioffice/v2/document" "github.com/unidoc/unioffice/v2/schema/soo/wml" "log" ) func main() { _ = license.SetMeteredKey("your-api-key") doc := document.New() defer doc.Close() // Add content doc.AddParagraph().AddRun().SetText("Main document content.") // Header hdr := doc.AddHeader() hdrPara := hdr.AddParagraph() hdrPara.Properties().SetAlignment(wml.ST_JcCenter) hdrPara.AddRun().SetText("My Company Report") // Footer with page number ftr := doc.AddFooter() ftrPara := ftr.AddParagraph() ftrPara.Properties().SetAlignment(wml.ST_JcCenter) ftrPara.AddRun().SetText("Page ") ftrPara.AddRun().AddField(document.FieldCurrentPage) ftrPara.AddRun().SetText(" of ") ftrPara.AddRun().AddField(document.FieldNumberOfPages) // Bind header/footer to default section doc.BodySection().SetHeader(hdr, wml.ST_HdrFtrDefault) doc.BodySection().SetFooter(ftr, wml.ST_HdrFtrDefault) if err := doc.SaveToFile("header_footer.docx"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Add Table to Slide - Go Source: https://context7.com/unidoc/unioffice/llms.txt Creates a table on a presentation slide and populates it with data. The table is initialized with a specified number of rows and columns. ```go package main import ( "github.com/unidoc/unioffice/v2/common/license" "github.com/unidoc/unioffice/v2/presentation" "log" ) func main() { _ = license.SetMeteredKey("your-api-key") prs := presentation.New() defer prs.Close() slide := prs.AddSlide() tbl := slide.AddTable() tbl.InitializeDefaults(4, 3) // 4 rows, 3 columns headers := []string{"Quarter", "Revenue", "Growth"} for col, h := range headers { tbl.Row(0).Cell(col).RichText().Run().SetText(h) } data := [][]string{ {"Q1", "$1.0M", "+10%"}, {"Q2", "$1.1M", "+12%"}, {"Q3", "$1.2M", "+15%"}, } for row, rowData := range data { for col, text := range rowData { tbl.Row(row+1).Cell(col).RichText().Run().SetText(text) } } if err := prs.SaveToFile("table_slide.pptx"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Declaring Empty Maps Source: https://github.com/unidoc/unioffice/wiki/UniOffice-Developer-Guide For maps where the size is known, use 'make' with a capacity. Otherwise, use 'make' without capacity. ```go m := make(map[x]y, 10) ``` ```go m := make(map[x]y) ``` -------------------------------- ### Create and Save a New Word Document Source: https://context7.com/unidoc/unioffice/llms.txt Creates a new blank Word document and adds styled and normal paragraphs. Ensure to close the document after use. The document is saved to a specified file path. ```go package main import ( "github.com/unidoc/unioffice/v2/common/license" "github.com/unidoc/unioffice/v2/document" "github.com/unidoc/unioffice/v2/color" "github.com/unidoc/unioffice/v2/measurement" "log" ) func main() { _ = license.SetMeteredKey("your-api-key") doc := document.New() defer doc.Close() // Add a styled paragraph para := doc.AddParagraph() run := para.AddRun() run.Properties().SetBold(true) run.Properties().SetSize(14 * measurement.Point) run.Properties().Color().SetRGB(0x1F, 0x49, 0x7D) run.SetText("Hello, unioffice!") // Add a normal paragraph para2 := doc.AddParagraph() run2 := para2.AddRun() run2.SetText("This is a paragraph with default formatting.") if err := doc.SaveToFile("output.docx"); err != nil { log.Fatal(err) } // Output: output.docx created with two paragraphs } ``` -------------------------------- ### document.New() - Create a new Word document Source: https://context7.com/unidoc/unioffice/llms.txt Creates and returns a blank `*Document` ready for content. Use `SaveToFile` or `Save` to persist it. ```APIDOC ## document.New() - Create a new Word document Creates and returns a blank `*Document` ready for content. Use `SaveToFile` or `Save` to persist it. ```go package main import ( "github.com/unidoc/unioffice/v2/common/license" "github.com/unidoc/unioffice/v2/document" "github.com/unidoc/unioffice/v2/color" "github.com/unidoc/unioffice/v2/measurement" "log" ) func main() { _ = license.SetMeteredKey("your-api-key") doc := document.New() defer doc.Close() // Add a styled paragraph para := doc.AddParagraph() run := para.AddRun() run.Properties().SetBold(true) run.Properties().SetSize(14 * measurement.Point) run.Properties().Color().SetRGB(0x1F, 0x49, 0x7D) run.SetText("Hello, unioffice!") // Add a normal paragraph para2 := doc.AddParagraph() run2 := para2.AddRun() run2.SetText("This is a paragraph with default formatting.") if err := doc.SaveToFile("output.docx"); err != nil { log.Fatal(err) } // Output: output.docx created with two paragraphs } ``` ``` -------------------------------- ### Set Document Background Color Source: https://github.com/unidoc/unioffice/blob/master/README.md Demonstrates how to set a document's background color by accessing and manipulating the raw CT_Background element when a direct API is not available. ```go doc := document.New() doc.X().Background = wordprocessingml.NewCT_Background() doc.X().Background.ColorAttr = &wordprocessingml.ST_HexColor{} doc.X().Background.ColorAttr.ST_HexColorRGB = color.RGB(50, 50, 50).AsRGBString() ``` -------------------------------- ### AddSlideWithLayout / AddDefaultSlideWithLayout Source: https://context7.com/unidoc/unioffice/llms.txt Opens an existing .pptx as a template and creates new slides from its predefined layouts, filling placeholder text programmatically. ```APIDOC ## `prs.AddSlideWithLayout()` / `AddDefaultSlideWithLayout()` — Layout-based slides ### Description Opens an existing `.pptx` as a template and creates new slides from its predefined layouts, filling placeholder text programmatically. ### Method Signature ```go func (prs *Presentation) AddDefaultSlideWithLayout(layout *Layout) (*Slide, error) ``` ### Parameters - `layout` (*Layout) - The layout to use for the new slide. ### Usage Example ```go package main import ( "github.com/unidoc/unioffice/v2/common/license" "github.com/unidoc/unioffice/v2/presentation" "github.com/unidoc/unioffice/v2/schema/soo/pml" "log" ) func main() { _ = license.SetMeteredKey("your-api-key") prs, err := presentation.OpenTemplate("template.pptx") if err != nil { log.Fatal(err) } defer prs.Close() layout, err := prs.GetLayoutByName("Title and Content") if err != nil { log.Fatal(err) } slide, err := prs.AddDefaultSlideWithLayout(layout) if err != nil { log.Fatal(err) } title, err := slide.GetPlaceholder(pml.ST_PlaceholderTypeTitle) if err == nil { title.SetText("Quarterly Results") } body, err := slide.GetPlaceholder(pml.ST_PlaceholderTypeBody) if err == nil { body.Clear() p := body.AddParagraph() p.AddRun().SetText("• Revenue: $1.2M") p2 := body.AddParagraph() p2.AddRun().SetText("• Growth: +15%") } if err := prs.SaveToFile("from_template.pptx"); err != nil { log.Fatal(err) } } ``` ``` -------------------------------- ### Add Formatted Paragraphs and Runs to a Document Source: https://context7.com/unidoc/unioffice/llms.txt Demonstrates adding a heading paragraph with center alignment and a body paragraph with italicized text and specific spacing. Paragraph and run-level properties are configurable. ```go package main import ( "github.com/unidoc/unioffice/v2/common/license" "github.com/unidoc/unioffice/v2/document" "github.com/unidoc/unioffice/v2/measurement" "github.com/unidoc/unioffice/v2/schema/soo/wml" "log" ) func main() { _ = license.SetMeteredKey("your-api-key") doc := document.New() defer doc.Close() // Heading paragraph heading := doc.AddParagraph() hProps := heading.Properties() hProps.SetAlignment(wml.ST_JcCenter) hProps.SetStyle("Heading1") hRun := heading.AddRun() hRun.SetText("Document Title") // Body paragraph with spacing body := doc.AddParagraph() bProps := body.Properties() bProps.SetSpacing(measurement.Distance(6*measurement.Point), measurement.Distance(6*measurement.Point)) bProps.SetAlignment(wml.ST_JcBoth) r := body.AddRun() r.Properties().SetItalic(true) r.Properties().SetSize(11 * measurement.Point) r.SetText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.") if err := doc.SaveToFile("formatted.docx"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Error Handling in Go - Passing Errors Up Source: https://github.com/unidoc/unioffice/wiki/UniOffice-Developer-Guide Avoid using panic for error handling. Instead, pass errors up the call stack. Log errors before returning them to provide context. ```go err := doStuff() if err != nil { unioffice.Log("ERROR: doStuff failed: %v", err) return err } ``` -------------------------------- ### Run Tests in Docker Source: https://github.com/unidoc/unioffice/blob/master/README.md Provides commands to execute tests within a Dockerized environment using the provided Makefile. ```bash make docker-test ``` ```bash make docker-update-testdata ``` -------------------------------- ### document.Open() / document.OpenTemplate() - Open an existing document Source: https://context7.com/unidoc/unioffice/llms.txt Opens a `.docx` file for reading or editing. `OpenTemplate` opens a document as a template, replacing its body content while retaining styles. ```APIDOC ## document.Open() / document.OpenTemplate() - Open an existing document Opens a `.docx` file for reading or editing. `OpenTemplate` opens a document as a template, replacing its body content while retaining styles. ```go package main import ( "fmt" "github.com/unidoc/unioffice/v2/common/license" "github.com/unidoc/unioffice/v2/document" "log" ) func main() { _ = license.SetMeteredKey("your-api-key") doc, err := document.Open("existing.docx") if err != nil { log.Fatal(err) } defer doc.Close() // Iterate paragraphs and extract text for _, para := range doc.Paragraphs() { for _, run := range para.Runs() { fmt.Print(run.Text()) } fmt.Println() } // Edit: replace all runs in first paragraph if len(doc.Paragraphs()) > 0 { p := doc.Paragraphs()[0] for _, r := range p.Runs() { r.ClearContent() r.SetText("Replaced text") break } } if err := doc.SaveToFile("modified.docx"); err != nil { log.Fatal(err) } } ``` ``` -------------------------------- ### Read and write individual cells in a spreadsheet Source: https://context7.com/unidoc/unioffice/llms.txt Accesses cells by reference string and uses typed setters/getters for various data types including strings, numbers, booleans, dates, and formulas. Ensure the license key is set before creating a new workbook. ```go package main import ( "fmt" "github.com/unidoc/unioffice/v2/common/license" "github.com/unidoc/unioffice/v2/spreadsheet" "time" "log" ) func main() { _ = license.SetMeteredKey("your-api-key") wb := spreadsheet.New() defer wb.Close() sheet := wb.AddSheet() sheet.SetName("Data") sheet.Cell("A1").SetString("Name") sheet.Cell("B1").SetString("Score") sheet.Cell("C1").SetString("Date") sheet.Cell("D1").SetString("Pass") sheet.Cell("A2").SetString("Alice") sheet.Cell("B2").SetNumber(95.5) sheet.Cell("C2").SetDate(time.Now()) sheet.Cell("D2").SetBool(true) sheet.Cell("A3").SetString("Bob") sheet.Cell("B3").SetNumber(72.0) sheet.Cell("C3").SetDate(time.Now().AddDate(0, 0, -7)) sheet.Cell("D3").SetBool(false) // Formula sheet.Cell("B4").SetFormulaRaw("AVERAGE(B2:B3)") // Recalculate and read cached formula result sheet.RecalculateFormulas() fmt.Println("Average:", sheet.Cell("B4").GetCachedFormulaResult()) // Output: Average: 83.75 // Read typed value v, _ := sheet.Cell("B2").GetRawValue() fmt.Println("B2 raw value:", v) if err := wb.SaveToFile("cells.xlsx"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Default Declaration with 'var' Source: https://github.com/unidoc/unioffice/wiki/UniOffice-Developer-Guide Use 'var' to declare variables when their initial value does not matter. ```go var i int ``` -------------------------------- ### Check Golint Issues Source: https://github.com/unidoc/unioffice/wiki/UniOffice-Developer-Guide Count the number of issues reported by golint for the UniOffice project. The count should not increase on new contributions to maintain code quality standards. ```bash golint github.com/unidoc/unioffice/... | wc -l ``` -------------------------------- ### TODO/FIXME/NOTE Comment Convention in Go Source: https://github.com/unidoc/unioffice/wiki/UniOffice-Developer-Guide When using TODO, FIXME, or NOTE comments, include the author's GitHub handle. Avoid using XXX for clarity. ```go // FIXME(gunnsth): Not working for case t = 3. ``` -------------------------------- ### Hyperlinks in Documents Source: https://context7.com/unidoc/unioffice/llms.txt Inserts clickable hyperlinks within a paragraph run. Ensure the license key is set. ```go package main import ( "github.com/unidoc/unioffice/v2/common/license" "github.com/unidoc/unioffice/v2/document" "log" ) func main() { _ = license.SetMeteredKey("your-api-key") doc := document.New() defer doc.Close() para := doc.AddParagraph() para.AddRun().SetText("Visit our website: ") hl := doc.AddHyperlink("https://unidoc.io") hlRun := para.AddHyperlinkRun(hl) hlRun.Properties().SetStyle("Hyperlink") hlRun.SetText("UniDoc") if err := doc.SaveToFile("hyperlink.docx"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Explicit Initialization (Value Matters) Source: https://github.com/unidoc/unioffice/wiki/UniOffice-Developer-Guide When the initial value of a variable is important, make it explicit during declaration. ```go i := 0 ``` -------------------------------- ### Apply Cell Styles and Number Formats in Spreadsheet Source: https://context7.com/unidoc/unioffice/llms.txt Applies fonts, fills, borders, alignment, and number formats to cells and ranges in an XLSX file. Ensure you have a valid license key set. ```go package main import ( "github.com/unidoc/unioffice/v2/color" "github.com/unidoc/unioffice/v2/common/license" "github.com/unidoc/unioffice/v2/spreadsheet" "log" ) func main() { _ = license.SetMeteredKey("your-api-key") wb := spreadsheet.New() defer wb.Close() sheet := wb.AddSheet() sheet.SetName("Styled") // Create a bold header style with blue background headerStyle := wb.StyleSheet.AddCellStyle() headerFont := wb.StyleSheet.AddFont() headerFont.SetBold(true) headerFont.SetSize(12) headerFont.SetColor(color.White) headerStyle.SetFont(headerFont) headerFill := wb.StyleSheet.AddFill() headerFill.SetPatternFill().SetFgColor(color.FromRGB(31, 73, 125)) headerStyle.SetFill(headerFill) // Apply style to header row for col := 0; col < 5; col++ { row := sheet.Row(1) c := row.AddCell() c.SetStyle(headerStyle) c.SetString("Header") } // Date format style dateStyle := wb.StyleSheet.GetOrCreateStandardNumberFormat(spreadsheet.StandardFormatDate) sheet.Cell("A2").SetNumberWithStyle(44927.0, spreadsheet.StandardFormatDate) _ = dateStyle // Currency format sheet.Cell("B2").SetNumberWithStyle(1234.56, spreadsheet.StandardFormatCurrency2DecimalPlace) if err := wb.SaveToFile("styled.xlsx"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Apply conditional formatting to spreadsheet cells Source: https://context7.com/unidoc/unioffice/llms.txt Adds conditional formatting rules such as color scales, data bars, and icon sets to specified cell ranges. Requires setting a license key and populating data before applying formatting. ```go package main import ( "github.com/unidoc/unioffice/v2/common/license" "github.com/unidoc/unioffice/v2/spreadsheet" "github.com/unidoc/unioffice/v2/schema/soo/sml" "log" ) func main() { _ = license.SetMeteredKey("your-api-key") wb := spreadsheet.New() defer wb.Close() sheet := wb.AddSheet() sheet.SetName("CF") // Populate data for i := 1; i <= 10; i++ { row := sheet.AddRow() row.AddCell().SetNumber(float64(i * 10)) } // Color scale: green (low) → red (high) on A1:A10 cf := sheet.AddConditionalFormatting() cf.SetRangeRef("A1:A10") rule := cf.AddRule() cs := rule.SetColorScale() cs.AddFormatValue(sml.ST_CfvoTypeMin, "0") cs.AddFormatValue(sml.ST_CfvoTypeMax, "0") cs.AddColor(spreadsheet.ColorFromRGB(0x63, 0xBE, 0x7B)) // green cs.AddColor(spreadsheet.ColorFromRGB(0xF8, 0x69, 0x6B)) // red // Data bar on A1:A10 cf2 := sheet.AddConditionalFormatting() cf2.SetRangeRef("A1:A10") rule2 := cf2.AddRule() db := rule2.SetDataBar() db.AddFormatValue(sml.ST_CfvoTypeMin, "0") db.AddFormatValue(sml.ST_CfvoTypeMax, "0") db.AddColor(spreadsheet.ColorFromRGB(0x63, 0x8E, 0xC6)) if err := wb.SaveToFile("conditional.xlsx"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Incorrect Blank Line Usage in Function Source: https://github.com/unidoc/unioffice/wiki/UniOffice-Developer-Guide Illustrates incorrect usage of blank lines at the beginning of a function block. ```go func x() { return } // or func x() { if 2 > 1 { return } } ``` -------------------------------- ### Embed Images in Documents Source: https://context7.com/unidoc/unioffice/llms.txt Adds inline or anchored (floating) images with configurable wrapping and positioning. Ensure the image file exists and the license key is set. ```go package main import ( "github.com/unidoc/unioffice/v2/common" "github.com/unidoc/unioffice/v2/common/license" "github.com/unidoc/unioffice/v2/document" "github.com/unidoc/unioffice/v2/measurement" "log" ) func main() { _ = license.SetMeteredKey("your-api-key") doc := document.New() defer doc.Close() img, err := common.ImageFromFile("logo.png") if err != nil { log.Fatal(err) } imgRef, err := doc.AddImage(img) if err != nil { log.Fatal(err) } para := doc.AddParagraph() run := para.AddRun() // Inline image inlined, err := run.AddDrawingInline(imgRef) if err != nil { log.Fatal(err) } inlined.SetSize(2*measurement.Inch, 1*measurement.Inch) // Alternatively, anchored (floating) image: // anchored, _ := run.AddDrawingAnchored(imgRef) // anchored.SetSize(3*measurement.Inch, 2*measurement.Inch) // anchored.SetOffset(1*measurement.Inch, 1*measurement.Inch) // anchored.SetTextWrapSquare(document.WrapTextBothSides) if err := doc.SaveToFile("image.docx"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Declaring Empty Slices Source: https://github.com/unidoc/unioffice/wiki/UniOffice-Developer-Guide Prefer 'var t []string' over 't := []string{}' for declaring empty slices. ```go var t []string ``` -------------------------------- ### Implement data validation with drop-down lists Source: https://context7.com/unidoc/unioffice/llms.txt Applies data validation to cells, restricting input to predefined lists or numeric/date ranges. Supports custom input prompts and error messages. Ensure the license key is set before creating the workbook. ```go package main import ( "github.com/unidoc/unioffice/v2/common/license" "github.com/unidoc/unioffice/v2/spreadsheet" "github.com/unidoc/unioffice/v2/schema/soo/sml" "log" ) func main() { _ = license.SetMeteredKey("your-api-key") wb := spreadsheet.New() defer wb.Close() sheet := wb.AddSheet() sheet.SetName("Validated") sheet.Cell("A1").SetString("Status") sheet.Cell("B1").SetString("Score") // Drop-down list validation dv := sheet.AddDataValidation() dv.SetRange("A2:A100") dvc := dv.SetList() dvc.SetValues([]string{"Active", "Inactive", "Pending"}) dv.SetError("Invalid Entry", "Please select a value from the list.") dv.SetPrompt("Status", "Choose Active, Inactive, or Pending.") // Numeric range validation dv2 := sheet.AddDataValidation() dv2.SetRange("B2:B100") dv2.SetType(sml.ST_DataValidationTypeDecimal) dv2.SetOperator(sml.ST_DataValidationOperatorBetween) compare := dv2.SetValue("0") _ = compare dv2.SetValue2("100") if err := wb.SaveToFile("validation.xlsx"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### sheet.AddConditionalFormatting() Source: https://context7.com/unidoc/unioffice/llms.txt Applies color scales, data bars, icon sets, and rule-based cell formatting. ```APIDOC ## sheet.AddConditionalFormatting() ### Description Applies color scales, data bars, icon sets, and rule-based cell formatting to a specified range. ### Method This describes a method for adding conditional formatting rules to a sheet. ### Endpoint Not applicable (this is an SDK method, not an HTTP endpoint). ### Parameters - **rangeRef** (string) - Required - The range of cells to apply the formatting to (e.g., "A1:A10"). ### Request Example ```go cf := sheet.AddConditionalFormatting() cf.SetRangeRef("A1:A10") rule := cf.AddRule() cs := rule.SetColorScale() cs.AddFormatValue(sml.ST_CfvoTypeMin, "0") cs.AddColor(spreadsheet.ColorFromRGB(0x63, 0xBE, 0x7B)) // green ``` ### Response - **ConditionalFormatting Object** - An object representing the conditional formatting rule that can be further configured. ### Response Example ```go cf := sheet.AddConditionalFormatting() cf.SetRangeRef("A1:A10") ``` ```