Repository Public
1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocDOCX/DocxExporter.swift3// Description: WordprocessingML export, entry point and package level: assembles the OPC package (content types, relationships,4// document, styles, numbering, settings, notes, comments, headers, media, properties, preserved parts, ORIX extras).5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import DocModel10import DocContainer1112public struct DocxExportOptions: Sendable {13 /// Formats citations and the bibliography. Without it citations show their keys and the bibliography a plain list.14 public var citations: (any CitationFormatting)?15 /// Formatted page number of a paragraph id, when the document has been laid out (cached values of page references and the contents).16 public var pageOf: (@Sendable (String) -> String?)?17 /// Total number of pages, when known (cached value of NUMPAGES).18 public var pageCount: Int?19 public init() {}20}2122public enum DocxExporter {23 public static func export(_ doc: DocumentModel, options: DocxExportOptions = .init()) throws -> ExportResult {24 try DocxStack.run {25 let ctx = DocxExportContext(doc: doc, options: options, preflight: false)26 let data = try ctx.build()27 return ExportResult(data: data, warnings: ctx.warnings.warnings)28 }29 }3031 /// What would be lost or approximated if this document were exported to DOCX (shown to the user BEFORE exporting).32 /// The most severe warnings come first.33 public static func preflight(_ doc: DocumentModel) -> [FormatWarning] {34 let warnings: [FormatWarning]35 do {36 warnings = try DocxStack.run {37 let ctx = DocxExportContext(doc: doc, options: DocxExportOptions(), preflight: true)38 _ = try ctx.build()39 return ctx.warnings.warnings40 }41 } catch {42 return [FormatWarning(.dropped, feature: "DOCX export", detail: "The document cannot be exported: \(error)")]43 }44 return warnings.enumerated().sorted { a, b in45 a.element.severity != b.element.severity ? a.element.severity > b.element.severity : a.offset < b.offset46 }.map(\.element)47 }48}4950/// Relationships of one part.51final class DocxPartRels {52 private(set) var items: [(id: String, type: String, target: String, external: Bool)] = []5354 @discardableResult55 func add(type: String, target: String, external: Bool = false) -> String {56 if let e = items.first(where: { $0.type == type && $0.target == target && $0.external == external }) { return e.id }57 let id = "rId\(items.count + 1)"58 items.append((id, type, target, external))59 return id60 }61 var isEmpty: Bool { items.isEmpty }62 var xml: String {63 var s = xmlDeclaration + "<Relationships xmlns=\"\(XMLNS.rel)\">"64 for i in items {65 s += xmlTag("Relationship", [("Id", i.id), ("Type", i.type), ("Target", i.target), ("TargetMode", i.external ? "External" : nil)])66 }67 return s + "</Relationships>"68 }69}7071/// A part that holds text (document, header, footer, notes).72final class DocxPart {73 enum Kind { case body, header, footer, note }74 let name: String75 let kind: Kind76 let rels = DocxPartRels()77 init(name: String, kind: Kind) { self.name = name; self.kind = kind }78}7980final class DocxExportContext {81 let doc: DocumentModel82 let options: DocxExportOptions83 let preflight: Bool84 let numbering: Numbering85 var warnings = WarningCollector()8687 var nextID = 1 // revisions, bookmarks88 var nextDrawingID = 189 var media: [String: String] = [:] // asset id → file name inside word/media90 var mediaOrder: [(name: String, asset: String)] = []91 var listNumIDs: [String: Int] = [:]92 var headingNumID: Int?93 var footnoteIDs: [String: Int] = [:]94 var endnoteIDs: [String: Int] = [:]95 var footnoteOrder: [String] = []96 var endnoteOrder: [String] = []97 var commentWordIDs: [String: [Int]] = [:] // comment id → [own id, reply ids…]98 var commentStarts: [String: [String]] = [:] // "paragraphID#run" → comment ids99 var commentEnds: [String: [String]] = [:]100 var orphanComments: [String] = []101 var refKinds: [String: Set<Character>] = [:] // target paragraph id → bookmark kinds needed102 var refSafeIDs: [String: String] = [:]103 var bodyParagraphIDs = Set<String>()104 var tableStyleIDs: [(style: TableStyle, id: String, name: String)] = []105 var headerParts: [(part: DocxPart, xml: String)] = []106 var headerSeen: [String: Bool] = [:]107108 init(doc: DocumentModel, options: DocxExportOptions, preflight: Bool) {109 self.doc = doc; self.options = options; self.preflight = preflight110 self.numbering = Numbering(doc)111 }112113 func warn(_ s: FormatWarning.Severity, _ feature: String, _ detail: String) { warnings.add(s, feature, detail) }114 func takeID() -> Int { defer { nextID += 1 }; return nextID }115116 static let rootNamespaces: [(String, String?)] = [117 ("xmlns:w", XMLNS.w), ("xmlns:r", XMLNS.r), ("xmlns:m", XMLNS.m), ("xmlns:wp", XMLNS.wp), ("xmlns:a", XMLNS.a), ("xmlns:pic", XMLNS.pic),118 ("xmlns:mc", XMLNS.mc), ("xmlns:w14", XMLNS.w14), ("xmlns:w15", XMLNS.w15), ("xmlns:wps", XMLNS.wps), ("xmlns:v", XMLNS.v), ("xmlns:o", XMLNS.o),119 ("mc:Ignorable", "w14 w15"),120 ]121122 // MARK: Build123124 func build() throws -> Data {125 prepare()126 let documentPart = DocxPart(name: "word/document.xml", kind: .body)127 let rootRels = DocxPartRels()128 var overrides: [(String, String)] = []129 var files: [(name: String, data: Data, compress: Bool)] = []130 func addXML(_ name: String, _ xml: String, type: String?) {131 files.append((name, Data(xml.utf8), true))132 if let type { overrides.append((name, type)) }133 }134135 rootRels.add(type: RelType.officeDocument, target: "word/document.xml")136 rootRels.add(type: RelType.coreProperties, target: "docProps/core.xml")137 documentPart.rels.add(type: RelType.styles, target: "styles.xml")138 documentPart.rels.add(type: RelType.numbering, target: "numbering.xml")139 documentPart.rels.add(type: RelType.settings, target: "settings.xml")140141 // The body comes first: it decides which notes, pictures, table styles and headers exist.142 let body = bodyXML(documentPart)143 let footnotesPart = DocxPart(name: "word/footnotes.xml", kind: .note)144 let endnotesPart = DocxPart(name: "word/endnotes.xml", kind: .note)145 let footnotes = notesXML(.footnote, part: footnotesPart)146 let endnotes = notesXML(.endnote, part: endnotesPart)147 if footnotes != nil { documentPart.rels.add(type: RelType.footnotes, target: "footnotes.xml") }148 if endnotes != nil { documentPart.rels.add(type: RelType.endnotes, target: "endnotes.xml") }149 let comments = commentsXML()150 if comments != nil {151 documentPart.rels.add(type: RelType.comments, target: "comments.xml")152 documentPart.rels.add(type: RelType.commentsExtended, target: "commentsExtended.xml")153 }154155 var background = ""156 if let bg = doc.pageSetup.background {157 background = xmlTag("w:background", [("w:color", bg.hexString)])158 if doc.sectionSetups.contains(where: { $0.background != bg }) {159 warn(.approximated, "Page background", "Word has one page colour per document; the colour of the first section is used everywhere.")160 }161 } else if doc.sectionSetups.contains(where: { $0.background != nil }) {162 warn(.dropped, "Page background", "Word has one page colour per document; section-specific page colours are not exported.")163 }164165 addXML("word/document.xml", xmlDeclaration + xmlTag("w:document", DocxExportContext.rootNamespaces, background + "<w:body>" + body + "</w:body>"), type: ContentType.main)166 addXML("word/styles.xml", stylesXML(), type: ContentType.styles)167 addXML("word/numbering.xml", numberingXML(), type: ContentType.numbering)168 addXML("word/settings.xml", settingsXML(hasFootnotes: footnotes != nil, hasEndnotes: endnotes != nil, hasBackground: !background.isEmpty), type: ContentType.settings)169 if let footnotes {170 addXML(footnotesPart.name, footnotes, type: ContentType.footnotes)171 if !footnotesPart.rels.isEmpty { addXML(OPC.relsPath(for: footnotesPart.name), footnotesPart.rels.xml, type: nil) }172 }173 if let endnotes {174 addXML(endnotesPart.name, endnotes, type: ContentType.endnotes)175 if !endnotesPart.rels.isEmpty { addXML(OPC.relsPath(for: endnotesPart.name), endnotesPart.rels.xml, type: nil) }176 }177 if let comments {178 addXML("word/comments.xml", comments.comments, type: ContentType.comments)179 addXML("word/commentsExtended.xml", comments.extended, type: ContentType.commentsExtended)180 }181 for (part, xml) in headerParts {182 addXML(part.name, xml, type: part.kind == .header ? ContentType.header : ContentType.footer)183 if !part.rels.isEmpty { addXML(OPC.relsPath(for: part.name), part.rels.xml, type: nil) }184 }185 addXML("docProps/core.xml", corePropertiesXML(), type: ContentType.core)186187 var imageExtensions = Set<String>()188 for (name, asset) in mediaOrder {189 guard let a = doc.assets[asset] else { continue }190 files.append(("word/media/" + name, a.data, false))191 imageExtensions.insert((name as NSString).pathExtension)192 }193194 // Preserved parts, re-validated: the model may come from an untrusted container.195 var maxItem = 0196 let preserved = doc.preservedParts.keys.sorted()197 var keptPreserved = Set<String>()198 for name in preserved where !name.contains("_rels/") {199 guard DocxImportContext.isPreservable(name), (try? ZipWriterProbe.validate(name)) != nil, let data = doc.preservedParts[name],200 (try? XMLTree.parse(data, part: name)) != nil else {201 warn(.dropped, "Preserved parts", "The preserved part \(name) cannot be written back safely and was left out.")202 continue203 }204 keptPreserved.insert(name)205 }206 for name in preserved where keptPreserved.contains(name) {207 let data = doc.preservedParts[name]!208 var type: String?209 if name == "docProps/app.xml" { type = ContentType.app; rootRels.add(type: RelType.extendedProperties, target: name) }210 else if name == "docProps/custom.xml" { type = ContentType.custom; rootRels.add(type: RelType.customProperties, target: name) }211 else if name == "word/fontTable.xml" { type = ContentType.fontTable; documentPart.rels.add(type: RelType.fontTable, target: "fontTable.xml") }212 else if name == "word/webSettings.xml" { type = ContentType.webSettings; documentPart.rels.add(type: RelType.webSettings, target: "webSettings.xml") }213 else if name.hasPrefix("word/theme/") { type = ContentType.theme; documentPart.rels.add(type: RelType.theme, target: String(name.dropFirst(5))) }214 else if name.hasPrefix("customXml/itemProps") { type = ContentType.customXmlProps }215 else if name.hasPrefix("customXml/item") {216 documentPart.rels.add(type: RelType.customXml, target: "../" + name)217 if let n = Int(name.dropFirst("customXml/item".count).dropLast(4)) { maxItem = max(maxItem, n) }218 }219 if name.hasPrefix("customXml/itemProps"), let n = Int(name.dropFirst("customXml/itemProps".count).dropLast(4)) { maxItem = max(maxItem, n) }220 files.append((name, data, true))221 if let type { overrides.append((name, type)) }222 // The relationships of a preserved part are kept only when they stay inside the preserved set.223 let relsName = OPC.relsPath(for: name)224 if let relData = doc.preservedParts[relsName], let rels = try? OPC.parseRelationships(relData, part: name), !rels.isEmpty,225 rels.allSatisfy({ r in !r.external && OPC.resolve(target: r.target, from: name).map { keptPreserved.contains($0) } == true }) {226 files.append((relsName, relData, true))227 }228 }229230 // ORIX extras: the bibliography database and the settings Word has no place for, as a custom XML data part.231 let extras = OrixExtras(citationStyle: doc.settings.citationStyle, smartQuotes: doc.settings.smartQuotes, smartDashes: doc.settings.smartDashes,232 themeName: doc.styles.themeName, bibliography: doc.bibliography)233 let n = maxItem + 1234 addXML("customXml/item\(n).xml", extras.xml(), type: nil)235 addXML("customXml/itemProps\(n).xml", xmlDeclaration + xmlTag("ds:datastoreItem", [("ds:itemID", "{0F1E2D3C-4B5A-4978-8695-A4B3C2D1E0F9}"), ("xmlns:ds", "http://schemas.openxmlformats.org/officeDocument/2006/customXml")],236 xmlTag("ds:schemaRefs", [], xmlTag("ds:schemaRef", [("ds:uri", XMLNS.orix)]))), type: ContentType.customXmlProps)237 let itemRels = DocxPartRels()238 itemRels.add(type: RelType.customXmlProps, target: "itemProps\(n).xml")239 addXML("customXml/_rels/item\(n).xml.rels", itemRels.xml, type: nil)240 documentPart.rels.add(type: RelType.customXml, target: "../customXml/item\(n).xml")241242 addXML(OPC.relsPath(for: documentPart.name), documentPart.rels.xml, type: nil)243244 var types = xmlDeclaration + "<Types xmlns=\"\(XMLNS.ct)\">"245 types += xmlTag("Default", [("Extension", "rels"), ("ContentType", ContentType.rels)])246 types += xmlTag("Default", [("Extension", "xml"), ("ContentType", "application/xml")])247 for ext in imageExtensions.sorted() {248 types += xmlTag("Default", [("Extension", ext), ("ContentType", DocxMedia.mimeByExtension[ext] ?? "application/octet-stream")])249 }250 for (name, type) in overrides { types += xmlTag("Override", [("PartName", "/" + name), ("ContentType", type)]) }251 types += "</Types>"252253 var zip = ZipWriter()254 try zip.add("[Content_Types].xml", text: types)255 try zip.add("_rels/.rels", text: rootRels.xml)256 for f in files { try zip.add(f.name, f.data, compress: f.compress) }257 return zip.finalize()258 }259260 // MARK: Preparation261262 /// Everything that must be known before the first paragraph is written: list ids, comment ranges, cross-reference targets.263 func prepare() {264 for (i, l) in doc.lists.enumerated() where listNumIDs[l.id] == nil { listNumIDs[l.id] = i + 1 }265 if doc.styles.styles.contains(where: { $0.kind == .paragraph && $0.numbered }) { headingNumID = doc.lists.count + 1 }266267 // Comment ranges: first and last run that carry each comment, in reading order.268 var next = 0269 for c in doc.comments where commentWordIDs[c.id] == nil {270 commentWordIDs[c.id] = Array(next...(next + c.replies.count))271 next += c.replies.count + 1272 }273 var first: [String: String] = [:], last: [String: String] = [:]274 var seqParagraphs = Set<String>()275 func scan(_ p: Paragraph, body: Bool) {276 if body { bodyParagraphIDs.insert(p.id) }277 for (i, r) in p.runs.enumerated() {278 if case .field(.sequence)? = r.inline, !r.isDeleted { seqParagraphs.insert(p.id) }279 for id in r.comments where commentWordIDs[id] != nil {280 let key = "\(p.id)#\(i)"281 if first[id] == nil { first[id] = key }282 last[id] = key283 }284 }285 }286 doc.forEachBodyParagraph { p, _ in scan(p, body: true) }287 for id in numbering.footnoteOrder + numbering.endnoteOrder { for p in doc.notes[id]?.paragraphs ?? [] { scan(p, body: false) } }288 for c in doc.comments {289 if let f = first[c.id], let l = last[c.id] {290 commentStarts[f, default: []].append(c.id)291 commentEnds[l, default: []].append(c.id)292 } else {293 orphanComments.append(c.id)294 }295 }296 if !orphanComments.isEmpty {297 warn(.approximated, "Comments", "\(orphanComments.count) comment(s) without an anchor in the text are attached to the start of the document.")298 }299 var headerComments = false300 for su in doc.sectionSetups {301 for p in su.header.default + su.header.first + su.header.even + su.footer.default + su.footer.first + su.footer.even {302 if p.runs.contains(where: { !$0.comments.isEmpty }) { headerComments = true }303 }304 }305 if headerComments { warn(.dropped, "Comments", "Word does not allow comments in headers and footers; their anchors there are not exported.") }306307 // Cross-reference targets that are paragraphs get hidden bookmarks.308 var safeCounter = 0309 doc.forEachParagraphEverywhere { p, _, _ in310 for r in p.runs {311 guard case .crossRef(let ref)? = r.inline, self.numbering.bookmarks[ref.target] == nil, self.bodyParagraphIDs.contains(ref.target) else { continue }312 let hasSeq = seqParagraphs.contains(ref.target)313 let kind: Character314 switch ref.display {315 case .labelAndNumber: kind = hasSeq ? "L" : "T"316 case .number: kind = hasSeq ? "N" : "T"317 default: kind = "T"318 }319 self.refKinds[ref.target, default: []].insert(kind)320 if self.refSafeIDs[ref.target] == nil {321 if DocxConvention.isBookmarkSafe(ref.target) { self.refSafeIDs[ref.target] = ref.target } else {322 safeCounter += 1323 self.refSafeIDs[ref.target] = "x\(safeCounter)"324 }325 }326 }327 }328 }329330 // MARK: Styles331332 static let wordStyleNames: [String: String] = {333 var m: [String: String] = [StyleID.normal: "Normal", StyleID.title: "Title", StyleID.subtitle: "Subtitle", StyleID.quote: "Quote",334 StyleID.caption: "caption", StyleID.footnoteText: "footnote text", StyleID.header: "header", StyleID.footer: "footer",335 StyleID.bibliography: "Bibliography", StyleID.tocHeading: "TOC Heading", StyleID.listParagraph: "List Paragraph",336 StyleID.hyperlink: "Hyperlink", StyleID.strong: "Strong", StyleID.emphasis: "Emphasis"]337 for i in 1...9 { m[StyleID.heading(i)] = "heading \(i)"; m[StyleID.toc(i)] = "toc \(i)" }338 return m339 }()340341 func stylesXML() -> String {342 var s = xmlDeclaration + "<w:styles xmlns:w=\"\(XMLNS.w)\" xmlns:mc=\"\(XMLNS.mc)\" xmlns:w14=\"\(XMLNS.w14)\" mc:Ignorable=\"w14\">"343 s += "<w:docDefaults><w:rPrDefault>" + xmlTag("w:rPr", [], rPrInner(doc.styles.defaultChar, style: nil)) + "</w:rPrDefault><w:pPrDefault>"344 + xmlTag("w:pPr", [], pPrInner(style: nil, props: doc.styles.defaultPara)) + "</w:pPrDefault></w:docDefaults>"345 var usedNames = Set<String>()346 for st in doc.styles.styles {347 let builtIn = DocxExportContext.wordStyleNames[st.id]348 var name = builtIn ?? (st.name.isEmpty ? st.id : st.name)349 if usedNames.contains(name.lowercased()) { name = st.id }350 usedNames.insert(name.lowercased())351 var inner = xmlTag("w:name", [("w:val", name)])352 if builtIn != nil, !st.name.isEmpty, st.name != name { inner += xmlTag("w:aliases", [("w:val", st.name.replacingOccurrences(of: ",", with: " "))]) }353 if let b = st.basedOn, b != st.id { inner += xmlTag("w:basedOn", [("w:val", b)]) }354 if st.kind == .paragraph, let n = st.next { inner += xmlTag("w:next", [("w:val", n)]) }355 inner += "<w:qFormat/>"356 if st.kind == .paragraph {357 var numPr: String?358 if st.numbered, let numID = headingNumID {359 let level = doc.styles.styleProps(st.id).para.outlineLevel ?? 0360 if (1...9).contains(level) { numPr = "<w:numPr><w:ilvl w:val=\"\(level - 1)\"/><w:numId w:val=\"\(numID)\"/></w:numPr>" }361 else { warn(.dropped, "Numbered styles", "The style \"\(st.name)\" is numbered but is not a heading; its numbering is not exported.") }362 }363 let pPr = pPrInner(style: nil, props: st.para, numPr: numPr)364 if !pPr.isEmpty { inner += "<w:pPr>" + pPr + "</w:pPr>" }365 } else if st.para != .none {366 warn(.dropped, "Character styles", "Paragraph formatting stored in the character style \"\(st.name)\" is not exported.")367 }368 let rPr = rPrInner(st.char, style: nil)369 if !rPr.isEmpty { inner += "<w:rPr>" + rPr + "</w:rPr>" }370 s += xmlTag("w:style", [("w:type", st.kind == .paragraph ? "paragraph" : "character"), ("w:default", st.id == StyleID.normal && st.kind == .paragraph ? "1" : nil),371 ("w:customStyle", builtIn == nil ? "1" : nil), ("w:styleId", st.id)], inner)372 }373 s += "<w:style w:type=\"table\" w:default=\"1\" w:styleId=\"TableNormal\"><w:name w:val=\"Normal Table\"/><w:uiPriority w:val=\"99\"/><w:semiHidden/><w:unhideWhenUsed/>"374 + "<w:tblPr><w:tblInd w:w=\"0\" w:type=\"dxa\"/><w:tblCellMar><w:top w:w=\"0\" w:type=\"dxa\"/><w:left w:w=\"108\" w:type=\"dxa\"/><w:bottom w:w=\"0\" w:type=\"dxa\"/><w:right w:w=\"108\" w:type=\"dxa\"/></w:tblCellMar></w:tblPr></w:style>"375 for t in tableStyleIDs {376 var inner = xmlTag("w:name", [("w:val", t.name)]) + "<w:basedOn w:val=\"TableNormal\"/><w:uiPriority w:val=\"59\"/>"377 inner += "<w:tblPr><w:tblStyleRowBandSize w:val=\"1\"/>" + tableBordersXML(t.style) + cellMarginsXML(t.style.cellPadding) + "</w:tblPr>"378 if t.style.headerShading != nil || t.style.headerTextColor != nil {379 var cond = ""380 if let c = t.style.headerTextColor { cond += "<w:rPr>" + xmlTag("w:color", [("w:val", c.hexString)]) + "</w:rPr>" }381 if let f = t.style.headerShading { cond += "<w:tcPr>" + shadingXML(f) + "</w:tcPr>" }382 inner += xmlTag("w:tblStylePr", [("w:type", "firstRow")], cond)383 }384 if let f = t.style.bandedRowShading { inner += xmlTag("w:tblStylePr", [("w:type", "band1Horz")], "<w:tcPr>" + shadingXML(f) + "</w:tcPr>") }385 s += xmlTag("w:style", [("w:type", "table"), ("w:customStyle", "1"), ("w:styleId", t.id)], inner)386 }387 return s + "</w:styles>"388 }389390 func tableStyleID(_ style: TableStyle) -> String {391 if let e = tableStyleIDs.first(where: { $0.style == style }) { return e.id }392 var name = style.name.isEmpty ? "Table" : style.name393 let taken = Set(tableStyleIDs.map { $0.name.lowercased() } + doc.styles.styles.map { (DocxExportContext.wordStyleNames[$0.id] ?? $0.name).lowercased() } + ["normal table"])394 var k = 2395 let base = name396 while taken.contains(name.lowercased()) { name = "\(base) \(k)"; k += 1 }397 let id = "\(DocxConvention.tableStylePrefix)\(tableStyleIDs.count + 1)"398 tableStyleIDs.append((style, id, name))399 return id400 }401402 // MARK: Numbering403404 func numberingXML() -> String {405 let s = xmlDeclaration + "<w:numbering xmlns:w=\"\(XMLNS.w)\">"406 func level(_ i: Int, _ l: ListLevel, pStyle: String? = nil) -> String {407 let fmt: String408 switch l.format {409 case .decimal: fmt = "decimal"410 case .lowerAlpha: fmt = "lowerLetter"411 case .upperAlpha: fmt = "upperLetter"412 case .lowerRoman: fmt = "lowerRoman"413 case .upperRoman: fmt = "upperRoman"414 case .bullet: fmt = "bullet"415 case .none: fmt = "none"416 }417 var inner = xmlTag("w:start", [("w:val", String(l.start))]) + xmlTag("w:numFmt", [("w:val", fmt)])418 if let pStyle { inner += xmlTag("w:pStyle", [("w:val", pStyle)]) }419 inner += xmlTag("w:lvlText", [("w:val", l.pattern)]) + "<w:lvlJc w:val=\"left\"/>"420 inner += "<w:pPr>" + xmlTag("w:ind", [("w:left", DocxUnit.toTwips(l.indent)), ("w:hanging", DocxUnit.toTwips(l.hanging))]) + "</w:pPr>"421 return xmlTag("w:lvl", [("w:ilvl", String(i))], inner)422 }423 var abstracts = "", nums = ""424 for (i, l) in doc.lists.enumerated() {425 guard listNumIDs[l.id] == i + 1 else { continue }426 if l.levels.count > 9 { warn(.dropped, "Lists", "Word lists have nine levels; deeper levels are not exported.") }427 var inner = xmlTag("w:multiLevelType", [("w:val", l.levels.count > 1 ? "multilevel" : "singleLevel")])428 for (k, lv) in l.levels.prefix(9).enumerated() { inner += level(k, lv) }429 abstracts += xmlTag("w:abstractNum", [("w:abstractNumId", String(i))], inner)430 nums += xmlTag("w:num", [("w:numId", String(i + 1))], xmlTag("w:abstractNumId", [("w:val", String(i))]))431 }432 if let h = headingNumID {433 var inner = "<w:multiLevelType w:val=\"multilevel\"/>"434 for lvl in 1...9 {435 let owner = doc.styles.styles.first { $0.kind == .paragraph && $0.numbered && (doc.styles.styleProps($0.id).para.outlineLevel ?? 0) == lvl }436 let pattern = (1...lvl).map { "%\($0)" }.joined(separator: ".")437 inner += level(lvl - 1, ListLevel(format: .decimal, pattern: pattern, indent: 0, hanging: 0), pStyle: owner?.id)438 }439 abstracts += xmlTag("w:abstractNum", [("w:abstractNumId", String(h - 1))], inner)440 nums += xmlTag("w:num", [("w:numId", String(h))], xmlTag("w:abstractNumId", [("w:val", String(h - 1))]))441 }442 return s.appending(abstracts + nums + "</w:numbering>")443 }444445 // MARK: Settings and properties446447 func settingsXML(hasFootnotes: Bool, hasEndnotes: Bool, hasBackground: Bool) -> String {448 var s = xmlDeclaration + "<w:settings xmlns:w=\"\(XMLNS.w)\">"449 // Schema order matters to Word: displayBackgroundShape, trackRevisions, defaultTabStop, evenAndOddHeaders, footnotePr, endnotePr, compat.450 if hasBackground { s += "<w:displayBackgroundShape/>" }451 if doc.settings.trackChanges { s += "<w:trackRevisions/>" }452 s += "<w:defaultTabStop w:val=\"720\"/>"453 let setups = doc.sectionSetups454 if setups.contains(where: \.differentOddEven) {455 s += "<w:evenAndOddHeaders/>"456 if !setups.allSatisfy(\.differentOddEven) {457 warn(.approximated, "Odd and even headers", "Word applies different odd and even headers to the whole document, not to single sections.")458 }459 }460 if hasFootnotes { s += "<w:footnotePr><w:footnote w:id=\"-1\"/><w:footnote w:id=\"0\"/></w:footnotePr>" }461 if hasEndnotes { s += "<w:endnotePr><w:endnote w:id=\"-1\"/><w:endnote w:id=\"0\"/></w:endnotePr>" }462 s += "<w:compat><w:compatSetting w:name=\"compatibilityMode\" w:uri=\"http://schemas.microsoft.com/office/word\" w:val=\"15\"/></w:compat>"463 return s + "</w:settings>"464 }465466 func corePropertiesXML() -> String {467 let m = doc.meta468 var inner = ""469 inner += xmlTag("dc:title", [], XMLEscape.text(m.title))470 inner += xmlTag("dc:subject", [], XMLEscape.text(m.subject))471 inner += xmlTag("dc:creator", [], XMLEscape.text(m.author))472 inner += xmlTag("cp:keywords", [], XMLEscape.text(m.keywords.joined(separator: ", ")))473 inner += xmlTag("dc:language", [], XMLEscape.text(m.language))474 inner += xmlTag("dcterms:created", [("xsi:type", "dcterms:W3CDTF")], DocxDate.string(m.created))475 inner += xmlTag("dcterms:modified", [("xsi:type", "dcterms:W3CDTF")], DocxDate.string(m.modified))476 if m.keywords.contains(where: { $0.contains(",") || $0.contains(";") }) {477 warn(.approximated, "Keywords", "Keywords that contain a comma or a semicolon are split when the file is read back.")478 }479 return xmlDeclaration + xmlTag("cp:coreProperties", [("xmlns:cp", XMLNS.cp), ("xmlns:dc", XMLNS.dc), ("xmlns:dcterms", XMLNS.dcterms), ("xmlns:xsi", XMLNS.xsi)], inner)480 }481482 // MARK: Sections, headers and footers483484 func headerFooterXML(_ paragraphs: [Paragraph], part: DocxPart, watermark: String?) -> String {485 let root = part.kind == .header ? "w:hdr" : "w:ftr"486 var inner = ""487 let wm = watermark.map { watermarkRun($0) } ?? ""488 if paragraphs.isEmpty {489 inner = "<w:p>" + wm + "</w:p>"490 } else {491 for (i, p) in paragraphs.enumerated() { inner += paragraphXML(p, part: part, leading: i == 0 ? wm : "") }492 }493 return xmlDeclaration + xmlTag(root, DocxExportContext.rootNamespaces, inner)494 }495496 func watermarkRun(_ text: String) -> String {497 let shapetype = "<v:shapetype id=\"_x0000_t136\" coordsize=\"21600,21600\" o:spt=\"136\" adj=\"10800\" path=\"m@7,l@8,m@5,21600l@6,21600e\"><v:formulas><v:f eqn=\"sum #0 0 10800\"/><v:f eqn=\"prod #0 2 1\"/><v:f eqn=\"sum 21600 0 @1\"/><v:f eqn=\"sum 0 0 @2\"/><v:f eqn=\"sum 21600 0 @3\"/><v:f eqn=\"if @0 @3 0\"/><v:f eqn=\"if @0 21600 @1\"/><v:f eqn=\"if @0 0 @2\"/><v:f eqn=\"if @0 @4 21600\"/><v:f eqn=\"mid @5 @6\"/><v:f eqn=\"mid @8 @5\"/><v:f eqn=\"mid @7 @8\"/><v:f eqn=\"mid @6 @7\"/><v:f eqn=\"sum @6 0 @5\"/></v:formulas><v:path textpathok=\"t\" o:connecttype=\"custom\" o:connectlocs=\"@9,0;@10,10800;@11,21600;@12,10800\" o:connectangles=\"270,180,90,0\"/><v:textpath on=\"t\" fitshape=\"t\"/><v:handles><v:h position=\"#0,bottomRight\" xrange=\"6629,14971\"/></v:handles><o:lock v:ext=\"edit\" text=\"t\" shapetype=\"t\"/></v:shapetype>"498 let n = nextDrawingID499 nextDrawingID += 1500 let shape = xmlTag("v:shape", [("id", "\(DocxConvention.watermarkShapeID)\(n)"), ("o:spid", "_x0000_s\(2048 + n)"), ("type", "#_x0000_t136"),501 ("style", "position:absolute;margin-left:0;margin-top:0;width:412pt;height:137pt;rotation:315;z-index:-251658752;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin"),502 ("o:allowincell", "f"), ("fillcolor", "silver"), ("stroked", "f")],503 "<v:fill opacity=\".5\"/>" + xmlTag("v:textpath", [("style", "font-family:\"Helvetica\";font-size:1pt"), ("string", text)]))504 return "<w:r><w:rPr><w:noProof/></w:rPr><w:pict>" + shapetype + shape + "</w:pict></w:r>"505 }506507 /// `w:sectPr` of one section. `kind` is how the section starts (nil for the first one).508 func sectPrXML(_ setup: PageSetup, kind: SectionBreak.Kind?, document: DocxPart) -> String {509 var s = ""510 func reference(_ paragraphs: [Paragraph], _ type: String, header: Bool) {511 let key = (header ? "h" : "f") + type512 let watermark = header ? setup.watermark : nil513 let needed = !paragraphs.isEmpty || watermark != nil514 // A section without a reference inherits the previous section's header in Word, so an empty one must be explicit.515 guard needed || headerSeen[key] == true else { return }516 headerSeen[key] = needed || headerSeen[key] == true517 let index = headerParts.count + 1518 let part = DocxPart(name: header ? "word/header\(index).xml" : "word/footer\(index).xml", kind: header ? .header : .footer)519 let xml = headerFooterXML(paragraphs, part: part, watermark: watermark)520 headerParts.append((part, xml))521 let rid = document.rels.add(type: header ? RelType.header : RelType.footer, target: String(part.name.dropFirst(5)))522 s += xmlTag(header ? "w:headerReference" : "w:footerReference", [("w:type", type), ("r:id", rid)])523 }524 reference(setup.header.default, "default", header: true)525 reference(setup.header.first, "first", header: true)526 reference(setup.header.even, "even", header: true)527 reference(setup.footer.default, "default", header: false)528 reference(setup.footer.first, "first", header: false)529 reference(setup.footer.even, "even", header: false)530 if let kind {531 let v: String532 switch kind {533 case .nextPage: v = "nextPage"534 case .continuous: v = "continuous"535 case .oddPage: v = "oddPage"536 case .evenPage: v = "evenPage"537 }538 s += xmlTag("w:type", [("w:val", v)])539 }540 s += xmlTag("w:pgSz", [("w:w", DocxUnit.toTwips(setup.pageWidth)), ("w:h", DocxUnit.toTwips(setup.pageHeight)), ("w:orient", setup.landscape ? "landscape" : nil)])541 s += xmlTag("w:pgMar", [("w:top", DocxUnit.toTwips(setup.margins.top)), ("w:right", DocxUnit.toTwips(setup.margins.right)), ("w:bottom", DocxUnit.toTwips(setup.margins.bottom)),542 ("w:left", DocxUnit.toTwips(setup.margins.left)), ("w:header", DocxUnit.toTwips(setup.headerDistance)), ("w:footer", DocxUnit.toTwips(setup.footerDistance)), ("w:gutter", "0")])543 if let b = setup.border {544 let space = String(DocxUnit.safeInt(max(0, min(31, b.inset))))545 if b.inset > 31 { warn(.approximated, "Page borders", "Word places page borders at most 31 points from the page edge.") }546 var inner = ""547 for side in ["w:top", "w:left", "w:bottom", "w:right"] { inner += borderXML(side, b.line, space: space) }548 s += xmlTag("w:pgBorders", [("w:offsetFrom", "page")], inner)549 }550 var fmt: String?551 switch setup.pageNumberFormat {552 case .decimal: fmt = nil553 case .lowerRoman: fmt = "lowerRoman"554 case .upperRoman: fmt = "upperRoman"555 case .lowerAlpha: fmt = "lowerLetter"556 case .upperAlpha: fmt = "upperLetter"557 case .bullet, .none:558 fmt = nil559 warn(.approximated, "Page numbers", "This page number format has no Word equivalent; decimal numbers are used.")560 }561 if fmt != nil || setup.pageNumberStart != nil {562 s += xmlTag("w:pgNumType", [("w:fmt", fmt), ("w:start", setup.pageNumberStart.map(String.init))])563 }564 s += xmlTag("w:cols", [("w:num", setup.columns > 1 ? String(setup.columns) : nil), ("w:sep", setup.columns > 1 && setup.columnRule ? "1" : nil), ("w:space", DocxUnit.toTwips(setup.columnGap))])565 if setup.differentFirstPage { s += "<w:titlePg/>" }566 return "<w:sectPr>" + s + "</w:sectPr>"567 }568}569570/// Entry-name validation shared with the archive writer (same rules as `ZipReader`).571enum ZipWriterProbe {572 static func validate(_ name: String) throws {573 var probe = ZipWriter()574 try probe.add(name, Data())575 }576}577