Help us shape the future of Go! Take the 2026 Go Developer Survey

office

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

README

Office Document Parser

A Go package for parsing Office documents (DOCX and PPTX) and converting them to Markdown with media extraction, without using any external dependencies.

Features

  • ✅ DOCX Support: Parse Word documents and extract text, formatting, and media
  • ✅ PPTX Support: Parse PowerPoint presentations with slide-by-slide content extraction
  • ✅ Markdown Output: Convert formatted text to Markdown with proper headings, bold, italic
  • ✅ Media Extraction: Extract images, videos, and audio files with metadata
  • ✅ Text Range Tracking: Track text positions and page/slide numbers for each content piece
  • ✅ No External Dependencies: Pure Go implementation using only standard library
  • ✅ Command Line Tool: Convert documents from command line
  • ✅ Comprehensive Testing: Full test suite with real document samples

Command Line Usage

Install
go install github.com/yaoapp/gou/office/cmd
Convert Documents
# Convert a DOCX file
cmd convert document.docx

# Convert a PPTX file
cmd convert presentation.pptx

# Convert multiple files
cmd convert *.docx *.pptx

# Or use go run directly
cd cmd
go run main.go convert document.docx
Output Structure

For input file document.docx, the output will be:

document/
├── document.md          # Markdown content
├── metadata.json        # Document metadata and mapping
└── media/              # Extracted media files
    ├── image1.png
    ├── image2.jpg
    └── ...

The metadata.json file contains:

{
  "title": "Document Title",
  "author": "Author Name",
  "subject": "Document Subject",
  "keywords": "document, keywords",
  "pages": 5,
  "text_ranges": [
    {
      "start_pos": 0,
      "end_pos": 100,
      "page": 1,
      "type": "heading"
    }
  ],
  "media_refs": {
    "rId8": "media/image1.png",
    "rId10": "media/image2.png"
  },
  "files": {
    "markdown": "document.md",
    "metadata": "metadata.json",
    "media_dir": "media/"
  }
}

Library Usage

Basic Usage
package main

import (
    "fmt"
    "os"
    "github.com/yaoapp/gou/office"
)

func main() {
    // Create parser
    parser := office.NewParser()

    // Read document data
    data, err := os.ReadFile("document.docx")
    if err != nil {
        panic(err)
    }

    // Parse document
    result, err := parser.Parse(data)
    if err != nil {
        panic(err)
    }

    // Access the results
    fmt.Printf("Title: %s\n", result.Metadata.Title)
    fmt.Printf("Author: %s\n", result.Metadata.Author)
    fmt.Printf("Pages: %d\n", result.Metadata.Pages)
    fmt.Printf("Media files: %d\n", len(result.Media))

    // Print markdown content
    fmt.Println("Markdown Content:")
    fmt.Println(result.Markdown)

    // Access media files
    for _, media := range result.Media {
        fmt.Printf("Media: %s (%s, %d bytes)\n",
            media.Filename, media.Type, len(media.Content))
    }
}
Supported Formats
parser := office.NewParser()
formats := parser.GetSupportedFormats()
// Returns: ["docx", "pptx"]

Output Structure

ParseResult
type ParseResult struct {
    Markdown string     `json:"markdown"`  // Converted markdown text
    Metadata *Metadata  `json:"metadata"`  // Document metadata
    Media    []Media    `json:"media"`     // Extracted media files
}
Metadata
type Metadata struct {
    Title      string            `json:"title"`       // Document title
    Author     string            `json:"author"`      // Document author
    Subject    string            `json:"subject"`     // Document subject
    Keywords   string            `json:"keywords"`    // Document keywords
    Pages      int               `json:"pages"`       // Number of pages/slides
    TextRanges []TextRange       `json:"text_ranges"` // Text position tracking
    MediaRefs  map[string]string `json:"media_refs"`  // Media reference mapping
}
TextRange
type TextRange struct {
    StartPos int    `json:"start_pos"` // Start position in markdown
    EndPos   int    `json:"end_pos"`   // End position in markdown
    Page     int    `json:"page"`      // Page/slide number
    Type     string `json:"type"`      // Content type (text, heading, list, slide)
}
Media
type Media struct {
    ID       string `json:"id"`       // Unique media ID
    Type     string `json:"type"`     // Media type (image, video, audio)
    Format   string `json:"format"`   // File format (png, jpg, mp4, etc.)
    Content  []byte `json:"content"`  // File content bytes
    Filename string `json:"filename"` // Original filename
    RefID    string `json:"ref_id"`   // Reference ID for linking
}

DOCX Features

  • Text Extraction: Plain text and formatted content
  • Heading Detection: Automatic heading level detection (H1-H6)
  • Formatting: Bold, italic, and combined formatting
  • Media Support: Images, videos, audio files
  • Metadata: Title, author, subject, keywords
  • Text Ranges: Precise position tracking

