Repository Public
1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocDOCX/DocxImportStyles.swift3// Description: WordprocessingML import of formatting: run and paragraph properties, styles.xml (document defaults, paragraph,4// character and table styles), numbering.xml and section properties.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import DocModel10import DocContainer1112/// What a Word table style contributes to a table.13struct ImportedTableStyle {14 var style = TableStyle(name: "Custom", outerBorder: nil, innerHorizontal: nil, innerVertical: nil, cellPadding: Insets(top: 0, left: 5.4, bottom: 0, right: 5.4))15 var top: BorderLine?, bottom: BorderLine?, left: BorderLine?, right: BorderLine?16 var hasBorders = false17 var firstRowBottom: BorderLine?18 var basedOn: String?19 var unsupportedConditions = false20}2122extension DocxImportContext {2324 // MARK: Borders2526 static func border(_ n: XMLNode?) -> BorderLine? {27 guard let n else { return nil }28 let val = n.attr("w:val") ?? "single"29 if val == "nil" || val == "none" { return nil }30 let style: BorderLine.Style31 switch val {32 case "dashed", "dashSmallGap", "dotDash", "dotDotDash", "dashDotStroked": style = .dashed33 case "dotted": style = .dotted34 case "double", "triple", "thinThickSmallGap", "thickThinSmallGap", "thinThickThinSmallGap", "thinThickMediumGap", "thickThinMediumGap",35 "thinThickLargeGap", "thickThinLargeGap": style = .double36 default: style = .solid37 }38 let width = (DocxUnit.number(n.attr("w:sz") ?? "4") ?? 4) / 839 return BorderLine(width: max(0.25, min(12, width)), color: DocxColor.hex(n.attr("w:color")) ?? .black, style: style)40 }4142 static func shading(_ n: XMLNode?) -> RGBA? {43 guard let n else { return nil }44 if let fill = DocxColor.hex(n.attr("w:fill")) { return fill }45 // A solid pattern paints with the foreground colour.46 if n.attr("w:val") == "solid", let c = DocxColor.hex(n.attr("w:color")) { return c }47 return nil48 }4950 // MARK: Character properties5152 func themeFont(_ ref: String) -> String? {53 themeFonts[ref.lowercased().hasPrefix("major") ? "major" : "minor"]54 }5556 func charProps(_ rPr: XMLNode?) -> CharProps {57 guard let rPr else { return .none }58 var c = CharProps()59 if let f = rPr.first("w:rFonts") {60 if let a = f.attr("w:ascii") ?? f.attr("w:hAnsi"), !a.isEmpty { c.fontFamily = a }61 else if let t = f.attr("w:asciiTheme") ?? f.attr("w:hAnsiTheme") {62 if let name = themeFont(t) { c.fontFamily = name } else { warn(.approximated, "Theme fonts", "A theme font reference could not be resolved; the default font is used.") }63 }64 }65 if let v = DocxUnit.halfPoints(rPr.val("w:sz")), v > 0, v < 2000 { c.fontSize = v }66 if let v = docxOnOff(rPr.first("w:b")) { c.bold = v }67 if let v = docxOnOff(rPr.first("w:i")) { c.italic = v }68 if let u = rPr.first("w:u") { c.underline = (u.attr("w:val") ?? "single") != "none" }69 if let v = docxOnOff(rPr.first("w:strike")) { c.strikethrough = v }70 if let v = docxOnOff(rPr.first("w:dstrike")), v || c.strikethrough == nil { c.strikethrough = v }71 if let col = rPr.first("w:color") {72 if let rgb = DocxColor.hex(col.attr("w:val")) { c.color = rgb }73 }74 if let h = rPr.val("w:highlight") {75 if let rgb = DocxColor.highlight(named: h) { c.highlight = rgb }76 } else if let fill = DocxImportContext.shading(rPr.first("w:shd")) {77 c.highlight = fill78 }79 if let v = rPr.val("w:vertAlign") {80 switch v {81 case "superscript": c.vertical = .superscript82 case "subscript": c.vertical = .subscript83 default: c.vertical = .baseline84 }85 }86 if let v = DocxUnit.halfPoints(rPr.val("w:position")) { c.baselineShift = v }87 if let v = DocxUnit.twips(rPr.val("w:spacing")) { c.tracking = v }88 if let k = rPr.val("w:kern"), let v = DocxUnit.number(k) { c.kerning = v > 0 }89 if let v = docxOnOff(rPr.first("w:smallCaps")) { c.smallCaps = v }90 if let v = docxOnOff(rPr.first("w:caps")) { c.allCaps = v }91 if let l = rPr.first("w:lang"), let v = l.attr("w:val"), !v.isEmpty { c.language = v }92 if let lig = rPr.first("w14:ligatures")?.attr("w14:val") { c.ligatures = lig != "none" }93 if docxOnOff(rPr.first("w:vanish")) == true { warn(.approximated, "Hidden text", "Text marked as hidden is imported as ordinary visible text.") }94 for name in ["w:outline", "w:shadow", "w:emboss", "w:imprint"] where docxOnOff(rPr.first(name)) == true {95 warn(.dropped, "Text effects", "Outline, shadow, emboss and engrave text effects are not supported.")96 }97 if let b = rPr.first("w:bdr"), DocxImportContext.border(b) != nil { warn(.dropped, "Text borders", "Borders around runs of text are not supported.") }98 for c in rPr.children where ["w:w", "w:effect", "w:em", "w:fitText", "w:eastAsianLayout"].contains(c.name) {99 warn(.dropped, "Other character formatting", "Character scaling, emphasis marks, animated text and East Asian layout settings are not supported.")100 }101 if docxOnOff(rPr.first("w:rtl")) == true { warn(.approximated, "Right-to-left runs", "Run-level right-to-left marks are not kept; paragraph direction is.") }102 return c103 }104105 // MARK: Paragraph properties106107 func paraProps(_ pPr: XMLNode?) -> ParaProps {108 guard let pPr else { return .none }109 var p = ParaProps()110 if let jc = pPr.val("w:jc") {111 switch jc {112 case "left", "start": p.alignment = .left113 case "center": p.alignment = .center114 case "right", "end": p.alignment = .right115 case "both", "distribute", "lowKashida", "mediumKashida", "highKashida", "thaiDistribute": p.alignment = .justified116 default: break117 }118 }119 if let ind = pPr.first("w:ind") {120 if let v = DocxUnit.twips(ind.attr("w:left") ?? ind.attr("w:start")) { p.indentLeft = v }121 if let v = DocxUnit.twips(ind.attr("w:right") ?? ind.attr("w:end")) { p.indentRight = v }122 if let v = DocxUnit.twips(ind.attr("w:hanging")) { p.firstLineIndent = v == 0 ? 0 : -v }123 else if let v = DocxUnit.twips(ind.attr("w:firstLine")) { p.firstLineIndent = v }124 }125 if let sp = pPr.first("w:spacing") {126 if let v = DocxUnit.twips(sp.attr("w:before")) { p.spaceBefore = v }127 if let v = DocxUnit.twips(sp.attr("w:after")) { p.spaceAfter = v }128 if let line = sp.attr("w:line"), let v = DocxUnit.number(line), v > 0 {129 switch sp.attr("w:lineRule") ?? "auto" {130 case "exact": p.lineSpacing = .exact(v / 20)131 case "atLeast": p.lineSpacing = .atLeast(v / 20)132 default: p.lineSpacing = .multiple(v / 240)133 }134 }135 }136 if let v = docxOnOff(pPr.first("w:keepNext")) { p.keepWithNext = v }137 if let v = docxOnOff(pPr.first("w:keepLines")) { p.keepLinesTogether = v }138 if let v = docxOnOff(pPr.first("w:pageBreakBefore")) { p.pageBreakBefore = v }139 if let v = docxOnOff(pPr.first("w:widowControl")) { p.widowControl = v }140 if let v = docxOnOff(pPr.first("w:suppressAutoHyphens")) { p.hyphenate = !v }141 if let v = docxOnOff(pPr.first("w:bidi")) { p.rightToLeft = v }142 if let tabs = pPr.first("w:tabs") {143 var stops: [TabStop] = []144 for t in tabs.all("w:tab") {145 guard let pos = DocxUnit.twips(t.attr("w:pos")) else { continue }146 let kind: TabStop.Kind147 switch t.attr("w:val") ?? "left" {148 case "clear": continue149 case "center": kind = .center150 case "right", "end": kind = .right151 case "decimal": kind = .decimal152 case "bar": warn(.dropped, "Bar tabs", "Bar tab stops are not supported."); continue153 default: kind = .left154 }155 let leader: TabStop.Leader156 switch t.attr("w:leader") ?? "none" {157 case "dot", "middleDot": leader = .dots158 case "hyphen": leader = .dashes159 case "underscore", "heavy": leader = .line160 default: leader = .none161 }162 stops.append(TabStop(position: pos, kind: kind, leader: leader))163 }164 if !stops.isEmpty { p.tabs = stops }165 }166 if let lvl = DocxUnit.int(pPr.val("w:outlineLvl")) { p.outlineLevel = (0...8).contains(lvl) ? lvl + 1 : 0 }167 if let fill = DocxImportContext.shading(pPr.first("w:shd")) { p.shading = fill }168 if let b = pPr.first("w:pBdr") {169 p.borderTop = DocxImportContext.border(b.first("w:top"))170 p.borderBottom = DocxImportContext.border(b.first("w:bottom"))171 p.borderLeft = DocxImportContext.border(b.first("w:left") ?? b.first("w:start"))172 if DocxImportContext.border(b.first("w:right") ?? b.first("w:end")) != nil || DocxImportContext.border(b.first("w:between")) != nil {173 warn(.dropped, "Paragraph borders", "Right and between-paragraph borders are not supported; top, bottom and left borders are kept.")174 }175 }176 if let f = pPr.first("w:framePr") {177 if f.attr("w:dropCap") != nil { warn(.approximated, "Drop caps", "The drop cap is imported as an ordinary paragraph.") }178 else { warn(.approximated, "Text frames", "A framed (positioned) paragraph is imported in the normal text flow.") }179 }180 for c in pPr.children where ["w:contextualSpacing", "w:mirrorIndents", "w:textAlignment", "w:textDirection", "w:suppressLineNumbers", "w:textboxTightWrap"].contains(c.name) {181 if c.name == "w:textAlignment", c.attr("w:val") == "auto" || c.attr("w:val") == "baseline" { continue }182 if docxOnOff(c) == false { continue }183 warn(.dropped, "Other paragraph formatting", "Contextual spacing, mirrored indents, vertical text alignment and text direction of paragraphs are not supported.")184 }185 if pPr.first("w:pPrChange") != nil { warn(.dropped, "Tracked paragraph formatting", "Tracked changes of paragraph formatting are not kept; the current formatting is.") }186 return p187 }188189 // MARK: styles.xml190191 static let builtInByName: [String: String] = {192 var m: [String: String] = ["normal": StyleID.normal, "title": StyleID.title, "subtitle": StyleID.subtitle, "quote": StyleID.quote,193 "caption": StyleID.caption, "footnote text": StyleID.footnoteText, "header": StyleID.header, "footer": StyleID.footer,194 "bibliography": StyleID.bibliography, "toc heading": StyleID.tocHeading, "list paragraph": StyleID.listParagraph,195 "hyperlink": StyleID.hyperlink, "strong": StyleID.strong, "emphasis": StyleID.emphasis]196 for i in 1...9 { m["heading \(i)"] = StyleID.heading(i); m["toc \(i)"] = StyleID.toc(i) }197 return m198 }()199200 func importStyles(_ root: XMLNode) {201 if let dd = root.first("w:docDefaults") {202 doc.styles.defaultChar = charProps(dd.path("w:rPrDefault", "w:rPr"))203 doc.styles.defaultPara = paraProps(dd.path("w:pPrDefault", "w:pPr"))204 }205 let nodes = root.all("w:style").filter { $0.attr("w:styleId") != nil }206 // Pass 1: decide the model id of every paragraph and character style.207 var taken = Set<String>()208 var pending: [(node: XMLNode, id: String, kind: Style.Kind)] = []209 for n in nodes {210 let type = n.attr("w:type") ?? "paragraph"211 guard type == "paragraph" || type == "character" else { continue }212 let id = n.attr("w:styleId")!213 let name = (n.val("w:name") ?? id).lowercased()214 if let builtIn = DocxImportContext.builtInByName[name], !taken.contains(builtIn) {215 styleIDMap[id] = builtIn216 taken.insert(builtIn)217 }218 pending.append((n, id, type == "paragraph" ? .paragraph : .character))219 }220 for (_, id, _) in pending where styleIDMap[id] == nil {221 var candidate = id, k = 2222 while taken.contains(candidate) { candidate = "\(id)_\(k)"; k += 1 }223 styleIDMap[id] = candidate224 taken.insert(candidate)225 }226 // Pass 2: build the styles.227 var headingNumbered: [String] = []228 for (n, id, kind) in pending {229 let modelID = styleIDMap[id]!230 let name = n.val("w:aliases")?.split(separator: ",").first.map(String.init) ?? n.val("w:name") ?? id231 var style = Style(id: modelID, name: name, kind: kind)232 style.basedOn = n.val("w:basedOn").flatMap { styleIDMap[$0] }233 style.next = kind == .paragraph ? n.val("w:next").flatMap { styleIDMap[$0] } : nil234 if style.next == modelID { style.next = nil }235 style.char = charProps(n.first("w:rPr"))236 if kind == .paragraph {237 let pPr = n.first("w:pPr")238 style.para = paraProps(pPr)239 if let numPr = pPr?.first("w:numPr"), let numId = numPr.val("w:numId"), numId != "0" {240 styleNumbering[modelID] = (numId, DocxUnit.int(numPr.val("w:ilvl")) ?? 0)241 headingNumbered.append(modelID)242 }243 if docxBool(n.attr("w:default")) { defaultParaStyle = modelID }244 }245 styleKinds[modelID] = kind246 doc.styles.styles.append(style)247 }248 // A heading style linked to a numbering definition is a numbered heading.249 for id in headingNumbered {250 let level = doc.styles.styleProps(id).para.outlineLevel ?? 0251 guard (1...9).contains(level), let i = doc.styles.styles.firstIndex(where: { $0.id == id }) else { continue }252 doc.styles.styles[i].numbered = true253 headingNumIDs.insert(styleNumbering[id]!.numId)254 styleNumbering[id] = nil255 }256 // Table styles.257 for n in nodes where n.attr("w:type") == "table" {258 let id = n.attr("w:styleId")!259 var t = ImportedTableStyle()260 t.style.name = n.val("w:name") ?? id261 t.basedOn = n.val("w:basedOn")262 if let tblPr = n.first("w:tblPr") { applyTableProperties(tblPr, to: &t) }263 for cond in n.all("w:tblStylePr") {264 let type = cond.attr("w:type") ?? ""265 let fill = DocxImportContext.shading(cond.path("w:tcPr", "w:shd"))266 switch type {267 case "firstRow":268 if let fill { t.style.headerShading = fill }269 if let c = DocxColor.hex(cond.path("w:rPr", "w:color")?.attr("w:val")) { t.style.headerTextColor = c }270 t.firstRowBottom = DocxImportContext.border(cond.path("w:tcPr", "w:tcBorders", "w:bottom"))271 case "band1Horz", "band2Horz":272 if let fill, t.style.bandedRowShading == nil { t.style.bandedRowShading = fill }273 default:274 if !cond.children.isEmpty { t.unsupportedConditions = true }275 }276 }277 tableStyles[id] = t278 if docxBool(n.attr("w:default")) { defaultTableStyle = id }279 }280 if nodes.contains(where: { $0.attr("w:type") == "numbering" }) {281 warn(.info, "List styles", "Named list styles are not kept as styles; the lists that use them are imported.")282 }283 }284285 /// Reads table-level borders and cell margins (from a table style or from a table's own properties).286 func applyTableProperties(_ tblPr: XMLNode, to t: inout ImportedTableStyle) {287 if let b = tblPr.first("w:tblBorders") {288 t.hasBorders = true289 t.top = DocxImportContext.border(b.first("w:top"))290 t.bottom = DocxImportContext.border(b.first("w:bottom"))291 t.left = DocxImportContext.border(b.first("w:left") ?? b.first("w:start"))292 t.right = DocxImportContext.border(b.first("w:right") ?? b.first("w:end"))293 t.style.innerHorizontal = DocxImportContext.border(b.first("w:insideH"))294 t.style.innerVertical = DocxImportContext.border(b.first("w:insideV"))295 // The model has one outer border; a frame on all four sides maps to it, partial frames become cell borders.296 if let top = t.top, t.bottom != nil, t.left != nil, t.right != nil { t.style.outerBorder = top } else { t.style.outerBorder = nil }297 }298 if let mar = tblPr.first("w:tblCellMar") {299 var pad = t.style.cellPadding300 if let v = DocxUnit.twips(mar.first("w:top")?.attr("w:w")) { pad.top = v }301 if let v = DocxUnit.twips(mar.first("w:bottom")?.attr("w:w")) { pad.bottom = v }302 if let v = DocxUnit.twips((mar.first("w:left") ?? mar.first("w:start"))?.attr("w:w")) { pad.left = v }303 if let v = DocxUnit.twips((mar.first("w:right") ?? mar.first("w:end"))?.attr("w:w")) { pad.right = v }304 t.style.cellPadding = pad305 }306 }307308 func resolvedTableStyle(_ id: String?) -> ImportedTableStyle {309 var chain: [ImportedTableStyle] = []310 var cur = id, seen = Set<String>()311 while let c = cur, !seen.contains(c), let s = tableStyles[c] { chain.append(s); seen.insert(c); cur = s.basedOn }312 guard var out = chain.last else { return ImportedTableStyle() }313 for s in chain.dropLast().reversed() {314 if s.hasBorders {315 out.hasBorders = true; out.top = s.top; out.bottom = s.bottom; out.left = s.left; out.right = s.right316 out.style.outerBorder = s.style.outerBorder; out.style.innerHorizontal = s.style.innerHorizontal; out.style.innerVertical = s.style.innerVertical317 }318 if let v = s.style.headerShading { out.style.headerShading = v }319 if let v = s.style.headerTextColor { out.style.headerTextColor = v }320 if let v = s.style.bandedRowShading { out.style.bandedRowShading = v }321 if let v = s.firstRowBottom { out.firstRowBottom = v }322 if s.unsupportedConditions { out.unsupportedConditions = true }323 if s.style.cellPadding != ImportedTableStyle().style.cellPadding { out.style.cellPadding = s.style.cellPadding }324 }325 out.style.name = chain.first!.style.name326 return out327 }328329 func ensureNormalStyle() {330 if doc.styles.style(defaultParaStyle) == nil {331 doc.styles.styles.insert(Style(id: defaultParaStyle, name: "Normal"), at: 0)332 styleKinds[defaultParaStyle] = .paragraph333 }334 }335336 /// Model id of a paragraph style referenced from content. Unknown ids fall back to the default style with a warning.337 func paragraphStyle(_ wordID: String?) -> String {338 guard let wordID else { return defaultParaStyle }339 if let id = styleIDMap[wordID], styleKinds[id] == .paragraph { return id }340 warn(.approximated, "Missing styles", "The paragraph style \"\(wordID)\" is not defined in the document; the default style is used.")341 return defaultParaStyle342 }343344 func characterStyle(_ wordID: String?) -> String? {345 guard let wordID else { return nil }346 if let id = styleIDMap[wordID], styleKinds[id] == .character { return id }347 return nil348 }349350 // MARK: numbering.xml351352 static let bulletGlyphs: [UInt32: String] = [0xF0B7: "•", 0xF0A7: "▪", 0xF0D8: "➢", 0xF0FC: "✓", 0xF076: "❖", 0xF0A8: "◆", 0xF0E0: "→", 0xF02D: "–", 0x00B7: "•", 0xF06F: "◦", 0xF0B0: "◦"]353354 func importNumbering(_ root: XMLNode) {355 var abstracts: [String: [Int: XMLNode]] = [:]356 var styleLinks: [String: String] = [:]357 var linkedStyles: [String: String] = [:]358 for a in root.all("w:abstractNum") {359 guard let id = a.attr("w:abstractNumId") else { continue }360 var levels: [Int: XMLNode] = [:]361 for l in a.all("w:lvl") { if let i = DocxUnit.int(l.attr("w:ilvl")), (0..<9).contains(i) { levels[i] = l } }362 abstracts[id] = levels363 if let link = a.val("w:numStyleLink") { styleLinks[id] = link }364 if let link = a.val("w:styleLink") { linkedStyles[link] = id }365 }366 for num in root.all("w:num") {367 guard let numId = num.attr("w:numId"), var absId = num.val("w:abstractNumId") else { continue }368 if let link = styleLinks[absId], let target = linkedStyles[link] { absId = target }369 var levels = abstracts[absId] ?? [:]370 var startOverrides: [Int: Int] = [:]371 for o in num.all("w:lvlOverride") {372 guard let i = DocxUnit.int(o.attr("w:ilvl")), (0..<9).contains(i) else { continue }373 if let l = o.first("w:lvl") { levels[i] = l }374 if let s = DocxUnit.int(o.val("w:startOverride")) { startOverrides[i] = s }375 }376 if headingNumIDs.contains(numId) { continue }377 let count = max(1, (levels.keys.max() ?? 0) + 1)378 var out: [ListLevel] = []379 for i in 0..<count {380 var level = listLevel(levels[i], index: i)381 if let s = startOverrides[i] { level.start = s }382 out.append(level)383 }384 let def = ListDefinition(id: DocID.make(), levels: out)385 doc.lists.append(def)386 numToList[numId] = def.id387 }388 }389390 func listLevel(_ n: XMLNode?, index: Int) -> ListLevel {391 guard let n else { return ListLevel(format: .decimal, pattern: "%\(index + 1).", indent: 36 + Double(index) * 18) }392 let fmtName = n.val("w:numFmt") ?? "decimal"393 let format: NumberFormat394 switch fmtName {395 case "decimal", "decimalZero": format = .decimal396 case "lowerLetter": format = .lowerAlpha397 case "upperLetter": format = .upperAlpha398 case "lowerRoman": format = .lowerRoman399 case "upperRoman": format = .upperRoman400 case "bullet": format = .bullet401 case "none": format = NumberFormat.none402 default:403 format = .decimal404 warn(.approximated, "List number formats", "The number format \"\(fmtName)\" is imported as decimal numbers.")405 }406 var pattern = n.val("w:lvlText") ?? (format == .bullet ? "•" : "%\(index + 1).")407 if format == .bullet {408 let font = n.path("w:rPr", "w:rFonts")?.attr("w:ascii") ?? ""409 if n.first("w:lvlPicBulletId") != nil { pattern = "•" }410 else if pattern.unicodeScalars.count == 1, let u = pattern.unicodeScalars.first {411 if let g = DocxImportContext.bulletGlyphs[u.value] { pattern = g }412 else if u == "o", font.lowercased().contains("courier") { pattern = "◦" }413 else if (0xE000...0xF8FF).contains(u.value) { pattern = "•" }414 } else if pattern.isEmpty { pattern = "•" }415 }416 let ind = n.path("w:pPr", "w:ind")417 let left = DocxUnit.twips(ind?.attr("w:left") ?? ind?.attr("w:start")) ?? (36 + Double(index) * 18)418 let hanging = DocxUnit.twips(ind?.attr("w:hanging")) ?? 18419 return ListLevel(format: format, pattern: pattern, indent: left, hanging: hanging, start: DocxUnit.int(n.val("w:start")) ?? 1)420 }421422 // MARK: Section properties423424 /// Converts one `w:sectPr`. `previous` supplies the headers and footers a section inherits when it declares none.425 func pageSetup(_ sectPr: XMLNode?, previous: PageSetup?, rels: [String: Relationship]) -> (setup: PageSetup, kind: SectionBreak.Kind) {426 var s = PageSetup(paper: .letter)427 s.differentOddEven = evenAndOddHeaders428 if let prev = previous {429 // Inherited headers are copies: paragraph ids stay unique in the document.430 func fresh(_ ps: [Paragraph]) -> [Paragraph] { ps.map { var p = $0; p.id = DocID.make(); return p } }431 s.header = HeaderFooter(default: fresh(prev.header.default), first: fresh(prev.header.first), even: fresh(prev.header.even))432 s.footer = HeaderFooter(default: fresh(prev.footer.default), first: fresh(prev.footer.first), even: fresh(prev.footer.even))433 }434 guard let sectPr else { return (s, .nextPage) }435 if let sz = sectPr.first("w:pgSz"), let w = DocxUnit.twips(sz.attr("w:w")), let h = DocxUnit.twips(sz.attr("w:h")), w > 20, h > 20 {436 let (paper, landscape) = docxPaper(width: w, height: h)437 s.paper = paper438 s.landscape = landscape439 }440 if let m = sectPr.first("w:pgMar") {441 s.margins = Insets(top: abs(DocxUnit.twips(m.attr("w:top")) ?? 72), left: DocxUnit.twips(m.attr("w:left")) ?? 72,442 bottom: abs(DocxUnit.twips(m.attr("w:bottom")) ?? 72), right: DocxUnit.twips(m.attr("w:right")) ?? 72)443 if let v = DocxUnit.twips(m.attr("w:header")) { s.headerDistance = v }444 if let v = DocxUnit.twips(m.attr("w:footer")) { s.footerDistance = v }445 if let g = DocxUnit.twips(m.attr("w:gutter")), g > 0 { warn(.dropped, "Gutter margins", "The binding gutter is not supported; the other margins are kept.") }446 }447 if let cols = sectPr.first("w:cols") {448 let n = DocxUnit.int(cols.attr("w:num")) ?? max(1, cols.all("w:col").count)449 s.columns = max(1, min(12, n))450 if let sp = DocxUnit.twips(cols.attr("w:space")) { s.columnGap = sp } else if let sp = DocxUnit.twips(cols.first("w:col")?.attr("w:space")) { s.columnGap = sp }451 s.columnRule = docxBool(cols.attr("w:sep"))452 if cols.attr("w:equalWidth").map(docxBool) == false, s.columns > 1 {453 warn(.approximated, "Columns", "Columns of unequal width are imported as equal columns.")454 }455 }456 if let pn = sectPr.first("w:pgNumType") {457 s.pageNumberStart = DocxUnit.int(pn.attr("w:start"))458 switch pn.attr("w:fmt") ?? "decimal" {459 case "lowerRoman": s.pageNumberFormat = .lowerRoman460 case "upperRoman": s.pageNumberFormat = .upperRoman461 case "lowerLetter": s.pageNumberFormat = .lowerAlpha462 case "upperLetter": s.pageNumberFormat = .upperAlpha463 default: s.pageNumberFormat = .decimal464 }465 }466 s.differentFirstPage = docxOnOff(sectPr.first("w:titlePg")) ?? false467 if let b = sectPr.first("w:pgBorders"), let side = b.first("w:top") ?? b.first("w:left") ?? b.first("w:bottom") ?? b.first("w:right"),468 let line = DocxImportContext.border(side) {469 s.border = PageBorder(line: line, inset: DocxUnit.number(side.attr("w:space") ?? "24") ?? 24)470 }471 if sectPr.first("w:lnNumType") != nil { warn(.dropped, "Line numbering", "Line numbers in the margin are not supported.") }472 if sectPr.first("w:sectPrChange") != nil { warn(.dropped, "Tracked section changes", "Tracked changes of page setup are not kept; the current setup is.") }473 if let v = sectPr.val("w:vAlign"), v != "top" { warn(.dropped, "Vertical page alignment", "Vertical alignment of the page content is not supported.") }474475 if sectPr.first("w:headerReference") == nil { s.watermark = previous?.watermark }476 for (name, isHeader) in [("w:headerReference", true), ("w:footerReference", false)] {477 for ref in sectPr.all(name) {478 guard let rid = ref.attr("r:id"), let rel = rels[rid], !rel.external, let part = OPC.resolve(target: rel.target, from: mainPart) else { continue }479 let paragraphs = (try? importHeaderFooter(part: part)) ?? []480 if isHeader, let w = watermarkByPart[part] { s.watermark = w }481 let type = ref.attr("w:type") ?? "default"482 func assign(_ hf: inout HeaderFooter) {483 switch type {484 case "first": hf.first = paragraphs485 case "even": hf.even = paragraphs486 default: hf.default = paragraphs487 }488 }489 if isHeader { assign(&s.header) } else { assign(&s.footer) }490 }491 }492 let kind: SectionBreak.Kind493 switch sectPr.val("w:type") ?? "nextPage" {494 case "continuous": kind = .continuous495 case "oddPage": kind = .oddPage496 case "evenPage": kind = .evenPage497 case "nextColumn":498 kind = .nextPage499 warn(.approximated, "Section breaks", "A \"next column\" section break is imported as a \"next page\" break.")500 default: kind = .nextPage501 }502 return (s, kind)503 }504}505