docx

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 25, 2026 License: MIT Imports: 8 Imported by: 0

README

go-docx

A Go library for reading and writing Microsoft Word 2007+ (.docx, OOXML) — a complete rewrite of python-docx from Python.

Go Reference Go Report Card build

go-docx is a Go-language equivalent rewrite of python-docx (v1.2.0): it preserves the original project's full public API capabilities and .docx round-trip fidelity, while replacing runtime dependencies (lxml, Pillow, etc.) with Go's existing libraries (stdlib first), and migrating tests and documentation alongside. See docs/REFACTORING.md for the full refactoring rationale.

Repository: https://github.com/SamYue1/go-docx. Upstream: https://github.com/python-openxml/python-docx.

Status

Work in progress (WIP). Progressing in phases per docs/REFACTORING.md §9: skeleton & foundations → declarative XML framework → OPC layer → CT element classes → object layer → sub-domain completion → acceptance test alignment → documentation & CI. No stable release yet.

Features (target: feature parity with python-docx)

  • Open/save .docx (with built-in default template), supporting both paths and io.Reader/io.Writer
  • Paragraphs and Runs: text, bold/italic/superscript/subscript, font, color, alignment, indentation, spacing, breaks
  • Tables: add/delete rows and columns, merge cells, style, alignment, row height rules
  • Sections: page size/orientation, margins, section breaks
  • Headers and footers: first page / odd & even pages
  • Styles: paragraph/character/table styles, latent styles
  • Hyperlinks: address, text, runs, breaks
  • Images: embedded images, size and DPI adaptation (PNG/JPEG/GIF/BMP/TIFF)
  • Comments: add, author, initials, Comment.text, range marks
  • Core properties, document settings, numbering part

See docs/REFACTORING.md §5 for the full feature mapping (all 67 acceptance .feature files preserved).

Installation

go get github.com/SamYue1/go-docx

Requires Go 1.21+ (go:embed was introduced in 1.16; 1.21 is chosen for per-iteration loop variable scoping and other testing conveniences).

Quick Start

Go translation of the python-docx README example:

package main

import (
	"fmt"
	"os"

	"github.com/SamYue1/go-docx"
)

func main() {
	doc := docx.NewDocument()
	doc.AddParagraph("It was a dark and stormy night.")
	if err := doc.Save("dark-and-stormy.docx"); err != nil {
		panic(err)
	}

	f, _ := os.Open("dark-and-stormy.docx")
	defer f.Close()
	doc2, err := docx.Open(f)
	if err != nil {
		panic(err)
	}
	fmt.Println(doc2.Paragraphs[0].Text())
	// It was a dark and stormy night.
}

Tests

This library uses test-driven development (TDD) to drive the refactoring, with Go-idiomatic style:

  • Unit tests: testing + github.com/stretchr/testify/assert, naming follows the original project's BDD style (it_/and_/but_ as subtest names), table-driven preferred.
  • Acceptance tests: github.com/cucumber/godog, reusing the original python-docx 67 Gherkin .feature files as-is, with steps rewritten in Go.
  • Discipline: every change follows red → green → refactor; all three must be green before commit.
go vet ./...
go test ./...                 # Unit tests
go test ./test/features/      # Acceptance tests (godog Gherkin)

See docs/REFACTORING.md §6 for details (TDD workflow and Go test style conventions).

Architecture

Preserves python-docx's two-layer architecture: the low-level OpenXML layer (DOM + declarative content model, corresponding to the original xmlchemy) and the high-level user-facing object layer; intermediate layers are scoped with internal/, and the public API is re-exported through the root docx package. See docs/REFACTORING.md §3 for package structure and mapping.

Documentation

The refactoring plan and design documentation live in docs/REFACTORING.md. API reference is generated by go doc from source comments. Upstream Sphinx/rst docs have not been fully migrated yet — see docs/REFACTORING.md §7.

Contributing

Submit via TDD: go vet ./... && go test ./... && go test ./test/features/ must all pass.

License

MIT, same as upstream python-docx.

Acknowledgements

go-docx builds on years of work by Steve Canny and the python-openxml/python-docx maintainers. This repository is a Go-language refactoring and equivalent rebuild, with gratitude.

Documentation

Overview

Package docx provides the public API for creating, reading, and modifying WordprocessingML (.docx) files. It re-exports the internal types as type aliases so that callers import a single package. This package mirrors the top-level API of python-docx.

Index

Constants

