#if os(macOS) import AppKit import Foundation /// 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. enum DocxWriter { static func data(from text: NSAttributedString) -> Data { var links: [String] = [] let body = paragraphs(text, 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 ``. private static func paragraphs(_ text: NSAttributedString, links: inout [String]) -> String { let string = text.string as NSString var out = "" var table: (block: NSTextTable, cells: [[Int: [String]]])? func flushTable() { guard let current = table else { return } out += "" + ["top", "left", "bottom", "right", "insideH", "insideV"].map { "" }.joined() + "" let columns = max(current.block.numberOfColumns, current.cells.map { ($0.keys.max() ?? 0) + 1 }.max() ?? 1) out += "" + String(repeating: "", count: columns) + "" for row in current.cells { out += "" for column in 0..") + "" } out += "" } out += "" table = nil } var location = 0 while location < string.length { let range = string.paragraphRange(for: NSRange(location: location, length: 0)) location = NSMaxRange(range) let style = text.attribute(.paragraphStyle, at: range.location, effectiveRange: nil) as? NSParagraphStyle let paragraph = self.paragraph(text, range, style, links: &links) if let cell = style?.textBlocks.compactMap({ $0 as? NSTextTableBlock }).last { if table?.block !== cell.table { flushTable() table = (cell.table, []) } while table!.cells.count <= cell.startingRow { table!.cells.append([:]) } table!.cells[cell.startingRow][cell.startingColumn, default: []].append(paragraph) } else { flushTable() out += paragraph } } flushTable() return out } private static func paragraph(_ text: NSAttributedString, _ range: NSRange, _ style: NSParagraphStyle?, links: inout [String]) -> 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? NSFont { let traits = font.fontDescriptor.symbolicTraits let name = traits.contains(.monoSpace) ? "Menlo" : (font.familyName ?? "Helvetica Neue") properties += "" if traits.contains(.bold) { properties += "" } if traits.contains(.italic) { properties += "" } properties += "" } if let color = (attributes[.foregroundColor] as? NSColor)?.usingColorSpace(.sRGB) { properties += "" } if (attributes[.underlineStyle] as? Int ?? 0) != 0 { properties += "" } if (attributes[.strikethroughStyle] as? Int ?? 0) != 0 { properties += "" } if let background = (attributes[.backgroundColor] as? NSColor)?.usingColorSpace(.sRGB), background.alphaComponent > 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)" } /// `#rrggbb` of the color laid on white paper: Word has no transparency. private static func hex(_ color: NSColor) -> String { let a = color.alphaComponent func on(_ c: CGFloat) -> Int { Int(((c * a + (1 - a)) * 255).rounded()) } return String(format: "%02X%02X%02X", on(color.redComponent), on(color.greenComponent), on(color.blueComponent)) } 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 } } #endif