writer.go 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399
  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. }
  690. // Build serializes a Document into a complete .docx file; pictures
  691. // must be inline data URLs
  692. func Build(doc *model.Document) ([]byte, error) {
  693. return BuildMedia(doc, nil)
  694. }
  695. // BuildMedia serializes a Document, reading pictures that are
  696. // media?file= links through readVpath
  697. func BuildMedia(doc *model.Document, readVpath func(string) ([]byte, error)) ([]byte, error) {
  698. if doc == nil {
  699. return nil, errors.New("nil document")
  700. }
  701. b := &docxBuilder{doc: doc, fnIDs: map[string]int{}, mediaByHash: map[[32]byte]int{}, readVpath: readVpath,
  702. cmtTotal: map[string]int{}, cmtSeen: map[string]int{}, cmtWordID: map[string]int{}}
  703. b.fullWPt = textWidthPt(doc.Page)
  704. b.colWPt = b.fullWPt
  705. b.textWPt = b.fullWPt
  706. if doc.Page != nil && doc.Page.Columns > 1 {
  707. // a block inside the column flow is as wide as one column
  708. gap := doc.Page.ColGap * 72 / 25.4
  709. b.colWPt = (b.fullWPt - gap*float64(doc.Page.Columns-1)) / float64(doc.Page.Columns)
  710. b.multiCol = true
  711. b.sectDivider = `<w:p><w:pPr><w:sectPr><w:type w:val="continuous"/>` +
  712. pgGeometry(doc.Page) + `<w:cols w:num="1"/></w:sectPr></w:pPr></w:p>`
  713. }
  714. docPart := &docxPart{}
  715. body, err := b.convertBlocks(doc.HTML, docPart, true)
  716. if err != nil {
  717. return nil, err
  718. }
  719. // header / footer parts, each with its own relationships
  720. hfOn := doc.HFMode != model.HFModeNone
  721. type hfOut struct {
  722. xml string
  723. part *docxPart
  724. }
  725. var header, footer *hfOut
  726. if hfOn {
  727. if h := b.hfBody(doc.HeaderHTML, doc.Header, false); h != nil {
  728. header = &hfOut{xml: h.xml, part: h.part}
  729. }
  730. }
  731. if f := b.hfBody(doc.FooterHTML, doc.Footer, doc.PageNumbers); f != nil {
  732. if !hfOn {
  733. // "none" drops the text but a page counter is its own setting
  734. f = b.hfBody("", "", doc.PageNumbers)
  735. }
  736. if f != nil {
  737. footer = &hfOut{xml: f.xml, part: f.part}
  738. }
  739. }
  740. // footnotes referenced by the text (and the notes inside them)
  741. var fnXML string
  742. fnPart := &docxPart{}
  743. if len(b.fnOrder) > 0 {
  744. fnXML, err = b.footnotesXML(fnPart)
  745. if err != nil {
  746. return nil, err
  747. }
  748. }
  749. cmtXML, cmtExtXML := b.commentsXML()
  750. buf := new(bytes.Buffer)
  751. zw := zip.NewWriter(buf)
  752. add := func(name string, data []byte) error {
  753. w, err := zw.Create(name)
  754. if err != nil {
  755. return err
  756. }
  757. _, err = w.Write(data)
  758. return err
  759. }
  760. addS := func(name, content string) error { return add(name, []byte(content)) }
  761. var ct strings.Builder
  762. ct.WriteString(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` + "\n")
  763. ct.WriteString(`<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">`)
  764. ct.WriteString(`<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>`)
  765. ct.WriteString(`<Default Extension="xml" ContentType="application/xml"/>`)
  766. ct.WriteString(`<Default Extension="png" ContentType="image/png"/>`)
  767. ct.WriteString(`<Default Extension="jpeg" ContentType="image/jpeg"/>`)
  768. ct.WriteString(`<Default Extension="gif" ContentType="image/gif"/>`)
  769. ct.WriteString(`<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>`)
  770. ct.WriteString(`<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>`)
  771. ct.WriteString(`<Override PartName="/word/settings.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml"/>`)
  772. ct.WriteString(`<Override PartName="/word/numbering.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml"/>`)
  773. if header != nil {
  774. ct.WriteString(`<Override PartName="/word/header1.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml"/>`)
  775. }
  776. if footer != nil {
  777. ct.WriteString(`<Override PartName="/word/footer1.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml"/>`)
  778. }
  779. if fnXML != "" {
  780. ct.WriteString(`<Override PartName="/word/footnotes.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml"/>`)
  781. }
  782. if cmtXML != "" {
  783. ct.WriteString(`<Override PartName="/word/comments.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml"/>`)
  784. }
  785. if cmtExtXML != "" {
  786. ct.WriteString(`<Override PartName="/word/commentsExtended.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtended+xml"/>`)
  787. }
  788. ct.WriteString(`</Types>`)
  789. if err := addS("[Content_Types].xml", ct.String()); err != nil {
  790. return nil, err
  791. }
  792. if err := addS("_rels/.rels", `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>`+"\n"+
  793. `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">`+
  794. `<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>`+
  795. `</Relationships>`); err != nil {
  796. return nil, err
  797. }
  798. fixed := `<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>` +
  799. `<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering" Target="numbering.xml"/>` +
  800. `<Relationship Id="rId5" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings" Target="settings.xml"/>`
  801. headerRef, footerRef := "", ""
  802. if header != nil {
  803. fixed += `<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/>`
  804. headerRef = `<w:headerReference w:type="default" r:id="rId3"/>`
  805. }
  806. if footer != nil {
  807. fixed += `<Relationship Id="rId4" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer" Target="footer1.xml"/>`
  808. footerRef = `<w:footerReference w:type="default" r:id="rId4"/>`
  809. }
  810. if fnXML != "" {
  811. fixed += `<Relationship Id="rId6" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes" Target="footnotes.xml"/>`
  812. }
  813. if cmtXML != "" {
  814. fixed += `<Relationship Id="rId7" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="comments.xml"/>`
  815. }
  816. if cmtExtXML != "" {
  817. fixed += `<Relationship Id="rId8" Type="http://schemas.microsoft.com/office/2011/relationships/commentsExtended" Target="commentsExtended.xml"/>`
  818. }
  819. if err := addS("word/_rels/document.xml.rels", docPart.relsXML(fixed)); err != nil {
  820. return nil, err
  821. }
  822. sect := buildSectPr(doc.Page, headerRef, footerRef, b.usedDivider, doc.HFMode == model.HFModeExceptFirst)
  823. if err := addS("word/document.xml", `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>`+"\n"+
  824. `<w:document `+docxNs+`><w:body>`+body+sect+`</w:body></w:document>`); err != nil {
  825. return nil, err
  826. }
  827. if err := addS("word/styles.xml", docxStylesXML(doc)); err != nil {
  828. return nil, err
  829. }
  830. settings := docxSettings
  831. if doc.TrackChanges {
  832. // "Suggest edits" on: Word goes on tracking where the editor left off
  833. settings = strings.Replace(settings, `<w:defaultTabStop`, `<w:trackRevisions/><w:defaultTabStop`, 1)
  834. }
  835. if err := addS("word/settings.xml", settings); err != nil {
  836. return nil, err
  837. }
  838. if cmtXML != "" {
  839. if err := addS("word/comments.xml", cmtXML); err != nil {
  840. return nil, err
  841. }
  842. }
  843. if cmtExtXML != "" {
  844. if err := addS("word/commentsExtended.xml", cmtExtXML); err != nil {
  845. return nil, err
  846. }
  847. }
  848. if err := addS("word/numbering.xml", b.num.xml()); err != nil {
  849. return nil, err
  850. }
  851. if header != nil {
  852. if err := addS("word/header1.xml", hfPartXML("hdr", header.xml)); err != nil {
  853. return nil, err
  854. }
  855. if err := addS("word/_rels/header1.xml.rels", header.part.relsXML("")); err != nil {
  856. return nil, err
  857. }
  858. }
  859. if footer != nil {
  860. if err := addS("word/footer1.xml", hfPartXML("ftr", footer.xml)); err != nil {
  861. return nil, err
  862. }
  863. if err := addS("word/_rels/footer1.xml.rels", footer.part.relsXML("")); err != nil {
  864. return nil, err
  865. }
  866. }
  867. if fnXML != "" {
  868. if err := addS("word/footnotes.xml", fnXML); err != nil {
  869. return nil, err
  870. }
  871. if err := addS("word/_rels/footnotes.xml.rels", fnPart.relsXML("")); err != nil {
  872. return nil, err
  873. }
  874. }
  875. for _, m := range b.media {
  876. if err := add(fmt.Sprintf("word/media/image%d.%s", m.Index, m.Ext), m.Data); err != nil {
  877. return nil, err
  878. }
  879. }
  880. if err := zw.Close(); err != nil {
  881. return nil, err
  882. }
  883. return buf.Bytes(), nil
  884. }
  885. // textWidthPt is the width of the text column for a page setup
  886. func textWidthPt(pc *model.PageConf) float64 {
  887. size, orient := "A4", "portrait"
  888. mL, mR := 25.4, 25.4
  889. if pc != nil {
  890. if _, ok := pageSizesTwips[pc.Size]; ok {
  891. size = pc.Size
  892. }
  893. orient = pc.Orientation
  894. if pc.Margins != nil {
  895. mL, mR = pc.Margins.Left, pc.Margins.Right
  896. }
  897. }
  898. dim := pageSizesTwips[size]
  899. w := float64(dim[0])
  900. if orient == "landscape" {
  901. w = float64(dim[1])
  902. }
  903. return w/20 - (mL+mR)*72/25.4
  904. }
  905. // convertBlocks parses a fragment of editor HTML into body XML
  906. func (b *docxBuilder) convertBlocks(src string, part *docxPart, top bool) (string, error) {
  907. root, err := html.Parse(strings.NewReader("<body>" + src + "</body>"))
  908. if err != nil {
  909. return "", errors.New("cannot parse document HTML: " + err.Error())
  910. }
  911. body := htmlutil.FindNode(root, "body")
  912. if body == nil {
  913. return "", nil
  914. }
  915. liftReviewWrappers(body)
  916. if top {
  917. b.countComments(body)
  918. b.numberComments()
  919. }
  920. var sb strings.Builder
  921. base := wRunStyle{font: "Arial", sizePt: 11, color: "000000"}
  922. b.blocks(body, part, base, &sb, top)
  923. return sb.String(), nil
  924. }
  925. type hfResult struct {
  926. xml string
  927. part *docxPart
  928. }
  929. // hfBody renders a header/footer: rich HTML, else plain text, plus an
  930. // automatic centred page number
  931. func (b *docxBuilder) hfBody(richHTML, text string, pageNumbers bool) *hfResult {
  932. part := &docxPart{}
  933. var sb strings.Builder
  934. if strings.TrimSpace(richHTML) != "" {
  935. x, err := b.convertBlocks(richHTML, part, false)
  936. if err == nil {
  937. sb.WriteString(x)
  938. }
  939. } else if strings.TrimSpace(text) != "" {
  940. rs := wRunStyle{font: "Arial", sizePt: 9, color: "6B7078"}
  941. sb.WriteString(`<w:p><w:r>` + rs.rPr() + `<w:t xml:space="preserve">` + xmltree.Escape(text) + `</w:t></w:r></w:p>`)
  942. }
  943. hasField := strings.Contains(richHTML, `data-field="PAGE"`)
  944. if pageNumbers && !hasField {
  945. rs := wRunStyle{font: "Arial", sizePt: 10, color: "444444"}
  946. // the page number the editor draws by itself: its own style marks it
  947. // so an import turns it back into the page-number switch
  948. 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>` +
  949. rs.rPr() + `<w:t>1</w:t></w:r></w:fldSimple></w:p>`)
  950. }
  951. if sb.Len() == 0 {
  952. return nil
  953. }
  954. return &hfResult{xml: sb.String(), part: part}
  955. }
  956. func hfPartXML(root, inner string) string {
  957. return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` + "\n" +
  958. `<w:` + root + ` ` + docxNs + `>` + inner + `</w:` + root + `>`
  959. }
  960. // footnotesXML writes the separators and every referenced footnote
  961. func (b *docxBuilder) footnotesXML(part *docxPart) (string, error) {
  962. byID := map[string]string{}
  963. for _, fn := range b.doc.Footnotes {
  964. byID[fn.ID] = fn.HTML
  965. }
  966. var sb strings.Builder
  967. sb.WriteString(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` + "\n")
  968. sb.WriteString(`<w:footnotes ` + docxNs + `>`)
  969. 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>`)
  970. 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>`)
  971. // notes can reference notes; walk until no new ones appear
  972. for i := 0; i < len(b.fnOrder); i++ {
  973. id := b.fnOrder[i]
  974. src := byID[id]
  975. if strings.TrimSpace(src) == "" {
  976. src = "<p><br></p>"
  977. }
  978. x, err := b.convertBlocks(src, part, false)
  979. if err != nil {
  980. return "", err
  981. }
  982. mark := `<w:r><w:rPr><w:rStyle w:val="FootnoteReference"/><w:vertAlign w:val="superscript"/></w:rPr><w:footnoteRef/></w:r>`
  983. if at := strings.Index(x, "</w:pPr>"); at >= 0 && at < strings.Index(x+"<w:r>", "<w:r>")+len("</w:pPr>") {
  984. x = x[:at+len("</w:pPr>")] + mark + x[at+len("</w:pPr>"):]
  985. } else if at := strings.Index(x, "<w:p>"); at >= 0 {
  986. x = x[:at+len("<w:p>")] + mark + x[at+len("<w:p>"):]
  987. } else {
  988. x = `<w:p>` + mark + `</w:p>` + x
  989. }
  990. sb.WriteString(fmt.Sprintf(`<w:footnote w:id="%d">`, b.fnIDs[id]))
  991. sb.WriteString(x)
  992. sb.WriteString(`</w:footnote>`)
  993. }
  994. sb.WriteString(`</w:footnotes>`)
  995. return sb.String(), nil
  996. }
  997. /* ---------------- blocks ---------------- */
  998. type pProps struct {
  999. style string
  1000. beforePt, afterPt float64
  1001. hasBefore, hasAfter bool
  1002. lineRule string // auto | exact | atLeast
  1003. line int // twips (exact/atLeast) or 240ths (auto)
  1004. leftPt, rightPt, firstPt float64
  1005. hasInd bool
  1006. jc string
  1007. shade string
  1008. borders map[string]wBorder
  1009. keepNext, keepLines bool
  1010. widowOff bool
  1011. pageBreakBefore bool
  1012. tabs string
  1013. numID, ilvl int
  1014. bookmark string
  1015. mark string // paragraph mark run properties
  1016. }
  1017. func (pp pProps) xml() string {
  1018. var sb strings.Builder
  1019. sb.WriteString("<w:pPr>")
  1020. if pp.style != "" {
  1021. sb.WriteString(`<w:pStyle w:val="` + pp.style + `"/>`)
  1022. }
  1023. if pp.keepNext {
  1024. sb.WriteString(`<w:keepNext/>`)
  1025. }
  1026. if pp.keepLines {
  1027. sb.WriteString(`<w:keepLines/>`)
  1028. }
  1029. if pp.pageBreakBefore {
  1030. sb.WriteString(`<w:pageBreakBefore/>`)
  1031. }
  1032. if pp.widowOff {
  1033. sb.WriteString(`<w:widowControl w:val="0"/>`)
  1034. }
  1035. if pp.numID > 0 {
  1036. sb.WriteString(fmt.Sprintf(`<w:numPr><w:ilvl w:val="%d"/><w:numId w:val="%d"/></w:numPr>`, pp.ilvl, pp.numID))
  1037. }
  1038. if len(pp.borders) > 0 {
  1039. sb.WriteString("<w:pBdr>")
  1040. for _, side := range []string{"top", "left", "bottom", "right"} {
  1041. if bd, ok := pp.borders[side]; ok && bd.val != "nil" {
  1042. 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))
  1043. }
  1044. }
  1045. sb.WriteString("</w:pBdr>")
  1046. }
  1047. if pp.shade != "" {
  1048. sb.WriteString(`<w:shd w:val="clear" w:color="auto" w:fill="` + pp.shade + `"/>`)
  1049. }
  1050. if pp.tabs != "" {
  1051. sb.WriteString(pp.tabs)
  1052. }
  1053. sp := ""
  1054. if pp.hasBefore {
  1055. sp += fmt.Sprintf(` w:before="%d"`, twip(pp.beforePt))
  1056. }
  1057. if pp.hasAfter {
  1058. sp += fmt.Sprintf(` w:after="%d"`, twip(pp.afterPt))
  1059. }
  1060. if pp.lineRule != "" {
  1061. sp += fmt.Sprintf(` w:line="%d" w:lineRule="%s"`, pp.line, pp.lineRule)
  1062. }
  1063. if sp != "" {
  1064. sb.WriteString(`<w:spacing` + sp + `/>`)
  1065. }
  1066. if pp.hasInd {
  1067. ind := fmt.Sprintf(` w:left="%d" w:right="%d"`, twip(pp.leftPt), twip(pp.rightPt))
  1068. if pp.firstPt < 0 {
  1069. ind += fmt.Sprintf(` w:hanging="%d"`, twip(-pp.firstPt))
  1070. } else {
  1071. ind += fmt.Sprintf(` w:firstLine="%d"`, twip(pp.firstPt))
  1072. }
  1073. sb.WriteString(`<w:ind` + ind + `/>`)
  1074. }
  1075. if pp.jc != "" {
  1076. sb.WriteString(`<w:jc w:val="` + pp.jc + `"/>`)
  1077. }
  1078. sb.WriteString(pp.mark)
  1079. sb.WriteString("</w:pPr>")
  1080. return sb.String()
  1081. }
  1082. // blockStyleOf reads one block element's paragraph and run formatting
  1083. func (b *docxBuilder) blockStyleOf(n *html.Node, parent wRunStyle) (pProps, wRunStyle) {
  1084. css := withDefaultCSS(editorBlockCSS[n.Data], cssDecls(htmlutil.Attr(n, "style")))
  1085. pp := pProps{}
  1086. rs := parent
  1087. key := n.Data
  1088. if hasClass(n, "doc-title") {
  1089. key = "doc-title"
  1090. } else if hasClass(n, "doc-subtitle") {
  1091. key = "doc-subtitle"
  1092. }
  1093. if def, ok := editorBlockDefaults[key]; ok && key != "p" {
  1094. pp.style = def.style
  1095. rs.sizePt = def.sizePt
  1096. rs.bold = def.bold
  1097. rs.italic = def.italic
  1098. rs.color = def.color
  1099. pp.beforePt, pp.afterPt = def.beforePt, def.afterPt
  1100. pp.hasBefore, pp.hasAfter = true, true
  1101. pp.keepNext = strings.HasPrefix(key, "h")
  1102. }
  1103. rs = rs.applyBlockCSS(css)
  1104. em := rs.sizePt
  1105. if v, ok := css["margin"]; ok {
  1106. if s, ok := boxSides(v, em); ok {
  1107. pp.beforePt, pp.afterPt = s[0], s[2]
  1108. pp.leftPt, pp.rightPt = s[3], s[1]
  1109. pp.hasBefore, pp.hasAfter, pp.hasInd = true, true, true
  1110. }
  1111. }
  1112. if v, ok := css["margin-top"]; ok {
  1113. if pt, ok := cssPt(v, em); ok {
  1114. pp.beforePt = pt
  1115. pp.hasBefore = true
  1116. }
  1117. }
  1118. if v, ok := css["margin-bottom"]; ok {
  1119. if pt, ok := cssPt(v, em); ok {
  1120. pp.afterPt = pt
  1121. pp.hasAfter = true
  1122. }
  1123. }
  1124. if v, ok := css["margin-left"]; ok {
  1125. if pt, ok := cssPt(v, em); ok {
  1126. pp.leftPt = pt
  1127. pp.hasInd = true
  1128. }
  1129. }
  1130. if v, ok := css["margin-right"]; ok {
  1131. if pt, ok := cssPt(v, em); ok {
  1132. pp.rightPt = pt
  1133. pp.hasInd = true
  1134. }
  1135. }
  1136. if v, ok := css["text-indent"]; ok {
  1137. if pt, ok := cssPt(v, em); ok {
  1138. pp.firstPt = pt
  1139. pp.hasInd = true
  1140. }
  1141. }
  1142. switch css["text-align"] {
  1143. case "center":
  1144. pp.jc = "center"
  1145. case "right", "end":
  1146. pp.jc = "right"
  1147. case "justify":
  1148. pp.jc = "both"
  1149. case "left", "start":
  1150. pp.jc = "left"
  1151. }
  1152. if c := htmlutil.CSSColorHex(css["background-color"]); c != "" {
  1153. pp.shade = c
  1154. rs.shade = ""
  1155. }
  1156. for side, bd := range cssBorderSides(css) {
  1157. if bd.val != "nil" {
  1158. if pp.borders == nil {
  1159. pp.borders = map[string]wBorder{}
  1160. }
  1161. pp.borders[side] = bd
  1162. }
  1163. }
  1164. // padding: inside a border it is the border's space, and the text keeps
  1165. // clear of the rule by width + space; with no border it is plain extra
  1166. // spacing or indent
  1167. var pad [4]float64 // top right bottom left
  1168. padSet := false
  1169. if v, ok := css["padding"]; ok {
  1170. if s, ok := boxSides(v, em); ok {
  1171. pad, padSet = s, true
  1172. }
  1173. }
  1174. for i, side := range []string{"top", "right", "bottom", "left"} {
  1175. if pt, ok := cssPt(css["padding-"+side], em); ok {
  1176. pad[i], padSet = pt, true
  1177. }
  1178. }
  1179. for i, side := range []string{"top", "right", "bottom", "left"} {
  1180. bd, bordered := pp.borders[side]
  1181. if !bordered && (!padSet || pad[i] == 0) {
  1182. continue
  1183. }
  1184. extra := pad[i]
  1185. if bordered {
  1186. // w:space is whole points: what rounding takes from it goes
  1187. // to the spacing outside the rule (the indent already counts
  1188. // the full padding)
  1189. bd.space = pad[i]
  1190. pp.borders[side] = bd
  1191. extra = float64(bd.sz)/8 + pad[i]
  1192. }
  1193. frac := pad[i] - float64(borderSpace(pad[i]))
  1194. switch side {
  1195. case "top":
  1196. if !bordered {
  1197. pp.beforePt += extra
  1198. } else {
  1199. pp.beforePt += frac
  1200. }
  1201. pp.hasBefore = true
  1202. case "bottom":
  1203. if !bordered {
  1204. pp.afterPt += extra
  1205. } else {
  1206. pp.afterPt += frac
  1207. }
  1208. pp.hasAfter = true
  1209. case "left":
  1210. pp.leftPt += extra
  1211. pp.hasInd = true
  1212. case "right":
  1213. pp.rightPt += extra
  1214. pp.hasInd = true
  1215. }
  1216. }
  1217. pp.beforePt, pp.afterPt = math.Max(0, pp.beforePt), math.Max(0, pp.afterPt)
  1218. // line spacing: data-ls (multiple), data-lsexact, data-lsmin; a legacy
  1219. // unitless line-height means a multiple too
  1220. if v := htmlutil.Attr(n, "data-lsexact"); v != "" {
  1221. if pt, ok := cssPt(v, em); ok {
  1222. pp.lineRule, pp.line = "exact", twip(pt)
  1223. }
  1224. } else if v := htmlutil.Attr(n, "data-lsmin"); v != "" {
  1225. if pt, ok := cssPt(v, em); ok {
  1226. pp.lineRule, pp.line = "atLeast", twip(pt)
  1227. }
  1228. } else if v := htmlutil.Attr(n, "data-ls"); v != "" {
  1229. if f, err := strconv.ParseFloat(v, 64); err == nil && f > 0 {
  1230. pp.lineRule, pp.line = "auto", int(math.Round(f*240))
  1231. }
  1232. } else if v, ok := css["line-height"]; ok {
  1233. if f, err := strconv.ParseFloat(v, 64); err == nil && f > 0 {
  1234. pp.lineRule, pp.line = "auto", int(math.Round(f*240))
  1235. }
  1236. }
  1237. pp.keepNext = pp.keepNext || htmlutil.Attr(n, "data-keep-next") == "1"
  1238. pp.keepLines = htmlutil.Attr(n, "data-keep-lines") == "1"
  1239. pp.widowOff = htmlutil.Attr(n, "data-widow") == "0"
  1240. pp.pageBreakBefore = htmlutil.Attr(n, "data-page-break-before") == "1"
  1241. if v := htmlutil.Attr(n, "data-tabs"); v != "" {
  1242. pp.tabs = tabsXML(v)
  1243. }
  1244. if id := htmlutil.Attr(n, "id"); id != "" {
  1245. pp.bookmark = id
  1246. }
  1247. return pp, rs
  1248. }
  1249. // tabsXML turns data-tabs ("right:451.28:dot;left:36:none") into w:tabs
  1250. func tabsXML(v string) string {
  1251. var sb strings.Builder
  1252. for _, t := range strings.Split(v, ";") {
  1253. f := strings.Split(t, ":")
  1254. if len(f) < 2 {
  1255. continue
  1256. }
  1257. pos, err := strconv.ParseFloat(f[1], 64)
  1258. if err != nil {
  1259. continue
  1260. }
  1261. align := f[0]
  1262. switch align {
  1263. case "left", "right", "center", "decimal":
  1264. default:
  1265. align = "left"
  1266. }
  1267. leader := "none"
  1268. if len(f) > 2 && f[2] != "" {
  1269. leader = f[2]
  1270. }
  1271. sb.WriteString(fmt.Sprintf(`<w:tab w:val="%s" w:leader="%s" w:pos="%d"/>`, align, xmltree.Escape(leader), twip(pos)))
  1272. }
  1273. if sb.Len() == 0 {
  1274. return ""
  1275. }
  1276. return "<w:tabs>" + sb.String() + "</w:tabs>"
  1277. }
  1278. // blocks emits the block-level children of an element
  1279. func (b *docxBuilder) blocks(n *html.Node, part *docxPart, rs wRunStyle, sb *strings.Builder, top bool) {
  1280. var pending *html.Node // first of a run of stray inline nodes
  1281. flushInline := func(stop *html.Node) {
  1282. if pending == nil {
  1283. return
  1284. }
  1285. pp := pProps{}
  1286. b.paragraph(pending, stop, pp, rs, part, sb)
  1287. pending = nil
  1288. }
  1289. for c := n.FirstChild; c != nil; c = c.NextSibling {
  1290. if c.Type == html.TextNode {
  1291. if strings.TrimSpace(c.Data) != "" && pending == nil {
  1292. pending = c
  1293. }
  1294. continue
  1295. }
  1296. if c.Type != html.ElementNode {
  1297. continue
  1298. }
  1299. if !isBlockElement(c) {
  1300. if pending == nil {
  1301. pending = c
  1302. }
  1303. continue
  1304. }
  1305. flushInline(c)
  1306. if top && b.multiCol {
  1307. span := hasClass(c, "col-span-all")
  1308. if b.anyBlock && b.lastSpan && !span {
  1309. sb.WriteString(b.sectDivider)
  1310. b.usedDivider = true
  1311. }
  1312. b.lastSpan = span
  1313. b.textWPt = b.colWPt
  1314. if span {
  1315. b.textWPt = b.fullWPt
  1316. }
  1317. }
  1318. b.anyBlock = true
  1319. b.block(c, part, rs, sb)
  1320. }
  1321. flushInline(nil)
  1322. }
  1323. func isBlockElement(n *html.Node) bool {
  1324. if n.Type != html.ElementNode {
  1325. return false
  1326. }
  1327. if n.Data == "img" && hasClass(n, "doc-anchor") {
  1328. return false // lives inside a paragraph
  1329. }
  1330. switch n.Data {
  1331. case "p", "div", "h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "li", "table",
  1332. "blockquote", "pre", "hr", "section", "article", "header", "footer", "figure":
  1333. return true
  1334. }
  1335. return false
  1336. }
  1337. // block emits one block element
  1338. func (b *docxBuilder) block(c *html.Node, part *docxPart, rs wRunStyle, sb *strings.Builder) {
  1339. if hasClass(c, "doc-pagebreak") {
  1340. sb.WriteString(`<w:p><w:r><w:br w:type="page"/></w:r></w:p>`)
  1341. return
  1342. }
  1343. switch c.Data {
  1344. case "ul", "ol":
  1345. b.list(c, part, rs, sb, 0, b.containerLeft, "")
  1346. case "table":
  1347. b.table(c, part, rs, sb)
  1348. case "hr":
  1349. // docs.css: a 1px rule with 14pt either side; a 1pt exact line
  1350. // holds it, and the style brings it back as an <hr> on import
  1351. 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>` +
  1352. `<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>`)
  1353. case "pre":
  1354. pp, prs := b.blockStyleOf(c, rs)
  1355. b.paragraph(c.FirstChild, nil, pp, prs, part, sb)
  1356. case "blockquote":
  1357. pp, prs := b.blockStyleOf(c, rs)
  1358. if htmlutil.HasBlockChild(c) {
  1359. b.inContainer(pp, func() { b.blocks(c, part, prs, sb, false) })
  1360. } else {
  1361. b.paragraph(c.FirstChild, nil, pp, prs, part, sb)
  1362. }
  1363. default:
  1364. pp, prs := b.blockStyleOf(c, rs)
  1365. if htmlutil.HasBlockChild(c) {
  1366. // a container: its own inline runs become paragraphs between
  1367. // the nested blocks
  1368. inner := pp
  1369. inner.leftPt, inner.rightPt = 0, 0
  1370. b.inContainer(pp, func() { b.containerWithStyle(c, part, inner, prs, sb) })
  1371. return
  1372. }
  1373. b.paragraph(c.FirstChild, nil, pp, prs, part, sb)
  1374. }
  1375. }
  1376. // inContainer runs fn with the blocks it writes inside a container's
  1377. // indent (a blockquote the browser's indent command made, a div)
  1378. func (b *docxBuilder) inContainer(pp pProps, fn func()) {
  1379. l, r := b.containerLeft, b.containerRight
  1380. b.containerLeft += pp.leftPt
  1381. b.containerRight += pp.rightPt
  1382. fn()
  1383. b.containerLeft, b.containerRight = l, r
  1384. }
  1385. // containerWithStyle handles a div/p that holds nested blocks
  1386. func (b *docxBuilder) containerWithStyle(c *html.Node, part *docxPart, pp pProps, rs wRunStyle, sb *strings.Builder) {
  1387. var pending *html.Node
  1388. flush := func(stop *html.Node) {
  1389. if pending != nil {
  1390. b.paragraph(pending, stop, pp, rs, part, sb)
  1391. pending = nil
  1392. }
  1393. }
  1394. for ch := c.FirstChild; ch != nil; ch = ch.NextSibling {
  1395. if isBlockElement(ch) {
  1396. flush(ch)
  1397. b.block(ch, part, rs, sb)
  1398. continue
  1399. }
  1400. if pending == nil && !(ch.Type == html.TextNode && strings.TrimSpace(ch.Data) == "") {
  1401. pending = ch
  1402. }
  1403. }
  1404. flush(nil)
  1405. }
  1406. /* ---------------- paragraphs and runs ---------------- */
  1407. type runBuf struct {
  1408. sb strings.Builder
  1409. any bool
  1410. }
  1411. // paragraph writes the inline nodes from first up to (not including) stop
  1412. func (b *docxBuilder) paragraph(first, stop *html.Node, pp pProps, rs wRunStyle, part *docxPart, sb *strings.Builder) {
  1413. rb := &runBuf{}
  1414. for n := first; n != nil && n != stop; n = n.NextSibling {
  1415. b.inline(n, rs, part, rb)
  1416. }
  1417. runs := rb.sb.String()
  1418. // a line break that ends a block opens no line in HTML
  1419. if strings.HasSuffix(runs, "<w:br/></w:r>") {
  1420. if at := strings.LastIndex(runs, "<w:r>"); at >= 0 {
  1421. runs = runs[:at]
  1422. rb.any = strings.Contains(runs, "<w:t") || strings.Contains(runs, "<w:tab/>") ||
  1423. strings.Contains(runs, "<w:drawing>") || strings.Contains(runs, "<w:br/>") ||
  1424. strings.Contains(runs, "footnoteReference") || strings.Contains(runs, "fldSimple")
  1425. }
  1426. }
  1427. if pp.numID == 0 && (b.containerLeft != 0 || b.containerRight != 0) {
  1428. pp.leftPt += b.containerLeft
  1429. pp.rightPt += b.containerRight
  1430. pp.hasInd = true
  1431. }
  1432. pp.mark = rs.rPr()
  1433. sb.WriteString("<w:p>")
  1434. sb.WriteString(pp.xml())
  1435. if pp.bookmark != "" {
  1436. b.bookmarkN++
  1437. sb.WriteString(fmt.Sprintf(`<w:bookmarkStart w:id="%d" w:name="%s"/><w:bookmarkEnd w:id="%d"/>`,
  1438. b.bookmarkN, xmltree.Escape(pp.bookmark), b.bookmarkN))
  1439. }
  1440. sb.WriteString(runs)
  1441. if !rb.any {
  1442. // the paragraph mark carries the size an empty line is laid out in
  1443. sb.WriteString(`<w:r>` + rs.rPr() + `</w:r>`)
  1444. }
  1445. sb.WriteString("</w:p>")
  1446. }
  1447. var wsRun = regexp.MustCompile(`[ \t\r\n\f]+`)
  1448. func (b *docxBuilder) textRuns(text string, rs wRunStyle, rb *runBuf) {
  1449. text = strings.ReplaceAll(text, "\u00a0", " ")
  1450. if !rs.preWrap {
  1451. text = wsRun.ReplaceAllString(text, " ")
  1452. }
  1453. if text == "" {
  1454. return
  1455. }
  1456. rpr := rs.rPr()
  1457. var cur strings.Builder
  1458. flush := func() {
  1459. if cur.Len() == 0 {
  1460. return
  1461. }
  1462. rb.sb.WriteString(`<w:r>` + rpr + `<w:t xml:space="preserve">` + xmltree.Escape(cur.String()) + `</w:t></w:r>`)
  1463. cur.Reset()
  1464. rb.any = true
  1465. }
  1466. for _, r := range text {
  1467. switch {
  1468. case r == '\t':
  1469. flush()
  1470. rb.sb.WriteString(`<w:r>` + rpr + `<w:tab/></w:r>`)
  1471. rb.any = true
  1472. case r == '\n' && rs.preWrap:
  1473. flush()
  1474. rb.sb.WriteString(`<w:r>` + rpr + `<w:br/></w:r>`)
  1475. rb.any = true
  1476. case r == '\u200b':
  1477. default:
  1478. cur.WriteRune(r)
  1479. }
  1480. }
  1481. flush()
  1482. }
  1483. // inline writes one inline node (and its subtree) as runs
  1484. func (b *docxBuilder) inline(n *html.Node, rs wRunStyle, part *docxPart, rb *runBuf) {
  1485. if n.Type == html.TextNode {
  1486. b.textRuns(n.Data, rs, rb)
  1487. return
  1488. }
  1489. if n.Type != html.ElementNode {
  1490. return
  1491. }
  1492. switch n.Data {
  1493. case "br":
  1494. rb.sb.WriteString(`<w:r>` + rs.rPr() + `<w:br/></w:r>`)
  1495. rb.any = true
  1496. return
  1497. case "img":
  1498. if x := b.image(n, part); x != "" {
  1499. rb.sb.WriteString(x)
  1500. rb.any = true
  1501. }
  1502. return
  1503. case "script", "style":
  1504. return
  1505. }
  1506. if hasClass(n, "doc-autobreak") {
  1507. return
  1508. }
  1509. if hasClass(n, "doc-tab") {
  1510. rb.sb.WriteString(`<w:r>` + rs.rPr() + `<w:tab/></w:r>`)
  1511. rb.any = true
  1512. return
  1513. }
  1514. if n.Data == "sup" && hasClass(n, "doc-fnref") {
  1515. id := htmlutil.Attr(n, "data-fn")
  1516. num, ok := b.fnIDs[id]
  1517. if !ok {
  1518. num = len(b.fnOrder) + 1
  1519. b.fnIDs[id] = num
  1520. b.fnOrder = append(b.fnOrder, id)
  1521. }
  1522. 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))
  1523. rb.any = true
  1524. return
  1525. }
  1526. if hasClass(n, "doc-field") {
  1527. field := strings.ToUpper(htmlutil.Attr(n, "data-field"))
  1528. if field == "PAGE" || field == "NUMPAGES" {
  1529. inner := &runBuf{}
  1530. for c := n.FirstChild; c != nil; c = c.NextSibling {
  1531. b.inline(c, rs, part, inner)
  1532. }
  1533. if !inner.any {
  1534. inner.sb.WriteString(`<w:r>` + rs.rPr() + `<w:t>1</w:t></w:r>`)
  1535. }
  1536. rb.sb.WriteString(`<w:fldSimple w:instr=" ` + field + ` ">` + inner.sb.String() + `</w:fldSimple>`)
  1537. rb.any = true
  1538. return
  1539. }
  1540. }
  1541. if b.reviewInline(n, rs, part, rb) {
  1542. return
  1543. }
  1544. crs := rs
  1545. switch n.Data {
  1546. case "b", "strong":
  1547. crs.bold = true
  1548. case "i", "em":
  1549. crs.italic = true
  1550. case "u", "ins":
  1551. crs.underline = true
  1552. case "s", "strike", "del":
  1553. crs.strike = true
  1554. case "code", "tt", "kbd", "samp":
  1555. crs.font = "Consolas"
  1556. case "sup":
  1557. crs.vert = "superscript"
  1558. case "sub":
  1559. crs.vert = "subscript"
  1560. case "font":
  1561. if c := htmlutil.CSSColorHex(htmlutil.Attr(n, "color")); c != "" {
  1562. crs.color = c
  1563. }
  1564. if f := htmlutil.Attr(n, "face"); f != "" {
  1565. crs.font = fonts.FirstFamily(f)
  1566. }
  1567. case "a":
  1568. // the editor underlines and colours links unless the link says
  1569. // "inherit" (an imported link whose runs carry their own look)
  1570. css := cssDecls(htmlutil.Attr(n, "style"))
  1571. if css["color"] != "inherit" {
  1572. crs.color = "1A58C2"
  1573. }
  1574. if !strings.Contains(css["text-decoration"], "inherit") && css["text-decoration"] != "none" {
  1575. crs.underline = true
  1576. }
  1577. }
  1578. crs = crs.applyCSS(cssDecls(htmlutil.Attr(n, "style")))
  1579. if n.Data == "a" {
  1580. href := htmlutil.Attr(n, "href")
  1581. inner := &runBuf{}
  1582. for c := n.FirstChild; c != nil; c = c.NextSibling {
  1583. b.inline(c, crs, part, inner)
  1584. }
  1585. if !inner.any {
  1586. return
  1587. }
  1588. switch {
  1589. case strings.HasPrefix(href, "#") && len(href) > 1:
  1590. rb.sb.WriteString(`<w:hyperlink w:anchor="` + xmltree.Escape(href[1:]) + `">` + inner.sb.String() + `</w:hyperlink>`)
  1591. case href != "" && !strings.HasPrefix(strings.ToLower(strings.TrimSpace(href)), "javascript:"):
  1592. rid := part.add(relHyperlink, href, true)
  1593. rb.sb.WriteString(`<w:hyperlink r:id="` + rid + `">` + inner.sb.String() + `</w:hyperlink>`)
  1594. default:
  1595. rb.sb.WriteString(inner.sb.String())
  1596. }
  1597. rb.any = true
  1598. return
  1599. }
  1600. for c := n.FirstChild; c != nil; c = c.NextSibling {
  1601. if isBlockElement(c) {
  1602. continue // blocks inside inline content are not representable in a run
  1603. }
  1604. b.inline(c, crs, part, rb)
  1605. }
  1606. }
  1607. /* ---------------- pictures ---------------- */
  1608. var insetRe = regexp.MustCompile(`inset\(\s*([-\d.]+)%?\s*([-\d.]+)?%?\s*([-\d.]+)?%?\s*([-\d.]+)?%?\s*\)`)
  1609. func (b *docxBuilder) image(n *html.Node, part *docxPart) string {
  1610. // data-export-src: the PNG the editor rendered for a picture Word cannot
  1611. // take as it is (an SVG chart, a WebP); src stays the original
  1612. src := htmlutil.Attr(n, "data-export-src")
  1613. if src == "" {
  1614. src = htmlutil.Attr(n, "src")
  1615. }
  1616. data, ext, ok := media.ImageSrcBytes(src, b.readVpath)
  1617. if !ok {
  1618. return "" // a picture that cannot be read or embedded is skipped
  1619. }
  1620. // the same picture twice is one media part
  1621. sum := sha256.Sum256(data)
  1622. idx, seen := b.mediaByHash[sum]
  1623. if !seen {
  1624. b.imgCount++
  1625. idx = b.imgCount
  1626. b.mediaByHash[sum] = idx
  1627. b.media = append(b.media, media.Entry{Index: idx, Ext: ext, Data: data})
  1628. }
  1629. rid := part.add(relImage, fmt.Sprintf("media/image%d.%s", idx, ext), false)
  1630. css := cssDecls(htmlutil.Attr(n, "style"))
  1631. natW, natH := 0.0, 0.0
  1632. if cfg, _, err := image.DecodeConfig(bytes.NewReader(data)); err == nil {
  1633. natW, natH = float64(cfg.Width), float64(cfg.Height)
  1634. }
  1635. dim := func(name string) float64 {
  1636. if v, ok := css[name]; ok {
  1637. if pt, ok := cssPt(v, 11); ok && pt > 0 {
  1638. return pt
  1639. }
  1640. }
  1641. if a := htmlutil.Attr(n, name); a != "" {
  1642. if pt, ok := cssPt(a, 11); ok && pt > 0 {
  1643. return pt
  1644. }
  1645. }
  1646. return 0
  1647. }
  1648. wPt, hPt := dim("width"), dim("height")
  1649. fixedH := hPt > 0
  1650. switch {
  1651. case wPt > 0 && hPt <= 0:
  1652. if natW > 0 && natH > 0 {
  1653. hPt = wPt * natH / natW
  1654. } else {
  1655. hPt = wPt * 3 / 4
  1656. }
  1657. case hPt > 0 && wPt <= 0:
  1658. if natW > 0 && natH > 0 {
  1659. wPt = hPt * natW / natH
  1660. } else {
  1661. wPt = hPt * 4 / 3
  1662. }
  1663. case wPt <= 0 && hPt <= 0:
  1664. if natW > 0 && natH > 0 {
  1665. wPt, hPt = natW*0.75, natH*0.75
  1666. } else {
  1667. wPt, hPt = 300, 225
  1668. }
  1669. }
  1670. anchor := hasClass(n, "doc-anchor")
  1671. // an inline picture cannot be wider than the text column (the editor's
  1672. // max-width: 100%) - a stated height stays as the editor shows it, an
  1673. // automatic one scales along; an anchored picture may bleed past
  1674. if !anchor && b.textWPt > 0 && wPt > b.textWPt+0.5 {
  1675. if !fixedH {
  1676. hPt = hPt * b.textWPt / wPt
  1677. }
  1678. wPt = b.textWPt
  1679. }
  1680. cx, cy := int64(math.Round(wPt*12700)), int64(math.Round(hPt*12700))
  1681. crop := ""
  1682. if m := insetRe.FindStringSubmatch(css["object-view-box"]); m != nil {
  1683. vals := []string{m[1], m[2], m[3], m[4]}
  1684. fl := make([]float64, 4)
  1685. for i, v := range vals {
  1686. if v == "" {
  1687. v = vals[0]
  1688. if i == 3 && m[2] != "" {
  1689. v = m[2]
  1690. }
  1691. }
  1692. fl[i], _ = strconv.ParseFloat(v, 64)
  1693. }
  1694. crop = fmt.Sprintf(`<a:srcRect t="%d" r="%d" b="%d" l="%d"/>`,
  1695. int(math.Round(fl[0]*1000)), int(math.Round(fl[1]*1000)), int(math.Round(fl[2]*1000)), int(math.Round(fl[3]*1000)))
  1696. }
  1697. line := `<a:ln><a:noFill/></a:ln>`
  1698. borderPt := 0.0
  1699. if v, ok := css["border"]; ok {
  1700. if bd, ok := cssBorder(v); ok && bd.val != "nil" {
  1701. borderPt = float64(bd.sz) / 8
  1702. line = fmt.Sprintf(`<a:ln w="%d"><a:solidFill><a:srgbClr val="%s"/></a:solidFill><a:prstDash val="solid"/></a:ln>`,
  1703. int64(borderPt*12700), bd.color)
  1704. }
  1705. }
  1706. // the outline and the sideways margin (Google Docs sets pictures 1.5pt
  1707. // apart) ride on the effect extent, which Word lays out around the frame
  1708. mlPt, _ := cssPt(css["margin-left"], 11)
  1709. mrPt, _ := cssPt(css["margin-right"], 11)
  1710. if anchor {
  1711. mlPt, mrPt = 0, 0
  1712. }
  1713. eff := fmt.Sprintf(`<wp:effectExtent l="%d" t="%d" r="%d" b="%d"/>`,
  1714. int64((borderPt+mlPt)*12700), int64(borderPt*12700), int64((borderPt+mrPt)*12700), int64(borderPt*12700))
  1715. b.docPrID++
  1716. alt := xmltree.Escape(htmlutil.Attr(n, "alt"))
  1717. graphic := fmt.Sprintf(`<wp:docPr id="%d" name="Picture %d" descr="%s"/>`+
  1718. `<wp:cNvGraphicFramePr><a:graphicFrameLocks noChangeAspect="1"/></wp:cNvGraphicFramePr>`+
  1719. `<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">`+
  1720. `<pic:pic><pic:nvPicPr><pic:cNvPr id="%d" name="Picture %d"/><pic:cNvPicPr/></pic:nvPicPr>`+
  1721. `<pic:blipFill><a:blip r:embed="%s"/>%s<a:stretch><a:fillRect/></a:stretch></pic:blipFill>`+
  1722. `<pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="%d" cy="%d"/></a:xfrm>`+
  1723. `<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>%s</pic:spPr></pic:pic>`+
  1724. `</a:graphicData></a:graphic>`,
  1725. b.docPrID, b.docPrID, alt, b.docPrID, b.docPrID, rid, crop, cx, cy, line)
  1726. if anchor {
  1727. xPt, _ := cssPt(css["margin-left"], 11)
  1728. yPt, _ := cssPt(css["margin-top"], 11)
  1729. wrap := `<wp:wrapTopAndBottom/>`
  1730. posH := fmt.Sprintf(`<wp:positionH relativeFrom="column"><wp:posOffset>%d</wp:posOffset></wp:positionH>`, int64(math.Round(xPt*12700)))
  1731. if fl := css["float"]; fl == "left" || fl == "right" {
  1732. wrap = `<wp:wrapSquare wrapText="bothSides"/>`
  1733. if fl == "right" {
  1734. posH = `<wp:positionH relativeFrom="column"><wp:align>right</wp:align></wp:positionH>`
  1735. }
  1736. }
  1737. 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">`+
  1738. `<wp:simplePos x="0" y="0"/>%s<wp:positionV relativeFrom="paragraph"><wp:posOffset>%d</wp:posOffset></wp:positionV>`+
  1739. `<wp:extent cx="%d" cy="%d"/>%s%s%s</wp:anchor></w:drawing></w:r>`,
  1740. b.docPrID, posH, int64(math.Round(yPt*12700)), cx, cy, eff, wrap, graphic)
  1741. }
  1742. 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>`,
  1743. cx, cy, eff, graphic)
  1744. }
  1745. /* ---------------- lists ---------------- */
  1746. // list writes an ol/ul (depth = nesting level, leftPt = the indent its
  1747. // parent list's text starts at)
  1748. func (b *docxBuilder) list(l *html.Node, part *docxPart, rs wRunStyle, sb *strings.Builder, depth int, leftPt float64, key string) {
  1749. if depth > 8 {
  1750. depth = 8
  1751. }
  1752. css := cssDecls(htmlutil.Attr(l, "style"))
  1753. pad := 36.0
  1754. if v, ok := css["padding-left"]; ok {
  1755. if pt, ok := cssPt(v, rs.sizePt); ok {
  1756. pad = pt
  1757. }
  1758. }
  1759. hang := 18.0
  1760. if v, ok := css["--doc-hang"]; ok {
  1761. if pt, ok := cssPt(v, rs.sizePt); ok {
  1762. hang = pt
  1763. }
  1764. }
  1765. left := leftPt + pad
  1766. lrs := rs.applyBlockCSS(css)
  1767. if depth == 0 {
  1768. key = htmlutil.Attr(l, "data-num")
  1769. if key != "" {
  1770. key = "num:" + key
  1771. }
  1772. }
  1773. inst := b.num.instance(key)
  1774. if depth == 0 && key == "" {
  1775. // a list without an id is its own list: key it by its instance
  1776. key = fmt.Sprintf("inst:%d", inst.id)
  1777. b.num.byKey[key] = inst
  1778. }
  1779. if !inst.levels[depth].set {
  1780. d := defaultNumLevel(l.Data == "ul", depth)
  1781. if f := htmlutil.Attr(l, "data-fmt"); f != "" {
  1782. d.fmt = f
  1783. if f == "bullet" && l.Data == "ol" {
  1784. d.text = defaultBullets[depth%3]
  1785. }
  1786. if f != "bullet" && l.Data == "ul" {
  1787. d.text = "%" + strconv.Itoa(depth+1) + "."
  1788. }
  1789. }
  1790. if t, ok := attrPresent(l, "data-lvltext"); ok {
  1791. d.text = t
  1792. }
  1793. if s, err := strconv.Atoi(htmlutil.Attr(l, "start")); err == nil {
  1794. d.start = s
  1795. }
  1796. if hasClass(l, "of-checklist") {
  1797. d.fmt, d.text = "bullet", "\u2610"
  1798. }
  1799. d.leftPt, d.hangPt = left, hang
  1800. inst.levels[depth] = d
  1801. }
  1802. for c := l.FirstChild; c != nil; c = c.NextSibling {
  1803. if c.Type != html.ElementNode {
  1804. continue
  1805. }
  1806. switch c.Data {
  1807. case "li":
  1808. b.listItem(c, part, lrs, sb, inst, depth, left, hang, key)
  1809. case "ul", "ol":
  1810. b.list(c, part, lrs, sb, depth+1, left, key)
  1811. default:
  1812. if isBlockElement(c) {
  1813. b.block(c, part, lrs, sb)
  1814. }
  1815. }
  1816. }
  1817. }
  1818. func attrPresent(n *html.Node, name string) (string, bool) {
  1819. for _, a := range n.Attr {
  1820. if a.Key == name {
  1821. return a.Val, true
  1822. }
  1823. }
  1824. return "", false
  1825. }
  1826. func (b *docxBuilder) listItem(li *html.Node, part *docxPart, rs wRunStyle, sb *strings.Builder, inst *numInstance, depth int, left, hang float64, key string) {
  1827. pp, prs := b.blockStyleOf(li, rs)
  1828. pp.numID, pp.ilvl = inst.id, depth
  1829. pp.leftPt, pp.firstPt, pp.hasInd = left, -hang, true
  1830. numbered := false
  1831. var pending *html.Node
  1832. flush := func(stop *html.Node) {
  1833. if pending == nil {
  1834. return
  1835. }
  1836. ip := pp
  1837. if numbered {
  1838. // a later paragraph of the same item: aligned, not numbered
  1839. ip.numID = 0
  1840. ip.firstPt = 0
  1841. }
  1842. b.paragraph(pending, stop, ip, prs, part, sb)
  1843. numbered = true
  1844. pending = nil
  1845. }
  1846. for c := li.FirstChild; c != nil; c = c.NextSibling {
  1847. if c.Type == html.ElementNode && (c.Data == "ul" || c.Data == "ol") {
  1848. flush(c)
  1849. if !numbered {
  1850. b.paragraph(nil, nil, pp, prs, part, sb)
  1851. numbered = true
  1852. }
  1853. b.list(c, part, prs, sb, depth+1, left, key)
  1854. continue
  1855. }
  1856. if isBlockElement(c) {
  1857. flush(c)
  1858. cpp, crs := b.blockStyleOf(c, prs)
  1859. if !numbered {
  1860. cpp.numID, cpp.ilvl = inst.id, depth
  1861. cpp.firstPt = -hang
  1862. numbered = true
  1863. }
  1864. cpp.leftPt, cpp.hasInd = left, true
  1865. b.paragraph(c.FirstChild, nil, cpp, crs, part, sb)
  1866. continue
  1867. }
  1868. if pending == nil && !(c.Type == html.TextNode && strings.TrimSpace(c.Data) == "" && c.NextSibling != nil) {
  1869. pending = c
  1870. }
  1871. }
  1872. flush(nil)
  1873. if !numbered {
  1874. b.paragraph(nil, nil, pp, prs, part, sb)
  1875. }
  1876. }
  1877. /* ---------------- tables ---------------- */
  1878. type tcell struct {
  1879. node *html.Node
  1880. col, span, rows int
  1881. }
  1882. func (b *docxBuilder) table(t *html.Node, part *docxPart, rs wRunStyle, sb *strings.Builder) {
  1883. css := cssDecls(htmlutil.Attr(t, "style"))
  1884. rs = rs.applyBlockCSS(css)
  1885. // rows (thead/tbody/tfoot flattened), skipping layout spacers
  1886. var rows []*html.Node
  1887. var collect func(n *html.Node)
  1888. collect = func(n *html.Node) {
  1889. for c := n.FirstChild; c != nil; c = c.NextSibling {
  1890. if c.Type != html.ElementNode {
  1891. continue
  1892. }
  1893. switch c.Data {
  1894. case "thead", "tbody", "tfoot":
  1895. collect(c)
  1896. case "tr":
  1897. if !hasClass(c, "doc-autobreak") {
  1898. rows = append(rows, c)
  1899. }
  1900. }
  1901. }
  1902. }
  1903. collect(t)
  1904. if len(rows) == 0 {
  1905. return
  1906. }
  1907. // lay the cells out on the grid (rowspans occupy the rows below)
  1908. occupied := map[[2]int]bool{}
  1909. grid := make([][]tcell, len(rows))
  1910. nCols := 0
  1911. for r, tr := range rows {
  1912. col := 0
  1913. for td := tr.FirstChild; td != nil; td = td.NextSibling {
  1914. if td.Type != html.ElementNode || (td.Data != "td" && td.Data != "th") {
  1915. continue
  1916. }
  1917. for occupied[[2]int{r, col}] {
  1918. col++
  1919. }
  1920. span, _ := strconv.Atoi(htmlutil.Attr(td, "colspan"))
  1921. if span < 1 {
  1922. span = 1
  1923. }
  1924. rspan, _ := strconv.Atoi(htmlutil.Attr(td, "rowspan"))
  1925. if rspan < 1 {
  1926. rspan = 1
  1927. }
  1928. if r+rspan > len(rows) {
  1929. rspan = len(rows) - r
  1930. }
  1931. grid[r] = append(grid[r], tcell{node: td, col: col, span: span, rows: rspan})
  1932. for rr := r; rr < r+rspan; rr++ {
  1933. for cc := col; cc < col+span; cc++ {
  1934. occupied[[2]int{rr, cc}] = true
  1935. }
  1936. }
  1937. col += span
  1938. }
  1939. for occupied[[2]int{r, col}] {
  1940. col++
  1941. }
  1942. if col > nCols {
  1943. nCols = col
  1944. }
  1945. }
  1946. if nCols == 0 {
  1947. nCols = 1
  1948. }
  1949. // widths: the table's own, then the colgroup's columns
  1950. tblW := b.textWPt
  1951. if v, ok := css["width"]; ok {
  1952. if strings.HasSuffix(v, "%") {
  1953. if p, err := strconv.ParseFloat(strings.TrimSuffix(v, "%"), 64); err == nil && p > 0 {
  1954. tblW = b.textWPt * math.Min(p, 100) / 100
  1955. }
  1956. } else if pt, ok := cssPt(v, rs.sizePt); ok && pt > 10 {
  1957. tblW = pt
  1958. }
  1959. }
  1960. colW := make([]float64, nCols)
  1961. got := 0
  1962. sum := 0.0
  1963. pctCols := false
  1964. for cg := t.FirstChild; cg != nil; cg = cg.NextSibling {
  1965. if cg.Type != html.ElementNode || cg.Data != "colgroup" {
  1966. continue
  1967. }
  1968. for col := cg.FirstChild; col != nil && got < nCols; col = col.NextSibling {
  1969. if col.Type != html.ElementNode || col.Data != "col" {
  1970. continue
  1971. }
  1972. w := htmlutil.StyleProp(htmlutil.Attr(col, "style"), "width")
  1973. if strings.HasSuffix(w, "%") {
  1974. if p, err := strconv.ParseFloat(strings.TrimSuffix(w, "%"), 64); err == nil {
  1975. colW[got] = p
  1976. pctCols = true
  1977. }
  1978. } else if pt, ok := cssPt(w, 11); ok {
  1979. colW[got] = pt
  1980. }
  1981. sum += colW[got]
  1982. got++
  1983. }
  1984. }
  1985. if got == nCols && sum > 0 {
  1986. if pctCols || math.Abs(sum-tblW) > 1 && css["width"] == "" {
  1987. if !pctCols {
  1988. tblW = sum
  1989. }
  1990. for i := range colW {
  1991. colW[i] = colW[i] * tblW / sum
  1992. }
  1993. } else if math.Abs(sum-tblW) > 1 {
  1994. for i := range colW {
  1995. colW[i] = colW[i] * tblW / sum
  1996. }
  1997. }
  1998. } else {
  1999. for i := range colW {
  2000. colW[i] = tblW / float64(nCols)
  2001. }
  2002. }
  2003. var tp strings.Builder
  2004. // a table made in the editor (not an imported one) is marked: it has
  2005. // docs.css's spacing above and below, which a Word table cannot carry
  2006. tblStyle := "TableGrid"
  2007. if htmlutil.Attr(t, "data-docx") == "" {
  2008. tblStyle = editorTableStyle
  2009. }
  2010. tp.WriteString(`<w:tbl><w:tblPr><w:tblStyle w:val="` + tblStyle + `"/>`)
  2011. tp.WriteString(fmt.Sprintf(`<w:tblW w:w="%d" w:type="dxa"/>`, twip(tblW)))
  2012. switch {
  2013. case css["margin-left"] == "auto" && css["margin-right"] == "auto":
  2014. tp.WriteString(`<w:jc w:val="center"/>`)
  2015. case css["margin-left"] == "auto":
  2016. tp.WriteString(`<w:jc w:val="right"/>`)
  2017. default:
  2018. pt, _ := cssPt(css["margin-left"], 11)
  2019. if pt += b.containerLeft; pt != 0 {
  2020. tp.WriteString(fmt.Sprintf(`<w:tblInd w:w="%d" w:type="dxa"/>`, twip(pt)))
  2021. }
  2022. }
  2023. 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>`)
  2024. tp.WriteString(`<w:tblLook w:val="0600"/></w:tblPr><w:tblGrid>`)
  2025. for _, w := range colW {
  2026. tp.WriteString(fmt.Sprintf(`<w:gridCol w:w="%d"/>`, twip(w)))
  2027. }
  2028. tp.WriteString(`</w:tblGrid>`)
  2029. sb.WriteString(tp.String())
  2030. // cells continuing a rowspan from above, per row and grid column
  2031. cont := map[[2]int]tcell{}
  2032. for r := range grid {
  2033. for _, c := range grid[r] {
  2034. for rr := r + 1; rr < r+c.rows; rr++ {
  2035. cont[[2]int{rr, c.col}] = c
  2036. }
  2037. }
  2038. }
  2039. for r, tr := range rows {
  2040. trCSS := cssDecls(htmlutil.Attr(tr, "style"))
  2041. sb.WriteString("<w:tr><w:trPr>")
  2042. if htmlutil.Attr(tr, "data-cant-split") == "1" {
  2043. sb.WriteString(`<w:cantSplit/>`)
  2044. }
  2045. if pt, ok := cssPt(trCSS["height"], 11); ok && pt > 0 {
  2046. rule := "atLeast"
  2047. if htmlutil.Attr(tr, "data-exact") == "1" {
  2048. rule = "exact"
  2049. }
  2050. sb.WriteString(fmt.Sprintf(`<w:trHeight w:val="%d" w:hRule="%s"/>`, twip(pt), rule))
  2051. }
  2052. if htmlutil.Attr(tr, "data-header-row") == "1" {
  2053. sb.WriteString(`<w:tblHeader/>`)
  2054. }
  2055. sb.WriteString("</w:trPr>")
  2056. cells := grid[r]
  2057. ci := 0
  2058. for col := 0; col < nCols; {
  2059. if c, ok := cont[[2]int{r, col}]; ok {
  2060. b.cell(c, part, rs, sb, colW, "continue")
  2061. col += c.span
  2062. continue
  2063. }
  2064. if ci < len(cells) && cells[ci].col == col {
  2065. c := cells[ci]
  2066. ci++
  2067. merge := ""
  2068. if c.rows > 1 {
  2069. merge = "restart"
  2070. }
  2071. b.cell(c, part, rs, sb, colW, merge)
  2072. col += c.span
  2073. continue
  2074. }
  2075. // a ragged row: pad with an empty cell so the grid stays whole
  2076. 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])))
  2077. col++
  2078. }
  2079. sb.WriteString("</w:tr>")
  2080. }
  2081. sb.WriteString("</w:tbl>")
  2082. }
  2083. func (b *docxBuilder) cell(c tcell, part *docxPart, rs wRunStyle, sb *strings.Builder, colW []float64, merge string) {
  2084. td := c.node
  2085. css := cssDecls(htmlutil.Attr(td, "style"))
  2086. w := 0.0
  2087. for i := c.col; i < c.col+c.span && i < len(colW); i++ {
  2088. w += colW[i]
  2089. }
  2090. var tp strings.Builder
  2091. tp.WriteString(fmt.Sprintf(`<w:tcPr><w:tcW w:w="%d" w:type="dxa"/>`, twip(w)))
  2092. if c.span > 1 {
  2093. tp.WriteString(fmt.Sprintf(`<w:gridSpan w:val="%d"/>`, c.span))
  2094. }
  2095. if merge == "restart" {
  2096. tp.WriteString(`<w:vMerge w:val="restart"/>`)
  2097. } else if merge == "continue" {
  2098. tp.WriteString(`<w:vMerge/>`)
  2099. }
  2100. // borders: the cell's own, else the editor's default grid
  2101. def := wBorder{val: "single", sz: 6, color: "B9BEC7"}
  2102. borders := map[string]wBorder{"top": def, "left": def, "bottom": def, "right": def}
  2103. for side, bd := range cssBorderSides(css) {
  2104. borders[side] = bd
  2105. }
  2106. tp.WriteString("<w:tcBorders>")
  2107. for _, side := range []string{"top", "left", "bottom", "right"} {
  2108. bd := borders[side]
  2109. if bd.val == "nil" {
  2110. tp.WriteString(`<w:` + side + ` w:val="nil"/>`)
  2111. } else {
  2112. 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))
  2113. }
  2114. }
  2115. tp.WriteString("</w:tcBorders>")
  2116. shade := htmlutil.CSSColorHex(css["background-color"])
  2117. if shade == "" && td.Data == "th" {
  2118. shade = "F1F3F4"
  2119. }
  2120. if shade != "" {
  2121. tp.WriteString(`<w:shd w:val="clear" w:color="auto" w:fill="` + shade + `"/>`)
  2122. }
  2123. pad := [4]float64{3, 6, 3, 6} // the editor's 4px 8px
  2124. if v, ok := css["padding"]; ok {
  2125. if s, ok := boxSides(v, 11); ok {
  2126. pad = s
  2127. }
  2128. }
  2129. for i, side := range []string{"top", "right", "bottom", "left"} {
  2130. if pt, ok := cssPt(css["padding-"+side], 11); ok {
  2131. pad[i] = pt
  2132. }
  2133. }
  2134. 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>`,
  2135. twip(pad[0]), twip(pad[3]), twip(pad[2]), twip(pad[1])))
  2136. switch css["vertical-align"] {
  2137. case "middle":
  2138. tp.WriteString(`<w:vAlign w:val="center"/>`)
  2139. case "bottom":
  2140. tp.WriteString(`<w:vAlign w:val="bottom"/>`)
  2141. default:
  2142. tp.WriteString(`<w:vAlign w:val="top"/>`)
  2143. }
  2144. tp.WriteString("</w:tcPr>")
  2145. sb.WriteString("<w:tc>" + tp.String())
  2146. if merge == "continue" {
  2147. sb.WriteString("<w:p/></w:tc>")
  2148. return
  2149. }
  2150. crs := rs.applyBlockCSS(css)
  2151. if td.Data == "th" {
  2152. crs.bold = true
  2153. if _, ok := css["text-align"]; !ok {
  2154. css["text-align"] = "center" // the browser's th default
  2155. }
  2156. }
  2157. var inner strings.Builder
  2158. if htmlutil.HasBlockChild(td) {
  2159. b.containerWithStyle(td, part, pProps{jc: jcOf(css)}, crs, &inner)
  2160. } else {
  2161. b.paragraph(td.FirstChild, nil, pProps{jc: jcOf(css)}, crs, part, &inner)
  2162. }
  2163. x := inner.String()
  2164. if !strings.Contains(x, "<w:p>") && !strings.Contains(x, "<w:p ") {
  2165. x += "<w:p/>"
  2166. }
  2167. // Word needs a cell to end in a paragraph (a nested table cannot be last)
  2168. if strings.HasSuffix(x, "</w:tbl>") {
  2169. x += "<w:p/>"
  2170. }
  2171. sb.WriteString(x + "</w:tc>")
  2172. }
  2173. func jcOf(css map[string]string) string {
  2174. switch css["text-align"] {
  2175. case "center":
  2176. return "center"
  2177. case "right":
  2178. return "right"
  2179. case "justify":
  2180. return "both"
  2181. }
  2182. return ""
  2183. }
  2184. /* ---------------- section / styles / settings ---------------- */
  2185. // pgGeometry renders the pgSz + pgMar pair for a page config
  2186. func pgGeometry(pc *model.PageConf) string {
  2187. size := "A4"
  2188. orient := "portrait"
  2189. mT, mR, mB, mL := 25.4, 25.4, 25.4, 25.4
  2190. hd, fd := 12.7, 12.7
  2191. if pc != nil {
  2192. if _, ok := pageSizesTwips[pc.Size]; ok {
  2193. size = pc.Size
  2194. }
  2195. if pc.Orientation == "landscape" {
  2196. orient = "landscape"
  2197. }
  2198. if pc.Margins != nil {
  2199. mT, mR, mB, mL = pc.Margins.Top, pc.Margins.Right, pc.Margins.Bottom, pc.Margins.Left
  2200. }
  2201. if pc.HeaderDist != nil {
  2202. hd = *pc.HeaderDist
  2203. }
  2204. if pc.FooterDist != nil {
  2205. fd = *pc.FooterDist
  2206. }
  2207. }
  2208. dim := pageSizesTwips[size]
  2209. w, h := dim[0], dim[1]
  2210. orientAttr := ""
  2211. if orient == "landscape" {
  2212. w, h = h, w
  2213. orientAttr = ` w:orient="landscape"`
  2214. }
  2215. return fmt.Sprintf(`<w:pgSz w:w="%d" w:h="%d"%s/>`+
  2216. `<w:pgMar w:top="%d" w:right="%d" w:bottom="%d" w:left="%d" w:header="%d" w:footer="%d" w:gutter="0"/>`,
  2217. w, h, orientAttr,
  2218. mmToTwips(mT), mmToTwips(mR), mmToTwips(mB), mmToTwips(mL), mmToTwips(hd), mmToTwips(fd))
  2219. }
  2220. func buildSectPr(pc *model.PageConf, headerRef, footerRef string, continuous, titlePg bool) string {
  2221. typ := ""
  2222. if continuous {
  2223. // the columned body continues on the same page as the spanning
  2224. // title section it follows
  2225. typ = `<w:type w:val="continuous"/>`
  2226. }
  2227. cols := ""
  2228. if pc != nil && pc.Columns > 1 {
  2229. gap := pc.ColGap
  2230. if gap <= 0 {
  2231. gap = 8
  2232. }
  2233. cols = fmt.Sprintf(`<w:cols w:num="%d" w:space="%d"/>`, pc.Columns, mmToTwips(gap))
  2234. }
  2235. first := ""
  2236. if titlePg {
  2237. // "different first page" with no first-page reference: Word leaves
  2238. // page 1's header and footer empty
  2239. first = `<w:titlePg/>`
  2240. }
  2241. return `<w:sectPr>` + headerRef + footerRef + typ + pgGeometry(pc) + cols +
  2242. first + `</w:sectPr>`
  2243. }
  2244. // docxStylesXML pins the editor's typography - Word substitutes its own
  2245. // Normal defaults (Calibri, 8pt after) for anything left unstated, and that
  2246. // substitution is exactly what makes a document's pages break somewhere
  2247. // else than in the editor. Spacing units: half-points for sz, twentieths of
  2248. // a point for spacing, 240ths of a line for w:line.
  2249. func docxStylesXML(doc *model.Document) string {
  2250. ls := 1.15
  2251. if doc != nil && doc.LineSpacing > 0 {
  2252. ls = doc.LineSpacing
  2253. }
  2254. line := int(math.Round(ls * 240))
  2255. var sb strings.Builder
  2256. sb.WriteString(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` + "\n")
  2257. sb.WriteString(`<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">`)
  2258. 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>`)
  2259. 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))
  2260. sb.WriteString(`<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/><w:qFormat/></w:style>`)
  2261. 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>`)
  2262. sb.WriteString(`<w:style w:type="table" w:styleId="TableGrid"><w:name w:val="Table Grid"/><w:basedOn w:val="TableNormal"/></w:style>`)
  2263. 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>`)
  2264. names := []struct{ key, name string }{
  2265. {"h1", "heading 1"}, {"h2", "heading 2"}, {"h3", "heading 3"},
  2266. {"h4", "heading 4"}, {"h5", "heading 5"}, {"h6", "heading 6"},
  2267. {"doc-title", "Title"}, {"doc-subtitle", "Subtitle"},
  2268. }
  2269. for _, n := range names {
  2270. d := editorBlockDefaults[n.key]
  2271. 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))
  2272. if d.bold {
  2273. rpr = `<w:b/><w:bCs/>` + rpr
  2274. }
  2275. if d.italic {
  2276. rpr = `<w:i/><w:iCs/>` + rpr
  2277. }
  2278. keep := ""
  2279. if strings.HasPrefix(n.key, "h") {
  2280. keep = `<w:keepNext/><w:keepLines/>`
  2281. }
  2282. 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/>`+
  2283. `<w:pPr>%s<w:spacing w:before="%d" w:after="%d"/></w:pPr><w:rPr>%s</w:rPr></w:style>`,
  2284. d.style, n.name, keep, twip(d.beforePt), twip(d.afterPt), rpr))
  2285. }
  2286. sb.WriteString(`<w:style w:type="paragraph" w:customStyle="1" w:styleId="` + autoRuleStyle + `"><w:name w:val="Horizontal Rule"/></w:style>`)
  2287. 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>`)
  2288. 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>`)
  2289. 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>`)
  2290. sb.WriteString(`</w:styles>`)
  2291. return sb.String()
  2292. }
  2293. const docxSettings = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  2294. <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>`