View Source
const (
	// BreakLine specifies a line break.
	BreakLine = otext.BreakLine
	// BreakPage specifies a page break.
	BreakPage = otext.BreakPage
	// BreakColumn specifies a column break.
	BreakColumn = otext.BreakColumn
	// BreakLineClearLeft specifies a line break with left-side text wrapping cleared.
	BreakLineClearLeft = otext.BreakLineClearLeft
	// BreakLineClearRight specifies a line break with right-side text wrapping cleared.
	BreakLineClearRight = otext.BreakLineClearRight
	// BreakLineClearAll specifies a line break with both-side text wrapping cleared.
	BreakLineClearAll = otext.BreakLineClearAll
)
View Source
const (
	// HeaderFooterDefault refers to the default header/footer for odd and all pages.
	HeaderFooterDefault = osect.HeaderFooterDefault
	// HeaderFooterFirst refers to the header/footer for the first page of a section.
	HeaderFooterFirst = osect.HeaderFooterFirst
	// HeaderFooterEven refers to the header/footer for even-numbered pages.
	HeaderFooterEven = osect.HeaderFooterEven
)

Variables

This section is empty.

Functions

func Cm

func Cm(v float64) shared.Length

Cm converts a value in centimeters to Length (EMU).

func Emu

func Emu(v int) shared.Length

Emu converts a value in EMUs to Length.

func Inches

func Inches(v float64) shared.Length

Inches converts a value in inches to Length (EMU).

func Mm

func Mm(v float64) shared.Length

Mm converts a value in millimeters to Length (EMU).

func Pt

func Pt(v float64) shared.Length

Pt converts a value in points to Length (EMU).

func Twips

func Twips(v float64) shared.Length

Twips converts a value in twips to Length (EMU).

Types

type BreakType

type BreakType = otext.BreakType

BreakType specifies the type of break (line, page, column, etc.).

type Cell

type Cell = otable.Cell

Cell represents a cell within a table row.

type ColorFormat

type ColorFormat = dml.ColorFormat

ColorFormat represents the color formatting properties.

type Column

type Column = otable.Column

Column represents a column within a table grid.

type Comment

type Comment = odoc.Comment

Comment represents a single comment annotation in the document.

type Comments

type Comments = odoc.Comments

Comments represents a collection of document comments.

func NewComments

func NewComments() *Comments

NewComments creates a new empty Comments collection.

type Document

type Document = odoc.Document

Document represents a WordprocessingML (docx) document.

func NewDocument

func NewDocument() *Document

NewDocument creates a new empty Document with default styles and a single section.

func Open

func Open(r io.ReaderAt, size int64) (*Document, error)

Open opens a docx file from an io.ReaderAt with the given size and returns a Document.

func OpenPath

func OpenPath(path string) (*Document, error)

OpenPath opens a docx file from a file path and returns a Document.

type Font

type Font = otext.Font

Font provides access to character-level formatting properties.

type HeaderFooter

type HeaderFooter = osect.HeaderFooter

HeaderFooter represents a header or footer associated with a section.

type HeaderFooterType

type HeaderFooterType = osect.HeaderFooterType

HeaderFooterType identifies the type of header or footer (default, first, even).

type Hyperlink = otext.Hyperlink

Hyperlink represents a hyperlink within a run.

type Image

type Image = odoc.Image

Image represents an image with metadata such as path, DPI, and pixel dimensions.

type InlineShape

type InlineShape = odoc.InlineShape

InlineShape represents an inline drawing or picture shape.

func NewInlineShape

func NewInlineShape(typ string, width, height shared.Length) *InlineShape

NewInlineShape creates a new InlineShape with the given type, width, and height.

type InlineShapes

type InlineShapes = odoc.InlineShapes

InlineShapes represents a collection of inline shapes (pictures, etc.).

func NewInlineShapes

func NewInlineShapes() *InlineShapes

NewInlineShapes creates a new empty InlineShapes collection.

type LatentStyle

type LatentStyle = styles.LatentStyle

LatentStyle represents a single latent (exception) style entry.

type LatentStyles

type LatentStyles = styles.LatentStyles

LatentStyles provides access to latent style settings.

type Length

type Length = shared.Length

Length represents a distance measurement in EMUs.

type MsoColorType

type MsoColorType = dml.MsoColorType

MsoColorType identifies the type of color specification.

type MsoThemeColor

type MsoThemeColor = dml.MsoThemeColor

MsoThemeColor identifies a theme color in the document theme.

type NumberingPart

type NumberingPart = odoc.NumberingPart

NumberingPart manages numbered list definitions and numbering instances.

type Paragraph

type Paragraph = otext.Paragraph

Paragraph represents a paragraph within a document.

type ParagraphFormat

type ParagraphFormat = otext.ParagraphFormat

ParagraphFormat provides access to paragraph-level formatting properties.

type RGBColor

type RGBColor = shared.RGBColor

RGBColor represents an RGB color value.

type RenderedPageBreak

type RenderedPageBreak = otext.RenderedPageBreak

RenderedPageBreak represents a page break that has been rendered.

type Row

type Row = otable.Row

Row represents a row within a table.

type Run

type Run = otext.Run

Run represents a contiguous run of text with uniform formatting.

type Section

type Section = osect.Section

Section represents a document section that defines page layout properties.

type Settings

type Settings = osect.Settings

Settings provides access to document-level settings (e.g., odd/even headers).

type Style

