nambu.devGitHub ↗

SwiftDocuments

Read Word documents
in Swift

Read Word DOCX / DOCM files and work with their text, formatting and tables as Swift value types. Like SwiftSheets, the library aims to handle different file formats through a common model.

Version 1.0.0. The documented reading API follows semantic versioning.

Open source / MIT Swift 6.2+macOS 14+ / iOS 17+ No external Swift package dependencies

Starting with Word reading

Extract document structure

Read paragraphs, text formatting, tables and merged cells, hyperlinks and image references. Load image data when needed.

Look beyond the main text

Read headers, footers, footnotes, endnotes, comments and revisions. Warnings identify unsupported content and reference issues.

Choose how to read

Use read for a full document and inspect for package information. Use scan to process main-body blocks in order without retaining completed body blocks.

scan still keeps the input file, expanded main XML and related document information in memory. Its memory use is not constant.

Extract text with a few lines

Read a document

import Foundation
import SwiftDocuments

let url = URL(fileURLWithPath: "report.docx")
let result = try Document.read(contentsOf: url)
print(result.document.plainText)

for warning in result.warnings {
    print(warning.message)
}

Process the body one block at a time

import Foundation
import SwiftDocuments

let url = URL(fileURLWithPath: "report.docx")
let result = try Document.scan(contentsOf: url) { block in
    print(block.plainText)
}
print(result.blocksRead)

These examples read a local report.docx file. Swift does not run in the browser.

Install with Swift Package Manager

Depend on version 1.0.0 or later from the public repository.

Add the package to dependencies and its product to your target dependencies.

// Package.swift
dependencies: [
    .package(
        url: "https://github.com/nanbu/SwiftDocuments.git",
        from: "1.0.0"
    )
]

// Target dependencies
.product(name: "SwiftDocuments", package: "SwiftDocuments")

Formats and development scope

Format Status Details
DOCX / DOCM Reader implemented Word document formats. Macros in DOCM files are never executed.
ODT Partial reader implemented Reads text, formatting, tables, image references and related stories, with LibreOffice-produced documents verified.
Pages Partial reader implemented Reads modern IWA body text, basic formatting, headers, footers, anchored tables and inline images. A fictional DOCX imported and saved by Pages Creator Studio 15.4 is verified; complex layout and formatting remain partial.

Version 1.0 focuses on reading. Writing, format conversion, page rendering and layout, legacy .doc files and encrypted documents are not supported.

Explore the code and specifications