PPTX Features

  • Slide Extraction: Individual slide processing
  • Shape Processing: Text boxes, titles, content shapes
  • Slide Separators: Clear slide boundaries in markdown
  • Title Detection: Automatic title shape recognition
  • Media Support: All embedded media types
  • Slide Numbering: Proper slide sequence tracking

Performance

Benchmarks on Apple M2 Max:

  • DOCX Parsing: ~8.1ms per document
  • PPTX Parsing: ~2.4ms per document

Testing

Run the test suite:

go test -v

Run benchmarks:

go test -bench=.

The package includes comprehensive tests with real document samples covering:

  • Document type detection
  • Content extraction
  • Media file handling
  • Text range tracking
  • Error handling
  • Performance benchmarks

Architecture

The package is structured with separate parsers for each document type:

  • office.go - Main parser interface and common functionality
  • docx.go - DOCX-specific parsing logic
  • pptx.go - PPTX-specific parsing logic
  • cmd.go - Command line tool implementation
  • cmd/ - Command line application
  • office_test.go - Comprehensive test suite
  • cmd_test.go - Command line tool tests

Implementation Details

Document Detection

The parser automatically detects document type by examining the internal file structure:

  • DOCX: Looks for word/document.xml
  • PPTX: Looks for ppt/presentation.xml
XML Parsing

Office documents are ZIP archives containing XML files. The parser:

  1. Extracts the ZIP archive
  2. Parses relevant XML files using Go's encoding/xml
  3. Handles namespaces and relationships
  4. Extracts text content and formatting
Media Extraction

Media files are extracted from:

  • DOCX: word/media/ directory
  • PPTX: ppt/media/ directory

Supported media types:

  • Images: PNG, JPG, JPEG, GIF, BMP, TIFF, WEBP
  • Videos: MP4, AVI, MOV, WMV, FLV
  • Audio: MP3, WAV, AAC, FLAC

License

This package is part of the Yao framework and follows the same licensing terms.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ProcessParse

func ProcessParse(process *process.Process) interface{}

ProcessParse office.Parse Parse an Office document (DOCX/PPTX) from a file path. Embedded media is extracted and saved as files to output_dir.

Args:

  • filePath string - Path to the Office document
  • config map[string]interface{} - Optional configuration

Config fields:

  • output_dir string - Directory for extracted media (optional, default: auto temp dir)

Returns: *ProcessParseResult - Parsed document with markdown, metadata, and media file paths

Note: If output_dir is not specified, a temp directory is created automatically. The caller is responsible for cleaning up the output directory when done.

Usage:

var result = Process("office.Parse", "/path/to/document.docx", {"output_dir": "/data/tmp"})
// Returns: {"markdown": "...", "metadata": {...}, "media": [{"path": "/data/tmp/image1.png", ...}]}

func ProcessParseBytes

func ProcessParseBytes(process *process.Process) interface{}

ProcessParseBytes office.ParseBytes Parse an Office document from base64-encoded data (for in-memory files). Embedded media is extracted and saved as files to output_dir.

Args:

  • data string - Base64-encoded file content
  • config map[string]interface{} - Optional configuration

Config fields:

  • output_dir string - Directory for extracted media (optional, default: auto temp dir)

Returns: *ProcessParseResult - Parsed document with markdown, metadata, and media file paths

Note: The base64 decode + parse will hold the entire file in memory. For very large files (>100MB), prefer using office.Parse with a file path instead. If output_dir is not specified, a temp directory is created automatically. The caller is responsible for cleaning up the output directory when done.

Usage:

var result = Process("office.ParseBytes", "UEsDBBQAAAAIAA...", {"output_dir": "/data/tmp"})
// Returns: {"markdown": "...", "metadata": {...}, "media": [{"path": "/data/tmp/image1.png", ...}]}

func RunCommand

func RunCommand()

RunCommand runs the command line interface

Types

type CommandLineConverter

type CommandLineConverter struct {
	// contains filtered or unexported fields
}

CommandLineConverter handles command line operations

func NewCommandLineConverter

func NewCommandLineConverter() *CommandLineConverter

NewCommandLineConverter creates a new command line converter

func (*CommandLineConverter) ConvertFile

func (c *CommandLineConverter) ConvertFile(inputPath string) error

ConvertFile converts a single Office document to markdown and saves to output directory

type DocxBody

type DocxBody struct {
	XMLName    xml.Name        `xml:"body"`
	Paragraphs []DocxParagraph `xml:"p"`
}

DocxBody represents the document body

type DocxBold

type DocxBold struct {
	XMLName xml.Name `xml:"b"`
}

DocxBold represents bold formatting

type DocxCoreProperties

type DocxCoreProperties struct {
	XMLName     xml.Name `xml:"coreProperties"`
	Title       string   `xml:"title"`
	Subject     string   `xml:"subject"`
	Creator     string   `xml:"creator"`
	Keywords    string   `xml:"keywords"`
	Description string   `xml:"description"`
}

DocxCoreProperties represents document core properties

type DocxDocument

type DocxDocument struct {
	XMLName xml.Name `xml:"document"`
	Body    DocxBody `xml:"body"`
}

DocxDocument represents the main document structure

type DocxDrawing

type DocxDrawing struct {
	XMLName xml.Name `xml:"drawing"`
}

DocxDrawing represents embedded drawings/images

type DocxItalic

type DocxItalic struct {
	XMLName xml.Name `xml:"i"`
}

DocxItalic represents italic formatting

type DocxPPr

type DocxPPr struct {
	XMLName xml.Name   `xml:"pPr"`
	PStyle  DocxPStyle `xml:"pStyle"`
}

DocxPPr represents paragraph properties

type DocxPStyle

type DocxPStyle struct {
	XMLName xml.Name `xml:"pStyle"`
	Val     string   `xml:"val,attr"`
}

DocxPStyle represents paragraph style

type DocxParagraph

type DocxParagraph struct {
	XMLName xml.Name  `xml:"p"`
	PPr     DocxPPr   `xml:"pPr"`
	Runs    []DocxRun `xml:"r"`
}

DocxParagraph represents a paragraph in the document

type DocxRPr

type DocxRPr struct {
	XMLName xml.Name    `xml:"rPr"`
	Bold    *DocxBold   `xml:"b"`
	Italic  *DocxItalic `xml:"i"`
}

DocxRPr represents run properties (formatting)

type DocxRelationship

type DocxRelationship struct {
	XMLName xml.Name `xml:"Relationship"`
	ID      string   `xml:"Id,attr"`
	Type    string   `xml:"Type,attr"`
	Target  string   `xml:"Target,attr"`
}

DocxRelationship represents a single relationship

type DocxRelationships

type DocxRelationships struct {
	XMLName       xml.Name           `xml:"Relationships"`
	Relationships []DocxRelationship `xml:"Relationship"`
}

DocxRelationships represents document relationships

type DocxRun

type DocxRun struct {
	XMLName xml.Name    `xml:"r"`
	RPr     DocxRPr     `xml:"rPr"`
	Text    []DocxText  `xml:"t"`
	Drawing DocxDrawing `xml:"drawing"`
}

DocxRun represents a run of text with formatting

type DocxText

type DocxText struct {
	XMLName xml.Name `xml:"t"`
	Value   string   `xml:",chardata"`
}

DocxText represents text content

type FileParser

type FileParser interface {
	Parse(data []byte) (*ParseResult, error)
	GetSupportedFormats() []string
}

FileParser interface for Office document parsing

type Media

type Media struct {
	ID       string `json:"id"`
	Type     string `json:"type"`     // image, video, audio
	Format   string `json:"format"`   // png, jpg, mp4, etc.
	Content  []byte `json:"content"`  // File content
	Filename string `json:"filename"` // Original filename
	RefID    string `json:"ref_id"`   // Reference ID
}

Media represents a media file within the document

type Metadata

type Metadata struct {
	Title      string            `json:"title"`
	Author     string            `json:"author"`
	Subject    string            `json:"subject"`
	Keywords   string            `json:"keywords"`
	Pages      int               `json:"pages"`
	TextRanges []TextRange       `json:"text_ranges"`
	MediaRefs  map[string]string `json:"media_refs"` // Media reference mapping
}

Metadata contains document metadata and text range information

type ParseResult

type ParseResult struct {
	Markdown string    `json:"markdown"`
	Metadata *Metadata `json:"metadata"`
	Media    []Media   `json:"media"`
}

ParseResult represents the result of parsing an Office document

type Parser

type Parser struct {
	// contains filtered or unexported fields
}

Parser handles Office document parsing

func NewParser

func NewParser() *Parser

NewParser creates a new Office parser instance

func (*Parser) GetSupportedFormats

func (p *Parser) GetSupportedFormats() []string

GetSupportedFormats returns the list of supported document formats

func (*Parser) Parse

func (p *Parser) Parse(data []byte) (*ParseResult, error)

Parse parses an Office document from byte data

type PptxCNvPr

type PptxCNvPr struct {
	XMLName xml.Name `xml:"cNvPr"`
	Name    string   `xml:"name,attr"`
}

PptxCNvPr represents common non-visual properties

type PptxCSld

type PptxCSld struct {
	XMLName xml.Name   `xml:"cSld"`
	SpTree  PptxSpTree `xml:"spTree"`
}