type Style = styles.Style

Style represents a single style (paragraph, character, table, or numbering style).

type Styles

type Styles = styles.Styles

Styles provides access to the document's style definitions.

type TabStop

type TabStop = otext.TabStop

TabStop represents a single tab stop within a paragraph.

type TabStops

type TabStops = otext.TabStops

TabStops represents a collection of tab stops on a paragraph.

type Table

type Table = otable.Table

Table represents a table within a document.

Directories

Path Synopsis
internal
dml
Package dml provides DrawingML types for working with Office Open XML drawing and color constructs.
Package dml provides DrawingML types for working with Office Open XML drawing and color constructs.
enums
Package enums provides generic utilities for mapping between integer enum values and their XML string representations.
Package enums provides generic utilities for mapping between integer enum values and their XML string representations.
image
Package image provides image decoding and DPI extraction for formats supported by OOXML.
Package image provides image decoding and DPI extraction for formats supported by OOXML.
odoc
Package odoc provides the core document implementation for opening, creating, saving, and manipulating WordprocessingML documents.
Package odoc provides the core document implementation for opening, creating, saving, and manipulating WordprocessingML documents.
opc
Package opc implements the Open Packaging Conventions (OPC) standard for reading and writing OOXML packages (.docx, .xlsx, .pptx).
Package opc implements the Open Packaging Conventions (OPC) standard for reading and writing OOXML packages (.docx, .xlsx, .pptx).
opc/parts
Package parts provides higher-level OPC part implementations that wrap the core opc package types with domain-specific behaviour.
Package parts provides higher-level OPC part implementations that wrap the core opc package types with domain-specific behaviour.
osect
Package osect provides types for document sections and headers/footers.
Package osect provides types for document sections and headers/footers.
otable
Package otable provides high-level table objects (Table, Row, Cell, Column) wrapping oxml table proxy types, analogous to python-docx's table layer.
Package otable provides high-level table objects (Table, Row, Cell, Column) wrapping oxml table proxy types, analogous to python-docx's table layer.
otext
Package otext provides high-level text formatting objects (Paragraph, Run, Font, Hyperlink, TabStops, etc.) that wrap oxml proxy types, analogous to the python-docx text layer.
Package otext provides high-level text formatting objects (Paragraph, Run, Font, Hyperlink, TabStops, etc.) that wrap oxml proxy types, analogous to the python-docx text layer.
oxml
Package oxml provides Go proxy types for OOXML elements used in WordprocessingML documents.
Package oxml provides Go proxy types for OOXML elements used in WordprocessingML documents.
oxml/dom
Package dom implements a lightweight in-memory XML DOM for OOXML document manipulation.
Package dom implements a lightweight in-memory XML DOM for OOXML document manipulation.
oxml/ns
Package ns provides OOXML namespace URI constants, a prefix-to-URI map, and helpers for converting between Clark notation ({URI}local) and prefix:local notation.
Package ns provides OOXML namespace URI constants, a prefix-to-URI map, and helpers for converting between Clark notation ({URI}local) and prefix:local notation.
oxml/stypes
Package stypes provides simple-type converters for OOXML schema types (ST_OnOff, ST_DecimalNumber, ST_String, ST_HexColor, ST_HpsMeasure).
Package stypes provides simple-type converters for OOXML schema types (ST_OnOff, ST_DecimalNumber, ST_String, ST_HexColor, ST_HpsMeasure).
oxml/text
Package text provides XML proxy types for text-related OOXML elements: paragraph (w:p), run (w:r), font (w:rPr), hyperlink (w:hyperlink), and related formatting types.
Package text provides XML proxy types for text-related OOXML elements: paragraph (w:p), run (w:r), font (w:rPr), hyperlink (w:hyperlink), and related formatting types.
oxml/xmodel
Package xmodel provides a declarative schema registry for OOXML parent-child relationships and the functions to query/manipulate elements according to that schema.
Package xmodel provides a declarative schema registry for OOXML parent-child relationships and the functions to query/manipulate elements according to that schema.
parts
Package parts provides OPC part wrappers for document parts (DocumentPart, StylesPart, ImagePart, etc.), analogous to python-docx's parts layer.
Package parts provides OPC part wrappers for document parts (DocumentPart, StylesPart, ImagePart, etc.), analogous to python-docx's parts layer.
shared
Package shared provides common types and utilities used across the go-docx library, including length units and RGB color representation.
Package shared provides common types and utilities used across the go-docx library, including length units and RGB color representation.
styles
Package styles provides types for working with Word document styles, including Style, LatentStyles, and LatentStyle.
Package styles provides types for working with Word document styles, including Style, LatentStyles, and LatentStyle.
testutil
Package testutil provides test helpers for the go-docx acceptance tests.
Package testutil provides test helpers for the go-docx acceptance tests.
tpl
Package tpl embeds the default blank Word document template (default.docx).
Package tpl embeds the default blank Word document template (default.docx).
test

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL