Skip to content

Images ​

Basic image insertion ​

Input file template.docx: Image insertion input file

Golang code:

go
package main

import (
	"fmt"
	"os"

	gotemplatedocx "github.com/JJJJJJack/go-template-docx"
)

type ExampleStruct struct {
	MediaFilename string
}

func main() {
	docxTemplate, err := gotemplatedocx.NewDocxTemplateFromFilename("template.docx")
	if err != nil {
		fmt.Println("Error loading template:", err)
		return
	}

	filename := "example.jpg"

	bytes, _ := os.ReadFile(filename)

	templateValues := ExampleStruct{
		MediaFilename: filename,
	}

	docxTemplate.Media(filename, bytes)

	err = docxTemplate.Apply(templateValues)
	if err != nil {
		fmt.Println("Error applying template values:", err)
		return
	}

	err = docxTemplate.Save("template_output.docx")
	if err != nil {
		fmt.Println("Error saving output file:", err)
		return
	}
}

Output file template_output.docx: Output file

Image alignment

The insert image automatically inherit alignement from its placeholder.

Image styles ​

Border styling is provided with 2 options for now:

StyleAccepted tokens
Border ColorborderColor:<hex>,bc:<hex>
Border WidthborderWidth:<size>,bw:<size>

Pass border options to image to set an inserted image's border color and width:

text
{{image .MediaFilename "borderColor:#FF0000" "borderWidth:2"}}

borderColor accepts a six-digit hexadecimal RGB value, with or without a leading #. Its default is black (#000000). borderWidth sets the border width in points and defaults to 1. The bw option is an alias for borderWidth.

Defaults are used when one option is provided without the other.

Replacing images ​

To replace an existing image it's a little different, you need to put the template action inside the image's Alt Text property:

Input file template.docx: Image replacement input file

Golang code:

go
package main

import (
	"fmt"
	"os"

	gotemplatedocx "github.com/JJJJJJack/go-template-docx"
)

type ExampleStruct struct {
	MediaFilename string
}

func main() {
	docxTemplate, err := gotemplatedocx.NewDocxTemplateFromFilename("template.docx")
	if err != nil {
		fmt.Println("Error loading template:", err)
		return
	}

	filename := "cat.jpg"

	bytes, _ := os.ReadFile(filename)

	templateValues := ExampleStruct{
		MediaFilename: filename,
	}

	docxTemplate.Media(filename, bytes)

	err = docxTemplate.Apply(templateValues)
	if err != nil {
		fmt.Println("Error applying template values:", err)
		return
	}

	err = docxTemplate.Save("template_output.docx")
	if err != nil {
		fmt.Println("Error saving output file:", err)
		return
	}
}

Output file template_output.docx: Output file

Image replacement

The original image sizes are preserved when replacing images.