writer.go 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420
  1. package docx
  2. /*
  3. writer.go - Build a Word (.docx) file from a Document.
  4. The input is the Docs rich HTML model (see reader.go for the
  5. vocabulary) and every formatting decision in it is written out as
  6. explicit WordprocessingML, so that the file lays out in Word - and back
  7. in the editor - the way it looked in the editor:
  8. blocks spacing before/after (margin/padding), indents, alignment,
  9. line spacing (data-ls / data-lsexact / data-lsmin), shading,
  10. borders, keep-with-next / keep-lines / widow control,
  11. page-break-before and tab stops (data-tabs); headings and
  12. the title/subtitle keep their named styles
  13. runs font family (the first of the stack), size, weight, italic,
  14. underline, strike-through, colour, highlight/shading,
  15. small caps, caps, superscript/subscript, hyperlinks
  16. (external and internal #bookmark), tabs, line breaks,
  17. PAGE / NUMPAGES fields and footnote references
  18. lists one numbering definition per list, with the list's own
  19. number format, marker text, start and indents per level;
  20. a list interrupted by a paragraph keeps counting (data-num)
  21. tables the grid in twips, the table's indent, fixed layout, per
  22. cell borders, margins, shading, vertical alignment, column
  23. and row spans, row heights, cant-split and header rows
  24. pictures inline or anchored (top-and-bottom / square wrap), with the
  25. crop (srcRect) and the picture outline
  26. parts rich header/footer parts with their own pictures, footnotes,
  27. page size, margins and the header/footer distances
  28. What the editor draws with its own CSS defaults (a heading without
  29. inline style, a table cell without borders) is written with those
  30. defaults, mirrored in editorBlockDefaults - change docs.css and change
  31. them too.
  32. */
  33. import (
  34. "archive/zip"
  35. "bytes"
  36. "crypto/sha256"
  37. "errors"
  38. "fmt"
  39. "image"
  40. _ "image/gif"
  41. _ "image/jpeg"
  42. _ "image/png"
  43. "math"
  44. "regexp"
  45. "strconv"
  46. "strings"
  47. "golang.org/x/net/html"
  48. "imuslab.com/arozos/mod/office/internal/fonts"
  49. "imuslab.com/arozos/mod/office/internal/htmlutil"
  50. "imuslab.com/arozos/mod/office/internal/media"
  51. "imuslab.com/arozos/mod/office/internal/xmltree"
  52. "imuslab.com/arozos/mod/office/model"
  53. )
  54. const docxNs = `xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"`
  55. const (
  56. relImage = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"
  57. relHyperlink = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"
  58. )
  59. /* ---------------- CSS reading ---------------- */
  60. // cssDecls parses an inline style attribute (later declarations win)
  61. func cssDecls(style string) map[string]string {
  62. out := map[string]string{}
  63. var cur strings.Builder
  64. quote := byte(0)
  65. flush := func() {
  66. decl := cur.String()
  67. cur.Reset()
  68. kv := strings.SplitN(decl, ":", 2)
  69. if len(kv) != 2 {
  70. return
  71. }
  72. k := strings.ToLower(strings.TrimSpace(kv[0]))
  73. v := strings.TrimSpace(kv[1])
  74. v = strings.TrimSuffix(strings.TrimSpace(strings.TrimSuffix(v, "!important")), ";")
  75. if k != "" {
  76. out[k] = v
  77. }
  78. }
  79. for i := 0; i < len(style); i++ {
  80. c := style[i]
  81. switch {
  82. case quote != 0:
  83. if c == quote {
  84. quote = 0
  85. }
  86. cur.WriteByte(c)
  87. case c == '"' || c == '\'':
  88. quote = c
  89. cur.WriteByte(c)
  90. case c == ';':
  91. flush()
  92. default:
  93. cur.WriteByte(c)
  94. }
  95. }
  96. flush()
  97. return out
  98. }
  99. // cssPt converts a CSS length to points; em is relative to emPt; ok=false
  100. // when the value is not a length
  101. func cssPt(v string, emPt float64) (float64, bool) {
  102. v = strings.TrimSpace(strings.ToLower(v))
  103. if v == "" || v == "auto" || v == "normal" {
  104. return 0, false
  105. }
  106. if v == "0" {
  107. return 0, true
  108. }
  109. units := []struct {
  110. suf string
  111. k float64
  112. }{{"pt", 1}, {"px", 0.75}, {"mm", 72 / 25.4}, {"cm", 72 / 2.54}, {"in", 72}, {"em", 0}, {"rem", 11}}
  113. for _, u := range units {
  114. if strings.HasSuffix(v, u.suf) {
  115. n, err := strconv.ParseFloat(strings.TrimSpace(strings.TrimSuffix(v, u.suf)), 64)
  116. if err != nil {
  117. return 0, false
  118. }
  119. if u.suf == "em" {
  120. return n * emPt, true
  121. }
  122. return n * u.k, true
  123. }
  124. }
  125. if n, err := strconv.ParseFloat(v, 64); err == nil {
  126. return n * 0.75, true
  127. }
  128. return 0, false
  129. }
  130. // cssFontSizePt resolves font-size (absolute, %, em, keywords)
  131. func cssFontSizePt(v string, parentPt float64) (float64, bool) {
  132. v = strings.TrimSpace(strings.ToLower(v))
  133. if strings.HasSuffix(v, "%") {
  134. if n, err := strconv.ParseFloat(strings.TrimSuffix(v, "%"), 64); err == nil {
  135. return parentPt * n / 100, true
  136. }
  137. return 0, false
  138. }
  139. switch v {
  140. case "smaller":
  141. return parentPt * 0.83, true
  142. case "larger":
  143. return parentPt * 1.2, true
  144. case "xx-small":
  145. return 7, true
  146. case "x-small":
  147. return 7.5, true
  148. case "small":
  149. return 10, true
  150. case "medium":
  151. return 12, true
  152. case "large":
  153. return 13.5, true
  154. case "x-large":
  155. return 18, true
  156. case "xx-large":
  157. return 24, true
  158. case "xxx-large":
  159. return 36, true
  160. }
  161. return cssPt(v, parentPt)
  162. }
  163. // cssBorder parses "1pt solid #000" into a Word border (sz in eighths)
  164. type wBorder struct {
  165. val string
  166. sz int
  167. color string
  168. space float64 // pt between a paragraph border and its text
  169. }
  170. func cssBorder(v string) (wBorder, bool) {
  171. v = strings.TrimSpace(strings.ToLower(v))
  172. if v == "" {
  173. return wBorder{}, false
  174. }
  175. if v == "none" || v == "0" || strings.HasPrefix(v, "none ") || strings.Contains(v, " none") || v == "hidden" {
  176. return wBorder{val: "nil"}, true
  177. }
  178. b := wBorder{val: "single", sz: 4, color: "000000"}
  179. for _, tok := range splitCSSValue(v) {
  180. switch tok {
  181. case "solid":
  182. b.val = "single"
  183. case "dotted":
  184. b.val = "dotted"
  185. case "dashed":
  186. b.val = "dashed"
  187. case "double":
  188. b.val = "double"
  189. case "thin":
  190. b.sz = 4
  191. case "medium":
  192. b.sz = 12
  193. case "thick":
  194. b.sz = 18
  195. default:
  196. if pt, ok := cssPt(tok, 11); ok {
  197. b.sz = int(math.Round(pt * 8))
  198. if b.sz < 2 {
  199. b.sz = 2
  200. }
  201. if pt == 0 {
  202. return wBorder{val: "nil"}, true
  203. }
  204. continue
  205. }
  206. if c := htmlutil.CSSColorHex(tok); c != "" {
  207. b.color = c
  208. }
  209. }
  210. }
  211. return b, true
  212. }
  213. /*
  214. cssBorderSides reads the borders a style gives each side, the way CSS
  215. cascades them: the border shorthand, each side's own shorthand, then the
  216. longhands - border-width / -style / -color with one to four values, which is
  217. how the browser writes a uniform border back once it has been edited, and
  218. the per-side ones. Only the sides the style mentions are returned; a side
  219. given a width or colour but never a style has none, as in CSS.
  220. */
  221. func cssBorderSides(css map[string]string) map[string]wBorder {
  222. sides := []string{"top", "right", "bottom", "left"}
  223. out := map[string]wBorder{}
  224. if v, ok := css["border"]; ok {
  225. if bd, ok := cssBorder(v); ok {
  226. for _, side := range sides {
  227. out[side] = bd
  228. }
  229. }
  230. }
  231. for _, side := range sides {
  232. if v, ok := css["border-"+side]; ok {
  233. if bd, ok := cssBorder(v); ok {
  234. out[side] = bd
  235. }
  236. }
  237. }
  238. set := func(side, prop, v string) {
  239. v = strings.TrimSpace(strings.ToLower(v))
  240. bd, ok := out[side]
  241. if !ok {
  242. bd = wBorder{sz: 4, color: "000000"} // no style yet
  243. }
  244. switch prop {
  245. case "style":
  246. switch v {
  247. case "none", "hidden":
  248. bd.val = "nil"
  249. case "dotted", "dashed", "double":
  250. bd.val = v
  251. default:
  252. bd.val = "single"
  253. }
  254. case "width":
  255. switch v {
  256. case "thin":
  257. bd.sz = 4
  258. case "medium":
  259. bd.sz = 12
  260. case "thick":
  261. bd.sz = 18
  262. default:
  263. if pt, ok := cssPt(v, 11); ok {
  264. if pt == 0 {
  265. bd.val = "nil"
  266. }
  267. bd.sz = int(math.Max(2, math.Round(pt*8)))
  268. }
  269. }
  270. case "color":
  271. if c := htmlutil.CSSColorHex(v); c != "" {
  272. bd.color = c
  273. }
  274. }
  275. out[side] = bd
  276. }
  277. for _, prop := range []string{"style", "width", "color"} {
  278. if v, ok := css["border-"+prop]; ok {
  279. vals := splitCSSValue(strings.TrimSpace(v))
  280. for i, side := range sides {
  281. // 1 to 4 values, top right bottom left, as in padding
  282. switch len(vals) {
  283. case 1:
  284. set(side, prop, vals[0])
  285. case 2:
  286. set(side, prop, vals[i%2])
  287. case 3:
  288. set(side, prop, vals[[]int{0, 1, 2, 1}[i]])
  289. case 4:
  290. set(side, prop, vals[i])
  291. }
  292. }
  293. }
  294. for _, side := range sides {
  295. if v, ok := css["border-"+side+"-"+prop]; ok {
  296. set(side, prop, v)
  297. }
  298. }
  299. }
  300. for side, bd := range out {
  301. if bd.val == "" {
  302. delete(out, side)
  303. }
  304. }
  305. return out
  306. }
  307. // borderSpace is a border's w:space: whole points, 0 to 31
  308. func borderSpace(pt float64) int {
  309. return int(math.Max(0, math.Min(31, math.Round(pt))))
  310. }
  311. // splitCSSValue splits a shorthand on spaces, keeping rgb(...) whole
  312. func splitCSSValue(v string) []string {
  313. var out []string
  314. depth := 0
  315. var cur strings.Builder
  316. for _, r := range v {
  317. switch {
  318. case r == '(':
  319. depth++
  320. cur.WriteRune(r)
  321. case r == ')':
  322. depth--
  323. cur.WriteRune(r)
  324. case r == ' ' && depth == 0:
  325. if cur.Len() > 0 {
  326. out = append(out, cur.String())
  327. cur.Reset()
  328. }
  329. default:
  330. cur.WriteRune(r)
  331. }
  332. }
  333. if cur.Len() > 0 {
  334. out = append(out, cur.String())
  335. }
  336. return out
  337. }
  338. // boxSides expands a 1-4 value shorthand (padding, margin) into t r b l
  339. func boxSides(v string, emPt float64) ([4]float64, bool) {
  340. var out [4]float64
  341. toks := splitCSSValue(strings.TrimSpace(v))
  342. var vals []float64
  343. for _, t := range toks {
  344. pt, ok := cssPt(t, emPt)
  345. if !ok {
  346. return out, false
  347. }
  348. vals = append(vals, pt)
  349. }
  350. switch len(vals) {
  351. case 1:
  352. out = [4]float64{vals[0], vals[0], vals[0], vals[0]}
  353. case 2:
  354. out = [4]float64{vals[0], vals[1], vals[0], vals[1]}
  355. case 3:
  356. out = [4]float64{vals[0], vals[1], vals[2], vals[1]}
  357. case 4:
  358. out = [4]float64{vals[0], vals[1], vals[2], vals[3]}
  359. default:
  360. return out, false
  361. }
  362. return out, true
  363. }
  364. func twip(pt float64) int { return int(math.Round(pt * 20)) }
  365. func hasClass(n *html.Node, cls string) bool {
  366. return strings.Contains(" "+htmlutil.Attr(n, "class")+" ", " "+cls+" ")
  367. }
  368. /* ---------------- inherited formatting ---------------- */
  369. type wRunStyle struct {
  370. font string
  371. sizePt float64
  372. bold, italic bool
  373. underline, strike bool
  374. smallCaps, caps bool
  375. color string // RRGGBB
  376. shade string // RRGGBB background
  377. vert string // superscript | subscript
  378. preWrap bool
  379. link string
  380. }
  381. // applyBlockCSS folds a container's inline style into the run style; its
  382. // background belongs to the paragraph or cell, not to every run inside
  383. func (rs wRunStyle) applyBlockCSS(css map[string]string) wRunStyle {
  384. if _, ok := css["background-color"]; !ok {
  385. return rs.applyCSS(css)
  386. }
  387. own := make(map[string]string, len(css))
  388. for k, v := range css {
  389. if k != "background-color" {
  390. own[k] = v
  391. }
  392. }
  393. return rs.applyCSS(own)
  394. }
  395. // applyCSS folds an element's inline style into the inherited run style
  396. func (rs wRunStyle) applyCSS(css map[string]string) wRunStyle {
  397. if v, ok := css["font-family"]; ok {
  398. if f := fonts.FirstFamily(v); f != "" {
  399. rs.font = f
  400. }
  401. }
  402. if v, ok := css["font-size"]; ok {
  403. if pt, ok := cssFontSizePt(v, rs.sizePt); ok && pt > 0 {
  404. rs.sizePt = pt
  405. }
  406. }
  407. if v, ok := css["font-weight"]; ok {
  408. switch v {
  409. case "bold", "bolder", "600", "700", "800", "900":
  410. rs.bold = true
  411. case "normal", "lighter", "100", "200", "300", "400", "500":
  412. rs.bold = false
  413. }
  414. }
  415. if v, ok := css["font-style"]; ok {
  416. rs.italic = v == "italic" || v == "oblique"
  417. }
  418. for _, k := range []string{"text-decoration", "text-decoration-line"} {
  419. if v, ok := css[k]; ok {
  420. if v == "none" {
  421. rs.underline, rs.strike = false, false
  422. } else {
  423. if strings.Contains(v, "underline") {
  424. rs.underline = true
  425. }
  426. if strings.Contains(v, "line-through") {
  427. rs.strike = true
  428. }
  429. }
  430. }
  431. }
  432. if v, ok := css["color"]; ok && v != "inherit" {
  433. if c := htmlutil.CSSColorHex(v); c != "" {
  434. rs.color = c
  435. }
  436. }
  437. if v, ok := css["background-color"]; ok {
  438. rs.shade = htmlutil.CSSColorHex(v)
  439. }
  440. if v, ok := css["font-variant"]; ok {
  441. rs.smallCaps = strings.Contains(v, "small-caps")
  442. }
  443. if v, ok := css["text-transform"]; ok {
  444. rs.caps = v == "uppercase"
  445. }
  446. if v, ok := css["white-space"]; ok {
  447. rs.preWrap = strings.HasPrefix(v, "pre") || v == "break-spaces"
  448. }
  449. return rs
  450. }
  451. func (rs wRunStyle) rPr() string {
  452. var sb strings.Builder
  453. sb.WriteString("<w:rPr>")
  454. if rs.font != "" {
  455. f := xmltree.Escape(rs.font)
  456. sb.WriteString(`<w:rFonts w:ascii="` + f + `" w:hAnsi="` + f + `" w:cs="` + f + `" w:eastAsia="` + f + `"/>`)
  457. }
  458. if rs.bold {
  459. sb.WriteString(`<w:b/><w:bCs/>`)
  460. } else {
  461. sb.WriteString(`<w:b w:val="0"/><w:bCs w:val="0"/>`)
  462. }
  463. if rs.italic {
  464. sb.WriteString(`<w:i/><w:iCs/>`)
  465. } else {
  466. sb.WriteString(`<w:i w:val="0"/><w:iCs w:val="0"/>`)
  467. }
  468. if rs.caps {
  469. sb.WriteString(`<w:caps/>`)
  470. }
  471. if rs.smallCaps {
  472. sb.WriteString(`<w:smallCaps/>`)
  473. }
  474. if rs.strike {
  475. sb.WriteString(`<w:strike/>`)
  476. }
  477. col := rs.color
  478. if col == "" {
  479. col = "000000"
  480. }
  481. sb.WriteString(`<w:color w:val="` + col + `"/>`)
  482. if rs.sizePt > 0 {
  483. hp := int(math.Round(rs.sizePt * 2))
  484. sb.WriteString(fmt.Sprintf(`<w:sz w:val="%d"/><w:szCs w:val="%d"/>`, hp, hp))
  485. }
  486. if rs.underline {
  487. sb.WriteString(`<w:u w:val="single"/>`)
  488. } else {
  489. sb.WriteString(`<w:u w:val="none"/>`)
  490. }
  491. if rs.shade != "" {
  492. sb.WriteString(`<w:shd w:val="clear" w:color="auto" w:fill="` + rs.shade + `"/>`)
  493. }
  494. if rs.vert != "" {
  495. sb.WriteString(`<w:vertAlign w:val="` + rs.vert + `"/>`)
  496. }
  497. sb.WriteString("</w:rPr>")
  498. return sb.String()
  499. }
  500. /*
  501. The editor's own look for elements that state nothing (docs.css). The
  502. writer starts every element from these, then applies its inline style.
  503. */
  504. type blockDefault struct {
  505. sizePt, beforePt, afterPt float64
  506. bold, italic bool
  507. color string
  508. style string
  509. }
  510. var editorBlockDefaults = map[string]blockDefault{
  511. "p": {sizePt: 11, color: "000000"},
  512. "h1": {sizePt: 20, beforePt: 14, afterPt: 6, bold: true, color: "1F2328", style: "Heading1"},
  513. "h2": {sizePt: 16, beforePt: 14, afterPt: 6, bold: true, color: "1F2328", style: "Heading2"},
  514. "h3": {sizePt: 13, beforePt: 14, afterPt: 6, bold: true, color: "1F2328", style: "Heading3"},
  515. "h4": {sizePt: 11, beforePt: 14, afterPt: 6, bold: true, italic: true, color: "1F2328", style: "Heading4"},
  516. "h5": {sizePt: 11, beforePt: 14, afterPt: 6, bold: true, color: "1F2328", style: "Heading5"},
  517. "h6": {sizePt: 11, beforePt: 14, afterPt: 6, bold: true, italic: true, color: "1F2328", style: "Heading6"},
  518. "doc-title": {sizePt: 26, afterPt: 12, color: "1F2328", style: "Title"},
  519. "doc-subtitle": {sizePt: 15, afterPt: 16, color: "666666", style: "Subtitle"},
  520. }
  521. // editorBlockCSS is docs.css for the blocks it boxes (longhands only, so an
  522. // inline shorthand can replace them): the export starts from what the
  523. // editor draws before the element's own style is applied
  524. var editorBlockCSS = map[string]map[string]string{
  525. "blockquote": {
  526. "margin-top": "8pt", "margin-bottom": "8pt",
  527. "border-left": "3px solid #c3c7cc",
  528. "padding-top": "2pt", "padding-bottom": "2pt", "padding-left": "12px",
  529. "color": "#5f6368",
  530. },
  531. "pre": {
  532. "margin-top": "8pt", "margin-bottom": "8pt",
  533. "background-color": "#f1f3f4",
  534. "border-top": "1px solid #e2e5e9", "border-right": "1px solid #e2e5e9",
  535. "border-bottom": "1px solid #e2e5e9", "border-left": "1px solid #e2e5e9",
  536. "padding-top": "10px", "padding-right": "12px", "padding-bottom": "10px", "padding-left": "12px",
  537. "font-family": "Consolas, 'Courier New', monospace", "font-size": "10pt",
  538. "white-space": "pre-wrap",
  539. },
  540. }
  541. // withDefaultCSS lays an element's inline declarations over defaults; a
  542. // shorthand ("margin", "border") replaces the defaults it covers
  543. func withDefaultCSS(defaults, inline map[string]string) map[string]string {
  544. out := make(map[string]string, len(defaults)+len(inline))
  545. for k, v := range defaults {
  546. out[k] = v
  547. }
  548. for k := range inline {
  549. for d := range defaults {
  550. if strings.HasPrefix(d, k+"-") {
  551. delete(out, d)
  552. }
  553. }
  554. }
  555. for k, v := range inline {
  556. out[k] = v
  557. }
  558. return out
  559. }
  560. /* ---------------- relationships and media ---------------- */
  561. type docxPart struct {
  562. rels []string
  563. next int
  564. }
  565. func (p *docxPart) add(typ, target string, external bool) string {
  566. p.next++
  567. id := fmt.Sprintf("rId%d", 100+p.next)
  568. mode := ""
  569. if external {
  570. mode = ` TargetMode="External"`
  571. }
  572. p.rels = append(p.rels, `<Relationship Id="`+id+`" Type="`+typ+`" Target="`+xmltree.Escape(target)+`"`+mode+`/>`)
  573. return id
  574. }
  575. func (p *docxPart) relsXML(fixed string) string {
  576. return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` + "\n" +
  577. `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
  578. fixed + strings.Join(p.rels, "") + `</Relationships>`
  579. }
  580. /* ---------------- numbering ---------------- */
  581. type numLevelDef struct {
  582. fmt, text string
  583. start int
  584. leftPt, hangPt float64
  585. set bool
  586. }
  587. type numInstance struct {
  588. id int
  589. levels [9]numLevelDef
  590. }
  591. type docxNumbering struct {
  592. list []*numInstance
  593. byKey map[string]*numInstance
  594. }
  595. func (nb *docxNumbering) instance(key string) *numInstance {
  596. if nb.byKey == nil {
  597. nb.byKey = map[string]*numInstance{}
  598. }
  599. if key != "" {
  600. if in, ok := nb.byKey[key]; ok {
  601. return in
  602. }
  603. }
  604. in := &numInstance{id: len(nb.list) + 1}
  605. nb.list = append(nb.list, in)
  606. if key != "" {
  607. nb.byKey[key] = in
  608. }
  609. return in
  610. }
  611. func (nb *docxNumbering) xml() string {
  612. var sb strings.Builder
  613. sb.WriteString(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` + "\n")
  614. sb.WriteString(`<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">`)
  615. for _, in := range nb.list {
  616. sb.WriteString(fmt.Sprintf(`<w:abstractNum w:abstractNumId="%d"><w:multiLevelType w:val="hybridMultilevel"/>`, in.id))
  617. for l := 0; l < 9; l++ {
  618. d := in.levels[l]
  619. if !d.set {
  620. d = defaultNumLevel(in.levels[0].fmt == "bullet", l)
  621. }
  622. start := d.start
  623. if start < 0 {
  624. start = 1
  625. }
  626. sb.WriteString(fmt.Sprintf(`<w:lvl w:ilvl="%d"><w:start w:val="%d"/><w:numFmt w:val="%s"/><w:lvlText w:val="%s"/><w:lvlJc w:val="left"/>`+
  627. `<w:pPr><w:ind w:left="%d" w:hanging="%d"/></w:pPr>`,
  628. l, start, d.fmt, xmltree.Escape(d.text), twip(d.leftPt), twip(d.hangPt)))
  629. if d.fmt == "bullet" {
  630. sb.WriteString(`<w:rPr><w:rFonts w:ascii="Arial" w:hAnsi="Arial" w:cs="Arial"/><w:u w:val="none"/></w:rPr>`)
  631. }
  632. sb.WriteString(`</w:lvl>`)
  633. }
  634. sb.WriteString(`</w:abstractNum>`)
  635. }
  636. for _, in := range nb.list {
  637. sb.WriteString(fmt.Sprintf(`<w:num w:numId="%d"><w:abstractNumId w:val="%d"/></w:num>`, in.id, in.id))
  638. }
  639. sb.WriteString(`</w:numbering>`)
  640. return sb.String()
  641. }
  642. var defaultBullets = []string{"\u25cf", "\u25cb", "\u25a0"}
  643. var defaultOrdered = []string{"decimal", "lowerLetter", "lowerRoman"}
  644. func defaultNumLevel(bullet bool, level int) numLevelDef {
  645. d := numLevelDef{start: 1, leftPt: float64(level+1) * 36, hangPt: 18, set: true}
  646. if bullet {
  647. d.fmt = "bullet"
  648. d.text = defaultBullets[level%3]
  649. } else {
  650. d.fmt = defaultOrdered[level%3]
  651. d.text = "%" + strconv.Itoa(level+1) + "."
  652. }
  653. return d
  654. }
  655. /* ---------------- the builder ---------------- */
  656. type docxBuilder struct {
  657. doc *model.Document
  658. textWPt float64 // the width a block at hand may take (a column or the page)
  659. // the indent of the containers the block at hand sits in
  660. containerLeft, containerRight float64
  661. fullWPt float64 // the page's text width
  662. colWPt float64 // one column of a multi-column page
  663. media []media.Entry
  664. imgCount int
  665. mediaByHash map[[32]byte]int
  666. // resolves the media?file= links pictures carry (nil = data URLs only)
  667. readVpath func(string) ([]byte, error)
  668. // review markup (review.go): pieces per comment anchor, pieces
  669. // written so far, Word ids, and the revision counter
  670. cmtTotal map[string]int
  671. cmtSeen map[string]int
  672. cmtWordID map[string]int
  673. cmtOrder []*model.DocComment
  674. revID int
  675. inRev bool
  676. docPrID int
  677. num docxNumbering
  678. fnIDs map[string]int
  679. fnOrder []string
  680. bookmarkN int
  681. // multi-column documents: blocks with class "col-span-all" (IEEE-style
  682. // title/author rows) are emitted into their own single-column section,
  683. // separated from the columned body by a continuous section break
  684. multiCol bool
  685. sectDivider string
  686. lastSpan bool
  687. anyBlock bool
  688. usedDivider bool
  689. // runs the next paragraph writes before and after its text: the
  690. // begin and end of a table of contents' TOC field
  691. paraPre, paraPost string
  692. }
  693. // Build serializes a Document into a complete .docx file; pictures
  694. // must be inline data URLs
  695. func Build(doc *model.Document) ([]byte, error) {
  696. return BuildMedia(doc, nil)
  697. }
  698. // BuildMedia serializes a Document, reading pictures that are
  699. // media?file= links through readVpath
  700. func BuildMedia(doc *model.Document, readVpath func(string) ([]byte, error)) ([]byte, error) {
  701. if doc == nil {
  702. return nil, errors.New("nil document")
  703. }
  704. b := &docxBuilder{doc: doc, fnIDs: map[string]int{}, mediaByHash: map[[32]byte]int{}, readVpath: readVpath,
  705. cmtTotal: map[string]int{}, cmtSeen: map[string]int{}, cmtWordID: map[string]int{}}
  706. b.fullWPt = textWidthPt(doc.Page)
  707. b.colWPt = b.fullWPt
  708. b.textWPt = b.fullWPt
  709. if doc.Page != nil && doc.Page.Columns > 1 {
  710. // a block inside the column flow is as wide as one column
  711. gap := doc.Page.ColGap * 72 / 25.4
  712. b.colWPt = (b.fullWPt - gap*float64(doc.Page.Columns-1)) / float64(doc.Page.Columns)
  713. b.multiCol = true
  714. b.sectDivider = `<w:p><w:pPr><w:sectPr><w:type w:val="continuous"/>` +
  715. pgGeometry(doc.Page) + `<w:cols w:num="1"/></w:sectPr></w:pPr></w:p>`
  716. }
  717. docPart := &docxPart{}
  718. body, err := b.convertBlocks(doc.HTML, docPart, true)
  719. if err != nil {
  720. return nil, err
  721. }
  722. // header / footer parts, each with its own relationships
  723. hfOn := doc.HFMode != model.HFModeNone
  724. type hfOut struct {
  725. xml string
  726. part *docxPart
  727. }
  728. var header, footer *hfOut
  729. if hfOn {
  730. if h := b.hfBody(doc.HeaderHTML, doc.Header, false); h != nil {
  731. header = &hfOut{xml: h.xml, part: h.part}
  732. }
  733. }
  734. if f := b.hfBody(doc.FooterHTML, doc.Footer, doc.PageNumbers); f != nil {
  735. if !hfOn {
  736. // "none" drops the text but a page counter is its own setting
  737. f = b.hfBody("", "", doc.PageNumbers)
  738. }
  739. if f != nil {
  740. footer = &hfOut{xml: f.xml, part: f.part}
  741. }
  742. }
  743. // footnotes referenced by the text (and the notes inside them)
  744. var fnXML string
  745. fnPart := &docxPart{}
  746. if len(b.fnOrder) > 0 {
  747. fnXML, err = b.footnotesXML(fnPart)
  748. if err != nil {
  749. return nil, err
  750. }
  751. }
  752. cmtXML, cmtExtXML := b.commentsXML()
  753. buf := new(bytes.Buffer)
  754. zw := zip.NewWriter(buf)
  755. add := func(name string, data []byte) error {
  756. w, err := zw.Create(name)
  757. if err != nil {
  758. return err
  759. }
  760. _, err = w.Write(data)
  761. return err
  762. }
  763. addS := func(name, content string) error { return add(name, []byte(content)) }
  764. var ct strings.Builder
  765. ct.WriteString(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` + "\n")
  766. ct.WriteString(`<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">`)
  767. ct.WriteString(`<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>`)
  768. ct.WriteString(`<Default Extension="xml" ContentType="application/xml"/>`)
  769. ct.WriteString(`<Default Extension="png" ContentType="image/png"/>`)
  770. ct.WriteString(`<Default Extension="jpeg" ContentType="image/jpeg"/>`)
  771. ct.WriteString(`<Default Extension="gif" ContentType="image/gif"/>`)
  772. ct.WriteString(`<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>`)
  773. ct.WriteString(`<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>`)
  774. ct.WriteString(`<Override PartName="/word/settings.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml"/>`)
  775. ct.WriteString(`<Override PartName="/word/numbering.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml"/>`)
  776. if header != nil {
  777. ct.WriteString(`<Override PartName="/word/header1.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml"/>`)
  778. }
  779. if footer != nil {
  780. ct.WriteString(`<Override PartName="/word/footer1.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml"/>`)
  781. }
  782. if fnXML != "" {
  783. ct.WriteString(`<Override PartName="/word/footnotes.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml"/>`)
  784. }
  785. if cmtXML != "" {
  786. ct.WriteString(`<Override PartName="/word/comments.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml"/>`)
  787. }
  788. if cmtExtXML != "" {
  789. ct.WriteString(`<Override PartName="/word/commentsExtended.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtended+xml"/>`)
  790. }
  791. ct.WriteString(`</Types>`)
  792. if err := addS("[Content_Types].xml", ct.String()); err != nil {
  793. return nil, err
  794. }
  795. if err := addS("_rels/.rels", `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>`+"\n"+
  796. `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">`+
  797. `<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>`+
  798. `</Relationships>`); err != nil {
  799. return nil, err
  800. }
  801. fixed := `<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>` +
  802. `<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering" Target="numbering.xml"/>` +
  803. `<Relationship Id="rId5" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings" Target="settings.xml"/>`
  804. headerRef, footerRef := "", ""
  805. if header != nil {
  806. fixed += `<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/>`
  807. headerRef = `<w:headerReference w:type="default" r:id="rId3"/>`
  808. }
  809. if footer != nil {
  810. fixed += `<Relationship Id="rId4" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer" Target="footer1.xml"/>`
  811. footerRef = `<w:footerReference w:type="default" r:id="rId4"/>`
  812. }
  813. if fnXML != "" {
  814. fixed += `<Relationship Id="rId6" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes" Target="footnotes.xml"/>`
  815. }
  816. if cmtXML != "" {
  817. fixed += `<Relationship Id="rId7" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="comments.xml"/>`
  818. }
  819. if cmtExtXML != "" {
  820. fixed += `<Relationship Id="rId8" Type="http://schemas.microsoft.com/office/2011/relationships/commentsExtended" Target="commentsExtended.xml"/>`
  821. }
  822. if err := addS("word/_rels/document.xml.rels", docPart.relsXML(fixed)); err != nil {
  823. return nil, err
  824. }
  825. sect := buildSectPr(doc.Page, headerRef, footerRef, b.usedDivider, doc.HFMode == model.HFModeExceptFirst)
  826. if err := addS("word/document.xml", `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>`+"\n"+
  827. `<w:document `+docxNs+`><w:body>`+body+sect+`</w:body></w:document>`); err != nil {
  828. return nil, err
  829. }
  830. if err := addS("word/styles.xml", docxStylesXML(doc)); err != nil {
  831. return nil, err
  832. }
  833. settings := docxSettings
  834. if doc.TrackChanges {
  835. // "Suggest edits" on: Word goes on tracking where the editor left off
  836. settings = strings.Replace(settings, `<w:defaultTabStop`, `<w:trackRevisions/><w:defaultTabStop`, 1)
  837. }
  838. if err := addS("word/settings.xml", settings); err != nil {
  839. return nil, err
  840. }
  841. if cmtXML != "" {
  842. if err := addS("word/comments.xml", cmtXML); err != nil {
  843. return nil, err
  844. }
  845. }
  846. if cmtExtXML != "" {
  847. if err := addS("word/commentsExtended.xml", cmtExtXML); err != nil {
  848. return nil, err
  849. }
  850. }
  851. if err := addS("word/numbering.xml", b.num.xml()); err != nil {
  852. return nil, err
  853. }
  854. if header != nil {
  855. if err := addS("word/header1.xml", hfPartXML("hdr", header.xml)); err != nil {
  856. return nil, err
  857. }
  858. if err := addS("word/_rels/header1.xml.rels", header.part.relsXML("")); err != nil {
  859. return nil, err
  860. }
  861. }
  862. if footer != nil {
  863. if err := addS("word/footer1.xml", hfPartXML("ftr", footer.xml)); err != nil {
  864. return nil, err
  865. }
  866. if err := addS("word/_rels/footer1.xml.rels", footer.part.relsXML("")); err != nil {
  867. return nil, err
  868. }
  869. }
  870. if fnXML != "" {
  871. if err := addS("word/footnotes.xml", fnXML); err != nil {
  872. return nil, err
  873. }
  874. if err := addS("word/_rels/footnotes.xml.rels", fnPart.relsXML("")); err != nil {
  875. return nil, err
  876. }
  877. }
  878. for _, m := range b.media {
  879. if err := add(fmt.Sprintf("word/media/image%d.%s", m.Index, m.Ext), m.Data); err != nil {
  880. return nil, err
  881. }
  882. }
  883. if err := zw.Close(); err != nil {
  884. return nil, err
  885. }
  886. return buf.Bytes(), nil
  887. }
  888. // textWidthPt is the width of the text column for a page setup
  889. func textWidthPt(pc *model.PageConf) float64 {
  890. size, orient := "A4", "portrait"
  891. mL, mR := 25.4, 25.4
  892. if pc != nil {
  893. if _, ok := pageSizesTwips[pc.Size]; ok {
  894. size = pc.Size
  895. }
  896. orient = pc.Orientation
  897. if pc.Margins != nil {
  898. mL, mR = pc.Margins.Left, pc.Margins.Right
  899. }
  900. }
  901. dim := pageSizesTwips[size]
  902. w := float64(dim[0])
  903. if orient == "landscape" {
  904. w = float64(dim[1])
  905. }
  906. return w/20 - (mL+mR)*72/25.4
  907. }
  908. // convertBlocks parses a fragment of editor HTML into body XML
  909. func (b *docxBuilder) convertBlocks(src string, part *docxPart, top bool) (string, error) {
  910. root, err := html.Parse(strings.NewReader("<body>" + src + "</body>"))
  911. if err != nil {
  912. return "", errors.New("cannot parse document HTML: " + err.Error())
  913. }
  914. body := htmlutil.FindNode(root, "body")
  915. if body == nil {
  916. return "", nil
  917. }
  918. liftReviewWrappers(body)
  919. if top {
  920. b.countComments(body)
  921. b.numberComments()
  922. }
  923. var sb strings.Builder
  924. base := wRunStyle{font: "Arial", sizePt: 11, color: "000000"}
  925. b.blocks(body, part, base, &sb, top)
  926. return sb.String(), nil
  927. }
  928. type hfResult struct {
  929. xml string
  930. part *docxPart
  931. }
  932. // hfBody renders a header/footer: rich HTML, else plain text, plus an
  933. // automatic centred page number
  934. func (b *docxBuilder) hfBody(richHTML, text string, pageNumbers bool) *hfResult {
  935. part := &docxPart{}
  936. var sb strings.Builder
  937. if strings.TrimSpace(richHTML) != "" {
  938. x, err := b.convertBlocks(richHTML, part, false)
  939. if err == nil {
  940. sb.WriteString(x)
  941. }
  942. } else if strings.TrimSpace(text) != "" {
  943. rs := wRunStyle{font: "Arial", sizePt: 9, color: "6B7078"}
  944. sb.WriteString(`<w:p><w:r>` + rs.rPr() + `<w:t xml:space="preserve">` + xmltree.Escape(text) + `</w:t></w:r></w:p>`)
  945. }
  946. hasField := strings.Contains(richHTML, `data-field="PAGE"`)
  947. if pageNumbers && !hasField {
  948. rs := wRunStyle{font: "Arial", sizePt: 10, color: "444444"}
  949. // the page number the editor draws by itself: its own style marks it
  950. // so an import turns it back into the page-number switch
  951. sb.WriteString(`<w:p><w:pPr><w:pStyle w:val="` + autoPageNumberStyle + `"/><w:jc w:val="center"/></w:pPr><w:fldSimple w:instr=" PAGE "><w:r>` +
  952. rs.rPr() + `<w:t>1</w:t></w:r></w:fldSimple></w:p>`)
  953. }
  954. if sb.Len() == 0 {
  955. return nil
  956. }
  957. return &hfResult{xml: sb.String(), part: part}
  958. }
  959. func hfPartXML(root, inner string) string {
  960. return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` + "\n" +
  961. `<w:` + root + ` ` + docxNs + `>` + inner + `</w:` + root + `>`
  962. }
  963. // footnotesXML writes the separators and every referenced footnote
  964. func (b *docxBuilder) footnotesXML(part *docxPart) (string, error) {
  965. byID := map[string]string{}
  966. for _, fn := range b.doc.Footnotes {
  967. byID[fn.ID] = fn.HTML
  968. }
  969. var sb strings.Builder
  970. sb.WriteString(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` + "\n")
  971. sb.WriteString(`<w:footnotes ` + docxNs + `>`)
  972. sb.WriteString(`<w:footnote w:type="separator" w:id="-1"><w:p><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:separator/></w:r></w:p></w:footnote>`)
  973. sb.WriteString(`<w:footnote w:type="continuationSeparator" w:id="0"><w:p><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:continuationSeparator/></w:r></w:p></w:footnote>`)
  974. // notes can reference notes; walk until no new ones appear
  975. for i := 0; i < len(b.fnOrder); i++ {
  976. id := b.fnOrder[i]
  977. src := byID[id]
  978. if strings.TrimSpace(src) == "" {
  979. src = "<p><br></p>"
  980. }
  981. x, err := b.convertBlocks(src, part, false)
  982. if err != nil {
  983. return "", err
  984. }
  985. mark := `<w:r><w:rPr><w:rStyle w:val="FootnoteReference"/><w:vertAlign w:val="superscript"/></w:rPr><w:footnoteRef/></w:r>`
  986. if at := strings.Index(x, "</w:pPr>"); at >= 0 && at < strings.Index(x+"<w:r>", "<w:r>")+len("</w:pPr>") {
  987. x = x[:at+len("</w:pPr>")] + mark + x[at+len("</w:pPr>"):]
  988. } else if at := strings.Index(x, "<w:p>"); at >= 0 {
  989. x = x[:at+len("<w:p>")] + mark + x[at+len("<w:p>"):]
  990. } else {
  991. x = `<w:p>` + mark + `</w:p>` + x
  992. }
  993. sb.WriteString(fmt.Sprintf(`<w:footnote w:id="%d">`, b.fnIDs[id]))
  994. sb.WriteString(x)
  995. sb.WriteString(`</w:footnote>`)
  996. }
  997. sb.WriteString(`</w:footnotes>`)
  998. return sb.String(), nil
  999. }
  1000. /* ---------------- blocks ---------------- */
  1001. type pProps struct {
  1002. style string
  1003. beforePt, afterPt float64
  1004. hasBefore, hasAfter bool
  1005. lineRule string // auto | exact | atLeast
  1006. line int // twips (exact/atLeast) or 240ths (auto)
  1007. leftPt, rightPt, firstPt float64
  1008. hasInd bool
  1009. jc string
  1010. shade string
  1011. borders map[string]wBorder
  1012. keepNext, keepLines bool
  1013. widowOff bool
  1014. pageBreakBefore bool
  1015. tabs string
  1016. numID, ilvl int
  1017. bookmark string
  1018. mark string // paragraph mark run properties
  1019. }
  1020. func (pp pProps) xml() string {
  1021. var sb strings.Builder
  1022. sb.WriteString("<w:pPr>")
  1023. if pp.style != "" {
  1024. sb.WriteString(`<w:pStyle w:val="` + pp.style + `"/>`)
  1025. }
  1026. if pp.keepNext {
  1027. sb.WriteString(`<w:keepNext/>`)
  1028. }
  1029. if pp.keepLines {
  1030. sb.WriteString(`<w:keepLines/>`)
  1031. }
  1032. if pp.pageBreakBefore {
  1033. sb.WriteString(`<w:pageBreakBefore/>`)
  1034. }
  1035. if pp.widowOff {
  1036. sb.WriteString(`<w:widowControl w:val="0"/>`)
  1037. }
  1038. if pp.numID > 0 {
  1039. sb.WriteString(fmt.Sprintf(`<w:numPr><w:ilvl w:val="%d"/><w:numId w:val="%d"/></w:numPr>`, pp.ilvl, pp.numID))
  1040. }
  1041. if len(pp.borders) > 0 {
  1042. sb.WriteString("<w:pBdr>")
  1043. for _, side := range []string{"top", "left", "bottom", "right"} {
  1044. if bd, ok := pp.borders[side]; ok && bd.val != "nil" {
  1045. sb.WriteString(fmt.Sprintf(`<w:%s w:val="%s" w:sz="%d" w:space="%d" w:color="%s"/>`, side, bd.val, bd.sz, borderSpace(bd.space), bd.color))
  1046. }
  1047. }
  1048. sb.WriteString("</w:pBdr>")
  1049. }
  1050. if pp.shade != "" {
  1051. sb.WriteString(`<w:shd w:val="clear" w:color="auto" w:fill="` + pp.shade + `"/>`)
  1052. }
  1053. if pp.tabs != "" {
  1054. sb.WriteString(pp.tabs)
  1055. }
  1056. sp := ""
  1057. if pp.hasBefore {
  1058. sp += fmt.Sprintf(` w:before="%d"`, twip(pp.beforePt))
  1059. }
  1060. if pp.hasAfter {
  1061. sp += fmt.Sprintf(` w:after="%d"`, twip(pp.afterPt))
  1062. }
  1063. if pp.lineRule != "" {
  1064. sp += fmt.Sprintf(` w:line="%d" w:lineRule="%s"`, pp.line, pp.lineRule)
  1065. }
  1066. if sp != "" {
  1067. sb.WriteString(`<w:spacing` + sp + `/>`)
  1068. }
  1069. if pp.hasInd {
  1070. ind := fmt.Sprintf(` w:left="%d" w:right="%d"`, twip(pp.leftPt), twip(pp.rightPt))
  1071. if pp.firstPt < 0 {
  1072. ind += fmt.Sprintf(` w:hanging="%d"`, twip(-pp.firstPt))
  1073. } else {
  1074. ind += fmt.Sprintf(` w:firstLine="%d"`, twip(pp.firstPt))
  1075. }
  1076. sb.WriteString(`<w:ind` + ind + `/>`)
  1077. }
  1078. if pp.jc != "" {
  1079. sb.WriteString(`<w:jc w:val="` + pp.jc + `"/>`)
  1080. }
  1081. sb.WriteString(pp.mark)
  1082. sb.WriteString("</w:pPr>")
  1083. return sb.String()
  1084. }
  1085. // blockStyleOf reads one block element's paragraph and run formatting
  1086. func (b *docxBuilder) blockStyleOf(n *html.Node, parent wRunStyle) (pProps, wRunStyle) {
  1087. css := withDefaultCSS(editorBlockCSS[n.Data], cssDecls(htmlutil.Attr(n, "style")))
  1088. pp := pProps{}
  1089. rs := parent
  1090. key := n.Data
  1091. if hasClass(n, "doc-title") {
  1092. key = "doc-title"
  1093. } else if hasClass(n, "doc-subtitle") {
  1094. key = "doc-subtitle"
  1095. }
  1096. if def, ok := editorBlockDefaults[key]; ok && key != "p" {
  1097. pp.style = def.style
  1098. rs.sizePt = def.sizePt
  1099. rs.bold = def.bold
  1100. rs.italic = def.italic
  1101. rs.color = def.color
  1102. pp.beforePt, pp.afterPt = def.beforePt, def.afterPt
  1103. pp.hasBefore, pp.hasAfter = true, true
  1104. pp.keepNext = strings.HasPrefix(key, "h")
  1105. }
  1106. rs = rs.applyBlockCSS(css)
  1107. em := rs.sizePt
  1108. if v, ok := css["margin"]; ok {
  1109. if s, ok := boxSides(v, em); ok {
  1110. pp.beforePt, pp.afterPt = s[0], s[2]
  1111. pp.leftPt, pp.rightPt = s[3], s[1]
  1112. pp.hasBefore, pp.hasAfter, pp.hasInd = true, true, true
  1113. }
  1114. }
  1115. if v, ok := css["margin-top"]; ok {
  1116. if pt, ok := cssPt(v, em); ok {
  1117. pp.beforePt = pt
  1118. pp.hasBefore = true
  1119. }
  1120. }
  1121. if v, ok := css["margin-bottom"]; ok {
  1122. if pt, ok := cssPt(v, em); ok {
  1123. pp.afterPt = pt
  1124. pp.hasAfter = true
  1125. }
  1126. }
  1127. if v, ok := css["margin-left"]; ok {
  1128. if pt, ok := cssPt(v, em); ok {
  1129. pp.leftPt = pt
  1130. pp.hasInd = true
  1131. }
  1132. }
  1133. if v, ok := css["margin-right"]; ok {
  1134. if pt, ok := cssPt(v, em); ok {
  1135. pp.rightPt = pt
  1136. pp.hasInd = true
  1137. }
  1138. }
  1139. if v, ok := css["text-indent"]; ok {
  1140. if pt, ok := cssPt(v, em); ok {
  1141. pp.firstPt = pt
  1142. pp.hasInd = true
  1143. }
  1144. }
  1145. switch css["text-align"] {
  1146. case "center":
  1147. pp.jc = "center"
  1148. case "right", "end":
  1149. pp.jc = "right"
  1150. case "justify":
  1151. pp.jc = "both"
  1152. case "left", "start":
  1153. pp.jc = "left"
  1154. }
  1155. if c := htmlutil.CSSColorHex(css["background-color"]); c != "" {
  1156. pp.shade = c
  1157. rs.shade = ""
  1158. }
  1159. for side, bd := range cssBorderSides(css) {
  1160. if bd.val != "nil" {
  1161. if pp.borders == nil {
  1162. pp.borders = map[string]wBorder{}
  1163. }
  1164. pp.borders[side] = bd
  1165. }
  1166. }
  1167. // padding: inside a border it is the border's space, and the text keeps
  1168. // clear of the rule by width + space; with no border it is plain extra
  1169. // spacing or indent
  1170. var pad [4]float64 // top right bottom left
  1171. padSet := false
  1172. if v, ok := css["padding"]; ok {
  1173. if s, ok := boxSides(v, em); ok {
  1174. pad, padSet = s, true
  1175. }
  1176. }
  1177. for i, side := range []string{"top", "right", "bottom", "left"} {
  1178. if pt, ok := cssPt(css["padding-"+side], em); ok {
  1179. pad[i], padSet = pt, true
  1180. }
  1181. }
  1182. for i, side := range []string{"top", "right", "bottom", "left"} {
  1183. bd, bordered := pp.borders[side]
  1184. if !bordered && (!padSet || pad[i] == 0) {
  1185. continue
  1186. }
  1187. extra := pad[i]
  1188. if bordered {
  1189. // w:space is whole points: what rounding takes from it goes
  1190. // to the spacing outside the rule (the indent already counts
  1191. // the full padding)
  1192. bd.space = pad[i]
  1193. pp.borders[side] = bd
  1194. extra = float64(bd.sz)/8 + pad[i]
  1195. }
  1196. frac := pad[i] - float64(borderSpace(pad[i]))
  1197. switch side {
  1198. case "top":
  1199. if !bordered {
  1200. pp.beforePt += extra
  1201. } else {
  1202. pp.beforePt += frac
  1203. }
  1204. pp.hasBefore = true
  1205. case "bottom":
  1206. if !bordered {
  1207. pp.afterPt += extra
  1208. } else {
  1209. pp.afterPt += frac
  1210. }
  1211. pp.hasAfter = true
  1212. case "left":
  1213. pp.leftPt += extra
  1214. pp.hasInd = true
  1215. case "right":
  1216. pp.rightPt += extra
  1217. pp.hasInd = true
  1218. }
  1219. }
  1220. pp.beforePt, pp.afterPt = math.Max(0, pp.beforePt), math.Max(0, pp.afterPt)
  1221. // line spacing: data-ls (multiple), data-lsexact, data-lsmin; a legacy
  1222. // unitless line-height means a multiple too
  1223. if v := htmlutil.Attr(n, "data-lsexact"); v != "" {
  1224. if pt, ok := cssPt(v, em); ok {
  1225. pp.lineRule, pp.line = "exact", twip(pt)
  1226. }
  1227. } else if v := htmlutil.Attr(n, "data-lsmin"); v != "" {
  1228. if pt, ok := cssPt(v, em); ok {
  1229. pp.lineRule, pp.line = "atLeast", twip(pt)
  1230. }
  1231. } else if v := htmlutil.Attr(n, "data-ls"); v != "" {
  1232. if f, err := strconv.ParseFloat(v, 64); err == nil && f > 0 {
  1233. pp.lineRule, pp.line = "auto", int(math.Round(f*240))
  1234. }
  1235. } else if v, ok := css["line-height"]; ok {
  1236. if f, err := strconv.ParseFloat(v, 64); err == nil && f > 0 {
  1237. pp.lineRule, pp.line = "auto", int(math.Round(f*240))
  1238. }
  1239. }
  1240. pp.keepNext = pp.keepNext || htmlutil.Attr(n, "data-keep-next") == "1"
  1241. pp.keepLines = htmlutil.Attr(n, "data-keep-lines") == "1"
  1242. pp.widowOff = htmlutil.Attr(n, "data-widow") == "0"
  1243. pp.pageBreakBefore = htmlutil.Attr(n, "data-page-break-before") == "1"
  1244. if v := htmlutil.Attr(n, "data-tabs"); v != "" {
  1245. pp.tabs = tabsXML(v)
  1246. }
  1247. if id := htmlutil.Attr(n, "id"); id != "" {
  1248. pp.bookmark = id
  1249. }
  1250. if hasClass(n, "doc-toc") {
  1251. pp.style = tocStyleOf(n)
  1252. }
  1253. return pp, rs
  1254. }
  1255. // tabsXML turns data-tabs ("right:451.28:dot;left:36:none") into w:tabs
  1256. func tabsXML(v string) string {
  1257. var sb strings.Builder
  1258. for _, t := range strings.Split(v, ";") {
  1259. f := strings.Split(t, ":")
  1260. if len(f) < 2 {
  1261. continue
  1262. }
  1263. pos, err := strconv.ParseFloat(f[1], 64)
  1264. if err != nil {
  1265. continue
  1266. }
  1267. align := f[0]
  1268. switch align {
  1269. case "left", "right", "center", "decimal":
  1270. default:
  1271. align = "left"
  1272. }
  1273. leader := "none"
  1274. if len(f) > 2 && f[2] != "" {
  1275. leader = f[2]
  1276. }
  1277. sb.WriteString(fmt.Sprintf(`<w:tab w:val="%s" w:leader="%s" w:pos="%d"/>`, align, xmltree.Escape(leader), twip(pos)))
  1278. }
  1279. if sb.Len() == 0 {
  1280. return ""
  1281. }
  1282. return "<w:tabs>" + sb.String() + "</w:tabs>"
  1283. }
  1284. // blocks emits the block-level children of an element
  1285. func (b *docxBuilder) blocks(n *html.Node, part *docxPart, rs wRunStyle, sb *strings.Builder, top bool) {
  1286. var toc tocRun
  1287. var pending *html.Node // first of a run of stray inline nodes
  1288. flushInline := func(stop *html.Node) {
  1289. if pending == nil {
  1290. return
  1291. }
  1292. pp := pProps{}
  1293. b.paragraph(pending, stop, pp, rs, part, sb)
  1294. pending = nil
  1295. }
  1296. for c := n.FirstChild; c != nil; c = c.NextSibling {
  1297. if c.Type == html.TextNode {
  1298. if strings.TrimSpace(c.Data) != "" && pending == nil {
  1299. pending = c
  1300. }
  1301. continue
  1302. }
  1303. if c.Type != html.ElementNode {
  1304. continue
  1305. }
  1306. if !isBlockElement(c) {
  1307. if pending == nil {
  1308. pending = c
  1309. }
  1310. continue
  1311. }
  1312. flushInline(c)
  1313. if !isTocPara(c) {
  1314. toc.close(sb)
  1315. }
  1316. if top && b.multiCol {
  1317. span := hasClass(c, "col-span-all")
  1318. if b.anyBlock && b.lastSpan && !span {
  1319. sb.WriteString(b.sectDivider)
  1320. b.usedDivider = true
  1321. }
  1322. b.lastSpan = span
  1323. b.textWPt = b.colWPt
  1324. if span {
  1325. b.textWPt = b.fullWPt
  1326. }
  1327. }
  1328. b.anyBlock = true
  1329. toc.before(c, sb, b)
  1330. b.block(c, part, rs, sb)
  1331. }
  1332. flushInline(nil)
  1333. toc.close(sb)
  1334. }
  1335. func isBlockElement(n *html.Node) bool {
  1336. if n.Type != html.ElementNode {
  1337. return false
  1338. }
  1339. if n.Data == "img" && hasClass(n, "doc-anchor") {
  1340. return false // lives inside a paragraph
  1341. }
  1342. switch n.Data {
  1343. case "p", "div", "h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "li", "table",
  1344. "blockquote", "pre", "hr", "section", "article", "header", "footer", "figure":
  1345. return true
  1346. }
  1347. return false
  1348. }
  1349. // block emits one block element
  1350. func (b *docxBuilder) block(c *html.Node, part *docxPart, rs wRunStyle, sb *strings.Builder) {
  1351. if hasClass(c, "doc-pagebreak") {
  1352. sb.WriteString(`<w:p><w:r><w:br w:type="page"/></w:r></w:p>`)
  1353. return
  1354. }
  1355. switch c.Data {
  1356. case "ul", "ol":
  1357. b.list(c, part, rs, sb, 0, b.containerLeft, "")
  1358. case "table":
  1359. b.table(c, part, rs, sb)
  1360. case "hr":
  1361. // docs.css: a 1px rule with 14pt either side; a 1pt exact line
  1362. // holds it, and the style brings it back as an <hr> on import
  1363. sb.WriteString(`<w:p><w:pPr><w:pStyle w:val="` + autoRuleStyle + `"/><w:pBdr><w:top w:val="single" w:sz="6" w:space="0" w:color="C9CDD3"/></w:pBdr>` +
  1364. `<w:spacing w:before="280" w:after="265" w:line="20" w:lineRule="exact"/><w:rPr><w:sz w:val="2"/><w:szCs w:val="2"/></w:rPr></w:pPr></w:p>`)
  1365. case "pre":
  1366. pp, prs := b.blockStyleOf(c, rs)
  1367. b.paragraph(c.FirstChild, nil, pp, prs, part, sb)
  1368. case "blockquote":
  1369. pp, prs := b.blockStyleOf(c, rs)
  1370. if htmlutil.HasBlockChild(c) {
  1371. b.inContainer(pp, func() { b.blocks(c, part, prs, sb, false) })
  1372. } else {
  1373. b.paragraph(c.FirstChild, nil, pp, prs, part, sb)
  1374. }
  1375. default:
  1376. pp, prs := b.blockStyleOf(c, rs)
  1377. if htmlutil.HasBlockChild(c) {
  1378. // a container: its own inline runs become paragraphs between
  1379. // the nested blocks
  1380. inner := pp
  1381. inner.leftPt, inner.rightPt = 0, 0
  1382. b.inContainer(pp, func() { b.containerWithStyle(c, part, inner, prs, sb) })
  1383. return
  1384. }
  1385. b.paragraph(c.FirstChild, nil, pp, prs, part, sb)
  1386. }
  1387. }
  1388. // inContainer runs fn with the blocks it writes inside a container's
  1389. // indent (a blockquote the browser's indent command made, a div)
  1390. func (b *docxBuilder) inContainer(pp pProps, fn func()) {
  1391. l, r := b.containerLeft, b.containerRight
  1392. b.containerLeft += pp.leftPt
  1393. b.containerRight += pp.rightPt
  1394. fn()
  1395. b.containerLeft, b.containerRight = l, r
  1396. }
  1397. // containerWithStyle handles a div/p that holds nested blocks
  1398. func (b *docxBuilder) containerWithStyle(c *html.Node, part *docxPart, pp pProps, rs wRunStyle, sb *strings.Builder) {
  1399. var pending *html.Node
  1400. flush := func(stop *html.Node) {
  1401. if pending != nil {
  1402. b.paragraph(pending, stop, pp, rs, part, sb)
  1403. pending = nil
  1404. }
  1405. }
  1406. for ch := c.FirstChild; ch != nil; ch = ch.NextSibling {
  1407. if isBlockElement(ch) {
  1408. flush(ch)
  1409. b.block(ch, part, rs, sb)
  1410. continue
  1411. }
  1412. if pending == nil && !(ch.Type == html.TextNode && strings.TrimSpace(ch.Data) == "") {
  1413. pending = ch
  1414. }
  1415. }
  1416. flush(nil)
  1417. }
  1418. /* ---------------- paragraphs and runs ---------------- */
  1419. type runBuf struct {
  1420. sb strings.Builder
  1421. any bool
  1422. }
  1423. // paragraph writes the inline nodes from first up to (not including) stop
  1424. func (b *docxBuilder) paragraph(first, stop *html.Node, pp pProps, rs wRunStyle, part *docxPart, sb *strings.Builder) {
  1425. rb := &runBuf{}
  1426. for n := first; n != nil && n != stop; n = n.NextSibling {
  1427. b.inline(n, rs, part, rb)
  1428. }
  1429. runs := rb.sb.String()
  1430. // a line break that ends a block opens no line in HTML
  1431. if strings.HasSuffix(runs, "<w:br/></w:r>") {
  1432. if at := strings.LastIndex(runs, "<w:r>"); at >= 0 {
  1433. runs = runs[:at]
  1434. rb.any = strings.Contains(runs, "<w:t") || strings.Contains(runs, "<w:tab/>") ||
  1435. strings.Contains(runs, "<w:drawing>") || strings.Contains(runs, "<w:br/>") ||
  1436. strings.Contains(runs, "footnoteReference") || strings.Contains(runs, "fldSimple")
  1437. }
  1438. }
  1439. if pp.numID == 0 && (b.containerLeft != 0 || b.containerRight != 0) {
  1440. pp.leftPt += b.containerLeft
  1441. pp.rightPt += b.containerRight
  1442. pp.hasInd = true
  1443. }
  1444. pp.mark = rs.rPr()
  1445. sb.WriteString("<w:p>")
  1446. sb.WriteString(pp.xml())
  1447. if pp.bookmark != "" {
  1448. b.bookmarkN++
  1449. sb.WriteString(fmt.Sprintf(`<w:bookmarkStart w:id="%d" w:name="%s"/><w:bookmarkEnd w:id="%d"/>`,
  1450. b.bookmarkN, xmltree.Escape(pp.bookmark), b.bookmarkN))
  1451. }
  1452. if b.paraPre != "" || b.paraPost != "" {
  1453. runs = b.paraPre + runs + b.paraPost
  1454. rb.any = true
  1455. b.paraPre, b.paraPost = "", ""
  1456. }
  1457. sb.WriteString(runs)
  1458. if !rb.any {
  1459. // the paragraph mark carries the size an empty line is laid out in
  1460. sb.WriteString(`<w:r>` + rs.rPr() + `</w:r>`)
  1461. }
  1462. sb.WriteString("</w:p>")
  1463. }
  1464. var wsRun = regexp.MustCompile(`[ \t\r\n\f]+`)
  1465. func (b *docxBuilder) textRuns(text string, rs wRunStyle, rb *runBuf) {
  1466. text = strings.ReplaceAll(text, "\u00a0", " ")
  1467. if !rs.preWrap {
  1468. text = wsRun.ReplaceAllString(text, " ")
  1469. }
  1470. if text == "" {
  1471. return
  1472. }
  1473. rpr := rs.rPr()
  1474. var cur strings.Builder
  1475. flush := func() {
  1476. if cur.Len() == 0 {
  1477. return
  1478. }
  1479. rb.sb.WriteString(`<w:r>` + rpr + `<w:t xml:space="preserve">` + xmltree.Escape(cur.String()) + `</w:t></w:r>`)
  1480. cur.Reset()
  1481. rb.any = true
  1482. }
  1483. for _, r := range text {
  1484. switch {
  1485. case r == '\t':
  1486. flush()
  1487. rb.sb.WriteString(`<w:r>` + rpr + `<w:tab/></w:r>`)
  1488. rb.any = true
  1489. case r == '\n' && rs.preWrap:
  1490. flush()
  1491. rb.sb.WriteString(`<w:r>` + rpr + `<w:br/></w:r>`)
  1492. rb.any = true
  1493. case r == '\u200b':
  1494. default:
  1495. cur.WriteRune(r)
  1496. }
  1497. }
  1498. flush()
  1499. }
  1500. // inline writes one inline node (and its subtree) as runs
  1501. func (b *docxBuilder) inline(n *html.Node, rs wRunStyle, part *docxPart, rb *runBuf) {
  1502. if n.Type == html.TextNode {
  1503. b.textRuns(n.Data, rs, rb)
  1504. return
  1505. }
  1506. if n.Type != html.ElementNode {
  1507. return
  1508. }
  1509. switch n.Data {
  1510. case "br":
  1511. rb.sb.WriteString(`<w:r>` + rs.rPr() + `<w:br/></w:r>`)
  1512. rb.any = true
  1513. return
  1514. case "img":
  1515. if x := b.image(n, part); x != "" {
  1516. rb.sb.WriteString(x)
  1517. rb.any = true
  1518. }
  1519. return
  1520. case "script", "style":
  1521. return
  1522. }
  1523. if hasClass(n, "doc-autobreak") {
  1524. return
  1525. }
  1526. if hasClass(n, "doc-tab") {
  1527. rb.sb.WriteString(`<w:r>` + rs.rPr() + `<w:tab/></w:r>`)
  1528. rb.any = true
  1529. return
  1530. }
  1531. if n.Data == "sup" && hasClass(n, "doc-fnref") {
  1532. id := htmlutil.Attr(n, "data-fn")
  1533. num, ok := b.fnIDs[id]
  1534. if !ok {
  1535. num = len(b.fnOrder) + 1
  1536. b.fnIDs[id] = num
  1537. b.fnOrder = append(b.fnOrder, id)
  1538. }
  1539. rb.sb.WriteString(fmt.Sprintf(`<w:r><w:rPr><w:rStyle w:val="FootnoteReference"/><w:vertAlign w:val="superscript"/></w:rPr><w:footnoteReference w:id="%d"/></w:r>`, num))
  1540. rb.any = true
  1541. return
  1542. }
  1543. if hasClass(n, "doc-field") {
  1544. field := strings.ToUpper(htmlutil.Attr(n, "data-field"))
  1545. if field == "PAGE" || field == "NUMPAGES" {
  1546. inner := &runBuf{}
  1547. for c := n.FirstChild; c != nil; c = c.NextSibling {
  1548. b.inline(c, rs, part, inner)
  1549. }
  1550. if !inner.any {
  1551. inner.sb.WriteString(`<w:r>` + rs.rPr() + `<w:t>1</w:t></w:r>`)
  1552. }
  1553. rb.sb.WriteString(`<w:fldSimple w:instr=" ` + field + ` ">` + inner.sb.String() + `</w:fldSimple>`)
  1554. rb.any = true
  1555. return
  1556. }
  1557. }
  1558. if b.reviewInline(n, rs, part, rb) {
  1559. return
  1560. }
  1561. crs := rs
  1562. switch n.Data {
  1563. case "b", "strong":
  1564. crs.bold = true
  1565. case "i", "em":
  1566. crs.italic = true
  1567. case "u", "ins":
  1568. crs.underline = true
  1569. case "s", "strike", "del":
  1570. crs.strike = true
  1571. case "code", "tt", "kbd", "samp":
  1572. crs.font = "Consolas"
  1573. case "sup":
  1574. crs.vert = "superscript"
  1575. case "sub":
  1576. crs.vert = "subscript"
  1577. case "font":
  1578. if c := htmlutil.CSSColorHex(htmlutil.Attr(n, "color")); c != "" {
  1579. crs.color = c
  1580. }
  1581. if f := htmlutil.Attr(n, "face"); f != "" {
  1582. crs.font = fonts.FirstFamily(f)
  1583. }
  1584. case "a":
  1585. // the editor underlines and colours links unless the link says
  1586. // "inherit" (an imported link whose runs carry their own look)
  1587. css := cssDecls(htmlutil.Attr(n, "style"))
  1588. if css["color"] != "inherit" {
  1589. crs.color = "1A58C2"
  1590. }
  1591. if !strings.Contains(css["text-decoration"], "inherit") && css["text-decoration"] != "none" {
  1592. crs.underline = true
  1593. }
  1594. }
  1595. crs = crs.applyCSS(cssDecls(htmlutil.Attr(n, "style")))
  1596. if n.Data == "a" {
  1597. href := htmlutil.Attr(n, "href")
  1598. inner := &runBuf{}
  1599. for c := n.FirstChild; c != nil; c = c.NextSibling {
  1600. b.inline(c, crs, part, inner)
  1601. }
  1602. if !inner.any {
  1603. return
  1604. }
  1605. switch {
  1606. case strings.HasPrefix(href, "#") && len(href) > 1:
  1607. rb.sb.WriteString(`<w:hyperlink w:anchor="` + xmltree.Escape(href[1:]) + `">` + inner.sb.String() + `</w:hyperlink>`)
  1608. case href != "" && !strings.HasPrefix(strings.ToLower(strings.TrimSpace(href)), "javascript:"):
  1609. rid := part.add(relHyperlink, href, true)
  1610. rb.sb.WriteString(`<w:hyperlink r:id="` + rid + `">` + inner.sb.String() + `</w:hyperlink>`)
  1611. default:
  1612. rb.sb.WriteString(inner.sb.String())
  1613. }
  1614. rb.any = true
  1615. return
  1616. }
  1617. for c := n.FirstChild; c != nil; c = c.NextSibling {
  1618. if isBlockElement(c) {
  1619. continue // blocks inside inline content are not representable in a run
  1620. }
  1621. b.inline(c, crs, part, rb)
  1622. }
  1623. }
  1624. /* ---------------- pictures ---------------- */
  1625. var insetRe = regexp.MustCompile(`inset\(\s*([-\d.]+)%?\s*([-\d.]+)?%?\s*([-\d.]+)?%?\s*([-\d.]+)?%?\s*\)`)
  1626. func (b *docxBuilder) image(n *html.Node, part *docxPart) string {
  1627. // data-export-src: the PNG the editor rendered for a picture Word cannot
  1628. // take as it is (an SVG chart, a WebP); src stays the original
  1629. src := htmlutil.Attr(n, "data-export-src")
  1630. if src == "" {
  1631. src = htmlutil.Attr(n, "src")
  1632. }
  1633. data, ext, ok := media.ImageSrcBytes(src, b.readVpath)
  1634. if !ok {
  1635. return "" // a picture that cannot be read or embedded is skipped
  1636. }
  1637. // the same picture twice is one media part
  1638. sum := sha256.Sum256(data)
  1639. idx, seen := b.mediaByHash[sum]
  1640. if !seen {
  1641. b.imgCount++
  1642. idx = b.imgCount
  1643. b.mediaByHash[sum] = idx
  1644. b.media = append(b.media, media.Entry{Index: idx, Ext: ext, Data: data})
  1645. }
  1646. rid := part.add(relImage, fmt.Sprintf("media/image%d.%s", idx, ext), false)
  1647. css := cssDecls(htmlutil.Attr(n, "style"))
  1648. natW, natH := 0.0, 0.0
  1649. if cfg, _, err := image.DecodeConfig(bytes.NewReader(data)); err == nil {
  1650. natW, natH = float64(cfg.Width), float64(cfg.Height)
  1651. }
  1652. dim := func(name string) float64 {
  1653. if v, ok := css[name]; ok {
  1654. if pt, ok := cssPt(v, 11); ok && pt > 0 {
  1655. return pt
  1656. }
  1657. }
  1658. if a := htmlutil.Attr(n, name); a != "" {
  1659. if pt, ok := cssPt(a, 11); ok && pt > 0 {
  1660. return pt
  1661. }
  1662. }
  1663. return 0
  1664. }
  1665. wPt, hPt := dim("width"), dim("height")
  1666. switch {
  1667. case wPt > 0 && hPt <= 0:
  1668. if natW > 0 && natH > 0 {
  1669. hPt = wPt * natH / natW
  1670. } else {
  1671. hPt = wPt * 3 / 4
  1672. }
  1673. case hPt > 0 && wPt <= 0:
  1674. if natW > 0 && natH > 0 {
  1675. wPt = hPt * natW / natH
  1676. } else {
  1677. wPt = hPt * 4 / 3
  1678. }
  1679. case wPt <= 0 && hPt <= 0:
  1680. if natW > 0 && natH > 0 {
  1681. wPt, hPt = natW*0.75, natH*0.75
  1682. } else {
  1683. wPt, hPt = 300, 225
  1684. }
  1685. }
  1686. anchor := hasClass(n, "doc-anchor")
  1687. // an inline picture cannot be wider than the text column (the editor's
  1688. // max-width: 100%), and the editor scales it whole there - a stated
  1689. // height too (its aspect-ratio, docs.js fitPicture); an anchored
  1690. // picture may bleed past
  1691. if !anchor && b.textWPt > 0 && wPt > b.textWPt+0.5 {
  1692. hPt = hPt * b.textWPt / wPt
  1693. wPt = b.textWPt
  1694. }
  1695. cx, cy := int64(math.Round(wPt*12700)), int64(math.Round(hPt*12700))
  1696. crop := ""
  1697. if m := insetRe.FindStringSubmatch(css["object-view-box"]); m != nil {
  1698. vals := []string{m[1], m[2], m[3], m[4]}
  1699. fl := make([]float64, 4)
  1700. for i, v := range vals {
  1701. if v == "" {
  1702. v = vals[0]
  1703. if i == 3 && m[2] != "" {
  1704. v = m[2]
  1705. }
  1706. }
  1707. fl[i], _ = strconv.ParseFloat(v, 64)
  1708. }
  1709. crop = fmt.Sprintf(`<a:srcRect t="%d" r="%d" b="%d" l="%d"/>`,
  1710. int(math.Round(fl[0]*1000)), int(math.Round(fl[1]*1000)), int(math.Round(fl[2]*1000)), int(math.Round(fl[3]*1000)))
  1711. }
  1712. line := `<a:ln><a:noFill/></a:ln>`
  1713. borderPt := 0.0
  1714. if v, ok := css["border"]; ok {
  1715. if bd, ok := cssBorder(v); ok && bd.val != "nil" {
  1716. borderPt = float64(bd.sz) / 8
  1717. line = fmt.Sprintf(`<a:ln w="%d"><a:solidFill><a:srgbClr val="%s"/></a:solidFill><a:prstDash val="solid"/></a:ln>`,
  1718. int64(borderPt*12700), bd.color)
  1719. }
  1720. }
  1721. // the outline and the sideways margin (Google Docs sets pictures 1.5pt
  1722. // apart) ride on the effect extent, which Word lays out around the frame
  1723. mlPt, _ := cssPt(css["margin-left"], 11)
  1724. mrPt, _ := cssPt(css["margin-right"], 11)
  1725. if anchor {
  1726. mlPt, mrPt = 0, 0
  1727. }
  1728. eff := fmt.Sprintf(`<wp:effectExtent l="%d" t="%d" r="%d" b="%d"/>`,
  1729. int64((borderPt+mlPt)*12700), int64(borderPt*12700), int64((borderPt+mrPt)*12700), int64(borderPt*12700))
  1730. b.docPrID++
  1731. alt := xmltree.Escape(htmlutil.Attr(n, "alt"))
  1732. graphic := fmt.Sprintf(`<wp:docPr id="%d" name="Picture %d" descr="%s"/>`+
  1733. `<wp:cNvGraphicFramePr><a:graphicFrameLocks noChangeAspect="1"/></wp:cNvGraphicFramePr>`+
  1734. `<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">`+
  1735. `<pic:pic><pic:nvPicPr><pic:cNvPr id="%d" name="Picture %d"/><pic:cNvPicPr/></pic:nvPicPr>`+
  1736. `<pic:blipFill><a:blip r:embed="%s"/>%s<a:stretch><a:fillRect/></a:stretch></pic:blipFill>`+
  1737. `<pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="%d" cy="%d"/></a:xfrm>`+
  1738. `<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>%s</pic:spPr></pic:pic>`+
  1739. `</a:graphicData></a:graphic>`,
  1740. b.docPrID, b.docPrID, alt, b.docPrID, b.docPrID, rid, crop, cx, cy, line)
  1741. if anchor {
  1742. xPt, _ := cssPt(css["margin-left"], 11)
  1743. yPt, _ := cssPt(css["margin-top"], 11)
  1744. wrap := `<wp:wrapTopAndBottom/>`
  1745. posH := fmt.Sprintf(`<wp:positionH relativeFrom="column"><wp:posOffset>%d</wp:posOffset></wp:positionH>`, int64(math.Round(xPt*12700)))
  1746. if fl := css["float"]; fl == "left" || fl == "right" {
  1747. wrap = `<wp:wrapSquare wrapText="bothSides"/>`
  1748. if fl == "right" {
  1749. posH = `<wp:positionH relativeFrom="column"><wp:align>right</wp:align></wp:positionH>`
  1750. }
  1751. }
  1752. return fmt.Sprintf(`<w:r><w:drawing><wp:anchor distT="0" distB="0" distL="0" distR="0" simplePos="0" relativeHeight="%d" behindDoc="0" locked="0" layoutInCell="1" allowOverlap="1">`+
  1753. `<wp:simplePos x="0" y="0"/>%s<wp:positionV relativeFrom="paragraph"><wp:posOffset>%d</wp:posOffset></wp:positionV>`+
  1754. `<wp:extent cx="%d" cy="%d"/>%s%s%s</wp:anchor></w:drawing></w:r>`,
  1755. b.docPrID, posH, int64(math.Round(yPt*12700)), cx, cy, eff, wrap, graphic)
  1756. }
  1757. return fmt.Sprintf(`<w:r><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="%d" cy="%d"/>%s%s</wp:inline></w:drawing></w:r>`,
  1758. cx, cy, eff, graphic)
  1759. }
  1760. /* ---------------- lists ---------------- */
  1761. // list writes an ol/ul (depth = nesting level, leftPt = the indent its
  1762. // parent list's text starts at)
  1763. func (b *docxBuilder) list(l *html.Node, part *docxPart, rs wRunStyle, sb *strings.Builder, depth int, leftPt float64, key string) {
  1764. if depth > 8 {
  1765. depth = 8
  1766. }
  1767. css := cssDecls(htmlutil.Attr(l, "style"))
  1768. pad := 36.0
  1769. if v, ok := css["padding-left"]; ok {
  1770. if pt, ok := cssPt(v, rs.sizePt); ok {
  1771. pad = pt
  1772. }
  1773. }
  1774. hang := 18.0
  1775. if v, ok := css["--doc-hang"]; ok {
  1776. if pt, ok := cssPt(v, rs.sizePt); ok {
  1777. hang = pt
  1778. }
  1779. }
  1780. left := leftPt + pad
  1781. lrs := rs.applyBlockCSS(css)
  1782. if depth == 0 {
  1783. key = htmlutil.Attr(l, "data-num")
  1784. if key != "" {
  1785. key = "num:" + key
  1786. }
  1787. }
  1788. inst := b.num.instance(key)
  1789. if depth == 0 && key == "" {
  1790. // a list without an id is its own list: key it by its instance
  1791. key = fmt.Sprintf("inst:%d", inst.id)
  1792. b.num.byKey[key] = inst
  1793. }
  1794. if !inst.levels[depth].set {
  1795. d := defaultNumLevel(l.Data == "ul", depth)
  1796. if f := htmlutil.Attr(l, "data-fmt"); f != "" {
  1797. d.fmt = f
  1798. if f == "bullet" && l.Data == "ol" {
  1799. d.text = defaultBullets[depth%3]
  1800. }
  1801. if f != "bullet" && l.Data == "ul" {
  1802. d.text = "%" + strconv.Itoa(depth+1) + "."
  1803. }
  1804. }
  1805. if t, ok := attrPresent(l, "data-lvltext"); ok {
  1806. d.text = t
  1807. }
  1808. if s, err := strconv.Atoi(htmlutil.Attr(l, "start")); err == nil {
  1809. d.start = s
  1810. }
  1811. if hasClass(l, "of-checklist") {
  1812. d.fmt, d.text = "bullet", "\u2610"
  1813. }
  1814. d.leftPt, d.hangPt = left, hang
  1815. inst.levels[depth] = d
  1816. }
  1817. for c := l.FirstChild; c != nil; c = c.NextSibling {
  1818. if c.Type != html.ElementNode {
  1819. continue
  1820. }
  1821. switch c.Data {
  1822. case "li":
  1823. b.listItem(c, part, lrs, sb, inst, depth, left, hang, key)
  1824. case "ul", "ol":
  1825. b.list(c, part, lrs, sb, depth+1, left, key)
  1826. default:
  1827. if isBlockElement(c) {
  1828. b.block(c, part, lrs, sb)
  1829. }
  1830. }
  1831. }
  1832. }
  1833. func attrPresent(n *html.Node, name string) (string, bool) {
  1834. for _, a := range n.Attr {
  1835. if a.Key == name {
  1836. return a.Val, true
  1837. }
  1838. }
  1839. return "", false
  1840. }
  1841. func (b *docxBuilder) listItem(li *html.Node, part *docxPart, rs wRunStyle, sb *strings.Builder, inst *numInstance, depth int, left, hang float64, key string) {
  1842. pp, prs := b.blockStyleOf(li, rs)
  1843. pp.numID, pp.ilvl = inst.id, depth
  1844. pp.leftPt, pp.firstPt, pp.hasInd = left, -hang, true
  1845. numbered := false
  1846. var pending *html.Node
  1847. flush := func(stop *html.Node) {
  1848. if pending == nil {
  1849. return
  1850. }
  1851. ip := pp
  1852. if numbered {
  1853. // a later paragraph of the same item: aligned, not numbered
  1854. ip.numID = 0
  1855. ip.firstPt = 0
  1856. }
  1857. b.paragraph(pending, stop, ip, prs, part, sb)
  1858. numbered = true
  1859. pending = nil
  1860. }
  1861. for c := li.FirstChild; c != nil; c = c.NextSibling {
  1862. if c.Type == html.ElementNode && (c.Data == "ul" || c.Data == "ol") {
  1863. flush(c)
  1864. if !numbered {
  1865. b.paragraph(nil, nil, pp, prs, part, sb)
  1866. numbered = true
  1867. }
  1868. b.list(c, part, prs, sb, depth+1, left, key)
  1869. continue
  1870. }
  1871. if isBlockElement(c) {
  1872. flush(c)
  1873. cpp, crs := b.blockStyleOf(c, prs)
  1874. if !numbered {
  1875. cpp.numID, cpp.ilvl = inst.id, depth
  1876. cpp.firstPt = -hang
  1877. numbered = true
  1878. }
  1879. cpp.leftPt, cpp.hasInd = left, true
  1880. b.paragraph(c.FirstChild, nil, cpp, crs, part, sb)
  1881. continue
  1882. }
  1883. if pending == nil && !(c.Type == html.TextNode && strings.TrimSpace(c.Data) == "" && c.NextSibling != nil) {
  1884. pending = c
  1885. }
  1886. }
  1887. flush(nil)
  1888. if !numbered {
  1889. b.paragraph(nil, nil, pp, prs, part, sb)
  1890. }
  1891. }
  1892. /* ---------------- tables ---------------- */
  1893. type tcell struct {
  1894. node *html.Node
  1895. col, span, rows int
  1896. }
  1897. func (b *docxBuilder) table(t *html.Node, part *docxPart, rs wRunStyle, sb *strings.Builder) {
  1898. css := cssDecls(htmlutil.Attr(t, "style"))
  1899. rs = rs.applyBlockCSS(css)
  1900. // rows (thead/tbody/tfoot flattened), skipping layout spacers
  1901. var rows []*html.Node
  1902. var collect func(n *html.Node)
  1903. collect = func(n *html.Node) {
  1904. for c := n.FirstChild; c != nil; c = c.NextSibling {
  1905. if c.Type != html.ElementNode {
  1906. continue
  1907. }
  1908. switch c.Data {
  1909. case "thead", "tbody", "tfoot":
  1910. collect(c)
  1911. case "tr":
  1912. if !hasClass(c, "doc-autobreak") {
  1913. rows = append(rows, c)
  1914. }
  1915. }
  1916. }
  1917. }
  1918. collect(t)
  1919. if len(rows) == 0 {
  1920. return
  1921. }
  1922. // lay the cells out on the grid (rowspans occupy the rows below)
  1923. occupied := map[[2]int]bool{}
  1924. grid := make([][]tcell, len(rows))
  1925. nCols := 0
  1926. for r, tr := range rows {
  1927. col := 0
  1928. for td := tr.FirstChild; td != nil; td = td.NextSibling {
  1929. if td.Type != html.ElementNode || (td.Data != "td" && td.Data != "th") {
  1930. continue
  1931. }
  1932. for occupied[[2]int{r, col}] {
  1933. col++
  1934. }
  1935. span, _ := strconv.Atoi(htmlutil.Attr(td, "colspan"))
  1936. if span < 1 {
  1937. span = 1
  1938. }
  1939. rspan, _ := strconv.Atoi(htmlutil.Attr(td, "rowspan"))
  1940. if rspan < 1 {
  1941. rspan = 1
  1942. }
  1943. if r+rspan > len(rows) {
  1944. rspan = len(rows) - r
  1945. }
  1946. grid[r] = append(grid[r], tcell{node: td, col: col, span: span, rows: rspan})
  1947. for rr := r; rr < r+rspan; rr++ {
  1948. for cc := col; cc < col+span; cc++ {
  1949. occupied[[2]int{rr, cc}] = true
  1950. }
  1951. }
  1952. col += span
  1953. }
  1954. for occupied[[2]int{r, col}] {
  1955. col++
  1956. }
  1957. if col > nCols {
  1958. nCols = col
  1959. }
  1960. }
  1961. if nCols == 0 {
  1962. nCols = 1
  1963. }
  1964. // widths: the table's own, then the colgroup's columns
  1965. tblW := b.textWPt
  1966. if v, ok := css["width"]; ok {
  1967. if strings.HasSuffix(v, "%") {
  1968. if p, err := strconv.ParseFloat(strings.TrimSuffix(v, "%"), 64); err == nil && p > 0 {
  1969. tblW = b.textWPt * math.Min(p, 100) / 100
  1970. }
  1971. } else if pt, ok := cssPt(v, rs.sizePt); ok && pt > 10 {
  1972. tblW = pt
  1973. }
  1974. }
  1975. colW := make([]float64, nCols)
  1976. got := 0
  1977. sum := 0.0
  1978. pctCols := false
  1979. for cg := t.FirstChild; cg != nil; cg = cg.NextSibling {
  1980. if cg.Type != html.ElementNode || cg.Data != "colgroup" {
  1981. continue
  1982. }
  1983. for col := cg.FirstChild; col != nil && got < nCols; col = col.NextSibling {
  1984. if col.Type != html.ElementNode || col.Data != "col" {
  1985. continue
  1986. }
  1987. w := htmlutil.StyleProp(htmlutil.Attr(col, "style"), "width")
  1988. if strings.HasSuffix(w, "%") {
  1989. if p, err := strconv.ParseFloat(strings.TrimSuffix(w, "%"), 64); err == nil {
  1990. colW[got] = p
  1991. pctCols = true
  1992. }
  1993. } else if pt, ok := cssPt(w, 11); ok {
  1994. colW[got] = pt
  1995. }
  1996. sum += colW[got]
  1997. got++
  1998. }
  1999. }
  2000. if got == nCols && sum > 0 {
  2001. if pctCols || math.Abs(sum-tblW) > 1 && css["width"] == "" {
  2002. if !pctCols {
  2003. tblW = sum
  2004. }
  2005. for i := range colW {
  2006. colW[i] = colW[i] * tblW / sum
  2007. }
  2008. } else if math.Abs(sum-tblW) > 1 {
  2009. for i := range colW {
  2010. colW[i] = colW[i] * tblW / sum
  2011. }
  2012. }
  2013. } else {
  2014. for i := range colW {
  2015. colW[i] = tblW / float64(nCols)
  2016. }
  2017. }
  2018. var tp strings.Builder
  2019. // a table made in the editor (not an imported one) is marked: it has
  2020. // docs.css's spacing above and below, which a Word table cannot carry
  2021. tblStyle := "TableGrid"
  2022. if htmlutil.Attr(t, "data-docx") == "" {
  2023. tblStyle = editorTableStyle
  2024. }
  2025. tp.WriteString(`<w:tbl><w:tblPr><w:tblStyle w:val="` + tblStyle + `"/>`)
  2026. tp.WriteString(fmt.Sprintf(`<w:tblW w:w="%d" w:type="dxa"/>`, twip(tblW)))
  2027. switch {
  2028. case css["margin-left"] == "auto" && css["margin-right"] == "auto":
  2029. tp.WriteString(`<w:jc w:val="center"/>`)
  2030. case css["margin-left"] == "auto":
  2031. tp.WriteString(`<w:jc w:val="right"/>`)
  2032. default:
  2033. pt, _ := cssPt(css["margin-left"], 11)
  2034. if pt += b.containerLeft; pt != 0 {
  2035. tp.WriteString(fmt.Sprintf(`<w:tblInd w:w="%d" w:type="dxa"/>`, twip(pt)))
  2036. }
  2037. }
  2038. tp.WriteString(`<w:tblLayout w:type="fixed"/><w:tblCellMar><w:top w:w="0" w:type="dxa"/><w:left w:w="0" w:type="dxa"/><w:bottom w:w="0" w:type="dxa"/><w:right w:w="0" w:type="dxa"/></w:tblCellMar>`)
  2039. tp.WriteString(`<w:tblLook w:val="0600"/></w:tblPr><w:tblGrid>`)
  2040. for _, w := range colW {
  2041. tp.WriteString(fmt.Sprintf(`<w:gridCol w:w="%d"/>`, twip(w)))
  2042. }
  2043. tp.WriteString(`</w:tblGrid>`)
  2044. sb.WriteString(tp.String())
  2045. // cells continuing a rowspan from above, per row and grid column
  2046. cont := map[[2]int]tcell{}
  2047. for r := range grid {
  2048. for _, c := range grid[r] {
  2049. for rr := r + 1; rr < r+c.rows; rr++ {
  2050. cont[[2]int{rr, c.col}] = c
  2051. }
  2052. }
  2053. }
  2054. for r, tr := range rows {
  2055. trCSS := cssDecls(htmlutil.Attr(tr, "style"))
  2056. sb.WriteString("<w:tr><w:trPr>")
  2057. if htmlutil.Attr(tr, "data-cant-split") == "1" {
  2058. sb.WriteString(`<w:cantSplit/>`)
  2059. }
  2060. if pt, ok := cssPt(trCSS["height"], 11); ok && pt > 0 {
  2061. rule := "atLeast"
  2062. if htmlutil.Attr(tr, "data-exact") == "1" {
  2063. rule = "exact"
  2064. }
  2065. sb.WriteString(fmt.Sprintf(`<w:trHeight w:val="%d" w:hRule="%s"/>`, twip(pt), rule))
  2066. }
  2067. if htmlutil.Attr(tr, "data-header-row") == "1" {
  2068. sb.WriteString(`<w:tblHeader/>`)
  2069. }
  2070. sb.WriteString("</w:trPr>")
  2071. cells := grid[r]
  2072. ci := 0
  2073. for col := 0; col < nCols; {
  2074. if c, ok := cont[[2]int{r, col}]; ok {
  2075. b.cell(c, part, rs, sb, colW, "continue")
  2076. col += c.span
  2077. continue
  2078. }
  2079. if ci < len(cells) && cells[ci].col == col {
  2080. c := cells[ci]
  2081. ci++
  2082. merge := ""
  2083. if c.rows > 1 {
  2084. merge = "restart"
  2085. }
  2086. b.cell(c, part, rs, sb, colW, merge)
  2087. col += c.span
  2088. continue
  2089. }
  2090. // a ragged row: pad with an empty cell so the grid stays whole
  2091. sb.WriteString(fmt.Sprintf(`<w:tc><w:tcPr><w:tcW w:w="%d" w:type="dxa"/></w:tcPr><w:p/></w:tc>`, twip(colW[col])))
  2092. col++
  2093. }
  2094. sb.WriteString("</w:tr>")
  2095. }
  2096. sb.WriteString("</w:tbl>")
  2097. }
  2098. func (b *docxBuilder) cell(c tcell, part *docxPart, rs wRunStyle, sb *strings.Builder, colW []float64, merge string) {
  2099. td := c.node
  2100. css := cssDecls(htmlutil.Attr(td, "style"))
  2101. w := 0.0
  2102. for i := c.col; i < c.col+c.span && i < len(colW); i++ {
  2103. w += colW[i]
  2104. }
  2105. var tp strings.Builder
  2106. tp.WriteString(fmt.Sprintf(`<w:tcPr><w:tcW w:w="%d" w:type="dxa"/>`, twip(w)))
  2107. if c.span > 1 {
  2108. tp.WriteString(fmt.Sprintf(`<w:gridSpan w:val="%d"/>`, c.span))
  2109. }
  2110. if merge == "restart" {
  2111. tp.WriteString(`<w:vMerge w:val="restart"/>`)
  2112. } else if merge == "continue" {
  2113. tp.WriteString(`<w:vMerge/>`)
  2114. }
  2115. // borders: the cell's own, else the editor's default grid
  2116. def := wBorder{val: "single", sz: 6, color: "B9BEC7"}
  2117. borders := map[string]wBorder{"top": def, "left": def, "bottom": def, "right": def}
  2118. for side, bd := range cssBorderSides(css) {
  2119. borders[side] = bd
  2120. }
  2121. tp.WriteString("<w:tcBorders>")
  2122. for _, side := range []string{"top", "left", "bottom", "right"} {
  2123. bd := borders[side]
  2124. if bd.val == "nil" {
  2125. tp.WriteString(`<w:` + side + ` w:val="nil"/>`)
  2126. } else {
  2127. tp.WriteString(fmt.Sprintf(`<w:%s w:val="%s" w:sz="%d" w:space="0" w:color="%s"/>`, side, bd.val, bd.sz, bd.color))
  2128. }
  2129. }
  2130. tp.WriteString("</w:tcBorders>")
  2131. shade := htmlutil.CSSColorHex(css["background-color"])
  2132. if shade == "" && td.Data == "th" {
  2133. shade = "F1F3F4"
  2134. }
  2135. if shade != "" {
  2136. tp.WriteString(`<w:shd w:val="clear" w:color="auto" w:fill="` + shade + `"/>`)
  2137. }
  2138. pad := [4]float64{3, 6, 3, 6} // the editor's 4px 8px
  2139. if v, ok := css["padding"]; ok {
  2140. if s, ok := boxSides(v, 11); ok {
  2141. pad = s
  2142. }
  2143. }
  2144. for i, side := range []string{"top", "right", "bottom", "left"} {
  2145. if pt, ok := cssPt(css["padding-"+side], 11); ok {
  2146. pad[i] = pt
  2147. }
  2148. }
  2149. tp.WriteString(fmt.Sprintf(`<w:tcMar><w:top w:w="%d" w:type="dxa"/><w:left w:w="%d" w:type="dxa"/><w:bottom w:w="%d" w:type="dxa"/><w:right w:w="%d" w:type="dxa"/></w:tcMar>`,
  2150. twip(pad[0]), twip(pad[3]), twip(pad[2]), twip(pad[1])))
  2151. switch css["vertical-align"] {
  2152. case "middle":
  2153. tp.WriteString(`<w:vAlign w:val="center"/>`)
  2154. case "bottom":
  2155. tp.WriteString(`<w:vAlign w:val="bottom"/>`)
  2156. default:
  2157. tp.WriteString(`<w:vAlign w:val="top"/>`)
  2158. }
  2159. tp.WriteString("</w:tcPr>")
  2160. sb.WriteString("<w:tc>" + tp.String())
  2161. if merge == "continue" {
  2162. sb.WriteString("<w:p/></w:tc>")
  2163. return
  2164. }
  2165. crs := rs.applyBlockCSS(css)
  2166. if td.Data == "th" {
  2167. crs.bold = true
  2168. if _, ok := css["text-align"]; !ok {
  2169. css["text-align"] = "center" // the browser's th default
  2170. }
  2171. }
  2172. var inner strings.Builder
  2173. if htmlutil.HasBlockChild(td) {
  2174. b.containerWithStyle(td, part, pProps{jc: jcOf(css)}, crs, &inner)
  2175. } else {
  2176. b.paragraph(td.FirstChild, nil, pProps{jc: jcOf(css)}, crs, part, &inner)
  2177. }
  2178. x := inner.String()
  2179. if !strings.Contains(x, "<w:p>") && !strings.Contains(x, "<w:p ") {
  2180. x += "<w:p/>"
  2181. }
  2182. // Word needs a cell to end in a paragraph (a nested table cannot be last)
  2183. if strings.HasSuffix(x, "</w:tbl>") {
  2184. x += "<w:p/>"
  2185. }
  2186. sb.WriteString(x + "</w:tc>")
  2187. }
  2188. func jcOf(css map[string]string) string {
  2189. switch css["text-align"] {
  2190. case "center":
  2191. return "center"
  2192. case "right":
  2193. return "right"
  2194. case "justify":
  2195. return "both"
  2196. }
  2197. return ""
  2198. }
  2199. /* ---------------- section / styles / settings ---------------- */
  2200. // pgGeometry renders the pgSz + pgMar pair for a page config
  2201. func pgGeometry(pc *model.PageConf) string {
  2202. size := "A4"
  2203. orient := "portrait"
  2204. mT, mR, mB, mL := 25.4, 25.4, 25.4, 25.4
  2205. hd, fd := 12.7, 12.7
  2206. if pc != nil {
  2207. if _, ok := pageSizesTwips[pc.Size]; ok {
  2208. size = pc.Size
  2209. }
  2210. if pc.Orientation == "landscape" {
  2211. orient = "landscape"
  2212. }
  2213. if pc.Margins != nil {
  2214. mT, mR, mB, mL = pc.Margins.Top, pc.Margins.Right, pc.Margins.Bottom, pc.Margins.Left
  2215. }
  2216. if pc.HeaderDist != nil {
  2217. hd = *pc.HeaderDist
  2218. }
  2219. if pc.FooterDist != nil {
  2220. fd = *pc.FooterDist
  2221. }
  2222. }
  2223. dim := pageSizesTwips[size]
  2224. w, h := dim[0], dim[1]
  2225. orientAttr := ""
  2226. if orient == "landscape" {
  2227. w, h = h, w
  2228. orientAttr = ` w:orient="landscape"`
  2229. }
  2230. return fmt.Sprintf(`<w:pgSz w:w="%d" w:h="%d"%s/>`+
  2231. `<w:pgMar w:top="%d" w:right="%d" w:bottom="%d" w:left="%d" w:header="%d" w:footer="%d" w:gutter="0"/>`,
  2232. w, h, orientAttr,
  2233. mmToTwips(mT), mmToTwips(mR), mmToTwips(mB), mmToTwips(mL), mmToTwips(hd), mmToTwips(fd))
  2234. }
  2235. func buildSectPr(pc *model.PageConf, headerRef, footerRef string, continuous, titlePg bool) string {
  2236. typ := ""
  2237. if continuous {
  2238. // the columned body continues on the same page as the spanning
  2239. // title section it follows
  2240. typ = `<w:type w:val="continuous"/>`
  2241. }
  2242. cols := ""
  2243. if pc != nil && pc.Columns > 1 {
  2244. gap := pc.ColGap
  2245. if gap <= 0 {
  2246. gap = 8
  2247. }
  2248. cols = fmt.Sprintf(`<w:cols w:num="%d" w:space="%d"/>`, pc.Columns, mmToTwips(gap))
  2249. }
  2250. first := ""
  2251. if titlePg {
  2252. // "different first page" with no first-page reference: Word leaves
  2253. // page 1's header and footer empty
  2254. first = `<w:titlePg/>`
  2255. }
  2256. return `<w:sectPr>` + headerRef + footerRef + typ + pgGeometry(pc) + cols +
  2257. first + `</w:sectPr>`
  2258. }
  2259. // docxStylesXML pins the editor's typography - Word substitutes its own
  2260. // Normal defaults (Calibri, 8pt after) for anything left unstated, and that
  2261. // substitution is exactly what makes a document's pages break somewhere
  2262. // else than in the editor. Spacing units: half-points for sz, twentieths of
  2263. // a point for spacing, 240ths of a line for w:line.
  2264. func docxStylesXML(doc *model.Document) string {
  2265. ls := 1.15
  2266. if doc != nil && doc.LineSpacing > 0 {
  2267. ls = doc.LineSpacing
  2268. }
  2269. line := int(math.Round(ls * 240))
  2270. var sb strings.Builder
  2271. sb.WriteString(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` + "\n")
  2272. sb.WriteString(`<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">`)
  2273. sb.WriteString(`<w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="Arial" w:hAnsi="Arial" w:cs="Arial" w:eastAsia="Arial"/><w:sz w:val="22"/><w:szCs w:val="22"/><w:lang w:val="en-US"/></w:rPr></w:rPrDefault>`)
  2274. sb.WriteString(fmt.Sprintf(`<w:pPrDefault><w:pPr><w:widowControl/><w:spacing w:before="0" w:after="0" w:line="%d" w:lineRule="auto"/></w:pPr></w:pPrDefault></w:docDefaults>`, line))
  2275. sb.WriteString(`<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/><w:qFormat/></w:style>`)
  2276. sb.WriteString(`<w:style w:type="table" w:default="1" w:styleId="TableNormal"><w:name w:val="Normal Table"/><w:tblPr><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>`)
  2277. sb.WriteString(`<w:style w:type="table" w:styleId="TableGrid"><w:name w:val="Table Grid"/><w:basedOn w:val="TableNormal"/></w:style>`)
  2278. sb.WriteString(`<w:style w:type="table" w:customStyle="1" w:styleId="` + editorTableStyle + `"><w:name w:val="Editor Table"/><w:basedOn w:val="TableNormal"/></w:style>`)
  2279. names := []struct{ key, name string }{
  2280. {"h1", "heading 1"}, {"h2", "heading 2"}, {"h3", "heading 3"},
  2281. {"h4", "heading 4"}, {"h5", "heading 5"}, {"h6", "heading 6"},
  2282. {"doc-title", "Title"}, {"doc-subtitle", "Subtitle"},
  2283. }
  2284. for _, n := range names {
  2285. d := editorBlockDefaults[n.key]
  2286. rpr := fmt.Sprintf(`<w:color w:val="%s"/><w:sz w:val="%d"/><w:szCs w:val="%d"/>`, d.color, int(d.sizePt*2), int(d.sizePt*2))
  2287. if d.bold {
  2288. rpr = `<w:b/><w:bCs/>` + rpr
  2289. }
  2290. if d.italic {
  2291. rpr = `<w:i/><w:iCs/>` + rpr
  2292. }
  2293. keep := ""
  2294. if strings.HasPrefix(n.key, "h") {
  2295. keep = `<w:keepNext/><w:keepLines/>`
  2296. }
  2297. sb.WriteString(fmt.Sprintf(`<w:style w:type="paragraph" w:styleId="%s"><w:name w:val="%s"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:qFormat/>`+
  2298. `<w:pPr>%s<w:spacing w:before="%d" w:after="%d"/></w:pPr><w:rPr>%s</w:rPr></w:style>`,
  2299. d.style, n.name, keep, twip(d.beforePt), twip(d.afterPt), rpr))
  2300. }
  2301. // a table of contents: Word's own style names, so Word and the reader
  2302. // know the lines for what they are (the look is on each paragraph)
  2303. sb.WriteString(`<w:style w:type="paragraph" w:styleId="` + tocHeadingStyle + `"><w:name w:val="TOC Heading"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:uiPriority w:val="39"/><w:unhideWhenUsed/><w:qFormat/></w:style>`)
  2304. for lvl := 1; lvl <= 9; lvl++ {
  2305. sb.WriteString(fmt.Sprintf(`<w:style w:type="paragraph" w:styleId="TOC%d"><w:name w:val="toc %d"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:uiPriority w:val="39"/><w:unhideWhenUsed/></w:style>`, lvl, lvl))
  2306. }
  2307. sb.WriteString(`<w:style w:type="paragraph" w:customStyle="1" w:styleId="` + autoRuleStyle + `"><w:name w:val="Horizontal Rule"/></w:style>`)
  2308. sb.WriteString(`<w:style w:type="paragraph" w:customStyle="1" w:styleId="` + autoPageNumberStyle + `"><w:name w:val="Page Number Line"/><w:pPr><w:jc w:val="center"/></w:pPr></w:style>`)
  2309. sb.WriteString(`<w:style w:type="character" w:styleId="FootnoteReference"><w:name w:val="footnote reference"/><w:rPr><w:vertAlign w:val="superscript"/></w:rPr></w:style>`)
  2310. sb.WriteString(`<w:style w:type="character" w:styleId="Hyperlink"><w:name w:val="Hyperlink"/><w:rPr><w:color w:val="1A58C2"/><w:u w:val="single"/></w:rPr></w:style>`)
  2311. sb.WriteString(`</w:styles>`)
  2312. return sb.String()
  2313. }
  2314. const docxSettings = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  2315. <w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:defaultTabStop w:val="720"/><w:characterSpacingControl w:val="doNotCompress"/><w:compat><w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="15"/></w:compat></w:settings>`