PptxCSld represents the common slide data

type PptxCoreProperties

type PptxCoreProperties struct {
	XMLName     xml.Name `xml:"coreProperties"`
	Title       string   `xml:"title"`
	Subject     string   `xml:"subject"`
	Creator     string   `xml:"creator"`
	Keywords    string   `xml:"keywords"`
	Description string   `xml:"description"`
}

PptxCoreProperties represents presentation core properties

type PptxNvSpPr

type PptxNvSpPr struct {
	XMLName xml.Name  `xml:"nvSpPr"`
	CNvPr   PptxCNvPr `xml:"cNvPr"`
}

PptxNvSpPr represents non-visual shape properties

type PptxPPr

type PptxPPr struct {
	XMLName xml.Name `xml:"pPr"`
	Level   string   `xml:"lvl,attr"`
}

PptxPPr represents paragraph properties

type PptxParagraph

type PptxParagraph struct {
	XMLName xml.Name  `xml:"p"`
	PPr     PptxPPr   `xml:"pPr"`
	Runs    []PptxRun `xml:"r"`
}

PptxParagraph represents a paragraph in text body

type PptxPresentation

type PptxPresentation struct {
	XMLName    xml.Name       `xml:"presentation"`
	SlideIDLst PptxSlideIDLst `xml:"sldIdLst"`
}

PptxPresentation represents the main presentation structure

type PptxRPr

type PptxRPr struct {
	XMLName xml.Name `xml:"rPr"`
	Bold    string   `xml:"b,attr"`
	Italic  string   `xml:"i,attr"`
}

PptxRPr represents run properties

type PptxRelationship

type PptxRelationship struct {
	XMLName xml.Name `xml:"Relationship"`
	ID      string   `xml:"Id,attr"`
	Type    string   `xml:"Type,attr"`
	Target  string   `xml:"Target,attr"`
}

PptxRelationship represents a single relationship

type PptxRelationships

type PptxRelationships struct {
	XMLName       xml.Name           `xml:"Relationships"`
	Relationships []PptxRelationship `xml:"Relationship"`
}

PptxRelationships represents presentation relationships

type PptxRun

type PptxRun struct {
	XMLName xml.Name `xml:"r"`
	RPr     PptxRPr  `xml:"rPr"`
	Text    string   `xml:"t"`
}

PptxRun represents a run of text

type PptxShape

type PptxShape struct {
	XMLName xml.Name   `xml:"sp"`
	TxBody  PptxTxBody `xml:"txBody"`
	NvSpPr  PptxNvSpPr `xml:"nvSpPr"`
}

PptxShape represents a shape in the slide

type PptxSlide

type PptxSlide struct {
	XMLName xml.Name `xml:"sld"`
	CSld    PptxCSld `xml:"cSld"`
}

PptxSlide represents a slide

type PptxSlideID

type PptxSlideID struct {
	XMLName xml.Name `xml:"sldId"`
	ID      string   `xml:"id,attr"`
}

PptxSlideID represents a slide ID reference

type PptxSlideIDLst

type PptxSlideIDLst struct {
	XMLName  xml.Name      `xml:"sldIdLst"`
	SlideIds []PptxSlideID `xml:"sldId"`
}

PptxSlideIDLst represents the list of slide IDs

type PptxSpTree

type PptxSpTree struct {
	XMLName xml.Name    `xml:"spTree"`
	Shapes  []PptxShape `xml:"sp"`
}

PptxSpTree represents the shape tree

type PptxTxBody

type PptxTxBody struct {
	XMLName    xml.Name        `xml:"txBody"`
	Paragraphs []PptxParagraph `xml:"p"`
}

PptxTxBody represents text body

type ProcessMediaEntry

type ProcessMediaEntry struct {
	ID       string `json:"id"`
	Type     string `json:"type"`     // "image", "video", "audio"
	Format   string `json:"format"`   // "png", "jpeg", "gif", etc.
	Filename string `json:"filename"` // Original filename
	Path     string `json:"path"`     // OS file path where media is saved
}

ProcessMediaEntry represents a media entry with file path (no base64).

type ProcessParseResult

type ProcessParseResult struct {
	Markdown string              `json:"markdown"`
	Metadata *Metadata           `json:"metadata"`
	Media    []ProcessMediaEntry `json:"media"`
}

ProcessParseResult is the result returned by office process handlers. Media files are saved to output_dir; media[].path contains the file path.

type TextRange

type TextRange struct {
	StartPos int    `json:"start_pos"`
	EndPos   int    `json:"end_pos"`
	Page     int    `json:"page"`
	Type     string `json:"type"` // text, heading, list, etc.
}

TextRange represents a text range with position and page information

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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