A small framework that converts NSAttributedString to .docx Word files on iOS and macOS.
On iOS, NSAttributedString.DocumentType
supports only HTML and Rich Text, while on macOS .doc and .docx are available options. Even then .docx exporter on macOS supports only a subset of the attributes os NSAttributedString.
This library is used in SimpleFurigana for macOS and SimpleFurigana for iOS, hence the focus on furigana annotation export.
Add
.package(name: "DocX", url: "https://github.com/shinjukunian/DocX.git", .branch("master"))
to dependencies
in your Package.swift
file. This requires Swift 5.3, which shipped with Xcode12.
Alternatively, add DocX
in Xcode via File->Swift Packages->Add Package Dependency
, paste https://github.com/shinjukunian/DocX.git
as URL and specify master
as branch.
let string = NSAttributedString(string: "This is a string", attributes: [.font: UIFont.systemFont(ofSize: UIFont.systemFontSize), .backgroundColor: UIColor.blue])
let url = URL(fileURLWithPath:"myPath")
try? string.writeDocX(to: url)
See the attached sample projects (for iOS and macOS) for usage and limitations.
On iOS, DocX also includes a UIActivityItemProvider
subclass (DocXActivityItemProvider
) for exporting .docx files through UIActivityViewController
.
A sample output on macOS opened in Word365.
A sample output on iOS opened in Word for iOS. Furigana annotations are preserved. The link is clickable. Please note that Quicklook (on both platforms) only supports a limited number of attributes.
- most things in
NSAttributedString.Key
exceptNSAttributedString.Key.expansion
NSAttributedString.Key.kern
NSAttributedString.Key.ligature
NSAttributedString.Key.obliqueness
NSAttributedString.Key.superscript
(macOS only, doesnt really work for most fonts anyway)NSAttributedString.Key.textEffect
CTRubyAnnotation
for furigana (ruby) annotations in CoreText
Some attributes don't have a direct correspondence. For example NSAttributedString
does (typically) not have the concept of a page size.
- my fork of AEXML, many thanks to the original author tadija
- ZipArchive. I could not get any of the native Swift Zip libraries to work with the .docx folder structure.
- WKDocReader to read old-school .doc files
- BSDocxRipperZipper which supports both reading and writing, but only for a subset of attributes.
- OfficeOpenXML Specification
- this blog post on Ruby annotations
- this article on the file structure of the .docx format
MIT