import Foundation #if os(macOS) import AppKit typealias DocxFont = NSFont typealias DocxColor = NSColor #else import UIKit typealias DocxFont = UIFont typealias DocxColor = UIColor #endif /// Word's `.docx` from styled text: paragraphs with their runs' fonts, colors and links, and /// tables from the text's table blocks, which the system's own writer leaves out. iOS's HTML /// import keeps no tables, so there `tables` holds them, each standing for a paragraph that is /// its `marker` alone. enum DocxWriter { static func marker(_ index: Int) -> String { "\u{E000}\(index)\u{E001}" } static func data(from text: NSAttributedString, tables: [String] = []) -> Data { var links: [String] = [] let body = paragraphs(text, tables: tables, links: &links) let document = """ \(body)\ \ """ let relationships = links.enumerated().map { index, url in "" }.joined() var zip = ZipWriter() zip.add("[Content_Types].xml", """ \ \ \ \ """) zip.add("_rels/.rels", """ \ \ """) zip.add("word/_rels/document.xml.rels", """ \(relationships) """) zip.add("word/document.xml", document) return zip.data() } /// Paragraphs in order, consecutive ones in the same table gathered into ``. /// A `` of rows of cells, each cell its paragraphs. static func table(_ rows: [[String]], columns: Int) -> String { var out = "" + ["top", "left", "bottom", "right", "insideH", "insideV"].map { "" }.joined() + "" out += "" + String(repeating: "", count: columns) + "" for row in rows { out += "" for column in 0..") + "" } out += "" } return out + "" } private static func paragraphs(_ text: NSAttributedString, tables: [String], links: inout [String]) -> String { let string = text.string as NSString var out = "" #if os(macOS) var table: (block: NSTextTable, cells: [[Int: [String]]])? func flushTable() { guard let current = table else { return } let columns = max(current.block.numberOfColumns, current.cells.map { ($0.keys.max() ?? 0) + 1 }.max() ?? 1) out += Self.table(current.cells.map { row in (0.. String { var properties = "" if let style { switch style.alignment { case .center: properties += "" case .right: properties += "" default: break } let left = Int(style.headIndent * 20), first = Int((style.firstLineHeadIndent - style.headIndent) * 20) if left != 0 || first != 0 { properties += "" } properties += "" if !style.tabStops.isEmpty { properties += "" + style.tabStops.map { "" }.joined() + "" } } var runs = "" text.enumerateAttributes(in: range, options: []) { attributes, runRange, _ in var piece = (text.string as NSString).substring(with: runRange) piece = piece.trimmingCharacters(in: CharacterSet(charactersIn: "\n\r")) guard !piece.isEmpty else { return } var run = run(piece, attributes) let link = (attributes[.link] as? URL)?.absoluteString ?? (attributes[.link] as? String) if let link { links.append(link) run = "\(run)" } runs += run } return "\(properties)\(runs)" } private static func run(_ piece: String, _ attributes: [NSAttributedString.Key: Any]) -> String { var properties = "" if let font = attributes[.font] as? DocxFont { let traits = self.traits(font) let name = traits.mono ? "Menlo" : traits.family properties += "" if traits.bold { properties += "" } if traits.italic { properties += "" } properties += "" } if let color = (attributes[.foregroundColor] as? DocxColor).flatMap(rgba) { properties += "" } if (attributes[.underlineStyle] as? Int ?? 0) != 0 { properties += "" } if (attributes[.strikethroughStyle] as? Int ?? 0) != 0 { properties += "" } if let background = (attributes[.backgroundColor] as? DocxColor).flatMap(rgba), background.a > 0.05 { properties += "" } if let offset = attributes[.baselineOffset] as? Double, offset != 0 { properties += " 0 ? "superscript" : "subscript")\"/>" } // Tabs and line breaks are elements of their own. var content = "" var textRun = "" func flush() { if !textRun.isEmpty { content += "\(escape(textRun))" } textRun = "" } for character in piece { switch character { case "\t": flush(); content += "" case "\u{2028}", "\n": flush(); content += "" default: textRun.append(character) } } flush() return "\(properties)\(content)" } private static func traits(_ font: DocxFont) -> (bold: Bool, italic: Bool, mono: Bool, family: String) { let traits = font.fontDescriptor.symbolicTraits #if os(macOS) return (traits.contains(.bold), traits.contains(.italic), traits.contains(.monoSpace), font.familyName ?? "Helvetica Neue") #else return (traits.contains(.traitBold), traits.contains(.traitItalic), traits.contains(.traitMonoSpace), font.familyName) #endif } /// The color's sRGB components and alpha. private static func rgba(_ color: DocxColor) -> (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat)? { #if os(macOS) guard let c = color.usingColorSpace(.sRGB) else { return nil } return (c.redComponent, c.greenComponent, c.blueComponent, c.alphaComponent) #else var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0 guard color.getRed(&r, green: &g, blue: &b, alpha: &a) else { return nil } return (r, g, b, a) #endif } /// `#rrggbb` of the color laid on white paper: Word has no transparency. private static func hex(_ color: (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat)) -> String { func on(_ c: CGFloat) -> Int { Int(((c * color.a + (1 - color.a)) * 255).rounded()) } return String(format: "%02X%02X%02X", on(color.r), on(color.g), on(color.b)) } static func escape(_ s: String) -> String { s.replacingOccurrences(of: "&", with: "&").replacingOccurrences(of: "<", with: "<") .replacingOccurrences(of: ">", with: ">").replacingOccurrences(of: "\"", with: """) } } /// A zip archive with stored (uncompressed) entries, as `.docx` files are read. struct ZipWriter { private var entries: [(name: Data, data: Data, crc: UInt32, offset: UInt32)] = [] private var archive = Data() mutating func add(_ name: String, _ text: String) { let data = Data(text.utf8) let nameData = Data(name.utf8) let crc = Self.crc32(data) let offset = UInt32(archive.count) archive += Self.le32(0x04034b50) + Self.le16(20) + Self.le16(0) + Self.le16(0) + Self.le16(0) + Self.le16(0x21) archive += Self.le32(crc) + Self.le32(UInt32(data.count)) + Self.le32(UInt32(data.count)) archive += Self.le16(UInt16(nameData.count)) + Self.le16(0) + nameData + data entries.append((nameData, data, crc, offset)) } func data() -> Data { var central = Data() for entry in entries { central += Self.le32(0x02014b50) + Self.le16(20) + Self.le16(20) + Self.le16(0) + Self.le16(0) + Self.le16(0) + Self.le16(0x21) central += Self.le32(entry.crc) + Self.le32(UInt32(entry.data.count)) + Self.le32(UInt32(entry.data.count)) central += Self.le16(UInt16(entry.name.count)) + Self.le16(0) + Self.le16(0) + Self.le16(0) + Self.le16(0) + Self.le32(0) central += Self.le32(entry.offset) + entry.name } var end = Self.le32(0x06054b50) + Self.le16(0) + Self.le16(0) + Self.le16(UInt16(entries.count)) + Self.le16(UInt16(entries.count)) end += Self.le32(UInt32(central.count)) + Self.le32(UInt32(archive.count)) + Self.le16(0) return archive + central + end } private static func le16(_ v: UInt16) -> Data { withUnsafeBytes(of: v.littleEndian) { Data($0) } } private static func le32(_ v: UInt32) -> Data { withUnsafeBytes(of: v.littleEndian) { Data($0) } } private static let table: [UInt32] = (0..<256).map { n in var c = UInt32(n) for _ in 0..<8 { c = c & 1 != 0 ? 0xEDB88320 ^ (c >> 1) : c >> 1 } return c } static func crc32(_ data: Data) -> UInt32 { var c: UInt32 = 0xFFFFFFFF for byte in data { c = table[Int((c ^ UInt32(byte)) & 0xFF)] ^ (c >> 8) } return c ^ 0xFFFFFFFF } }