docx_reader.go 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123
  1. package office
  2. /*
  3. docx_reader.go - Parse a Word (.docx) file into a Document.
  4. The goal is that an imported document LOOKS like it did where it came
  5. from (Word, Google Docs), so formatting is resolved the way Word
  6. resolves it - docDefaults, style chains, numbering definitions, table
  7. styles - and written out as explicit inline CSS on the editor HTML
  8. (see docx_props.go for the inheritance and docs_layout.js for the half
  9. of the layout that can only be computed in the browser).
  10. The HTML vocabulary this produces is the Docs "rich model", also what
  11. the docx writer consumes:
  12. blocks p / h1-h6 (.doc-title, .doc-subtitle) with
  13. style: margin-bottom (spacing after), margin-top on headings
  14. and padding-top elsewhere (spacing before: Google
  15. Docs collapses a heading's with the spacing above it
  16. the way CSS margins collapse, and adds a body
  17. paragraph's), margin-left/-right (indents),
  18. text-indent, text-align, font-*, color,
  19. background-color, white-space:pre-wrap when the text
  20. relies on repeated spaces
  21. data-ls="1.15" auto line spacing (multiple of single)
  22. data-lsexact="15pt" exact line height
  23. data-lsmin="15pt" at-least line height
  24. data-keep-next / data-keep-lines / data-widow = "1"
  25. data-page-break-before="1"
  26. data-tabs="right:451.28:dot;left:36:none" (pt from the
  27. text column's left edge)
  28. lists ol / ul .doc-list with data-fmt, data-lvltext, start,
  29. style padding-left + --doc-hang; nested lists sit directly
  30. inside their parent list (what execCommand("indent") makes)
  31. runs span style=font-*, color, background-color, text-decoration,
  32. font-variant, text-transform; sup / sub; a (links, with
  33. color/decoration inherited so the runs decide),
  34. span.doc-tab (a real tab character), br,
  35. sup.doc-fnref[data-fn] (footnote reference),
  36. span.doc-field[data-field=PAGE|NUMPAGES]
  37. images img style=width/height in pt, object-view-box for a crop,
  38. border for a picture outline; img.doc-anchor (display:block,
  39. margin offsets) for anchored top-and-bottom pictures
  40. tables table.of-table style=width/margin-left, colgroup of pt
  41. widths, td/th with explicit border-*, padding,
  42. vertical-align, background-color, colspan/rowspan
  43. breaks div.doc-pagebreak
  44. Headers/footers come back as HTML (headerHtml/footerHtml) plus plain
  45. text for older consumers, footnotes as body.footnotes. Legacy binary
  46. .doc is rejected.
  47. */
  48. import (
  49. "archive/zip"
  50. "bytes"
  51. "errors"
  52. "fmt"
  53. "io"
  54. "path"
  55. "regexp"
  56. "sort"
  57. "strconv"
  58. "strings"
  59. )
  60. // ParseDocx converts raw .docx bytes into a Document
  61. func ParseDocx(data []byte) (*Document, error) {
  62. if len(data) > 8 && data[0] == 0xD0 && data[1] == 0xCF {
  63. return nil, errors.New("legacy binary .doc files are not supported - save the file as .docx first")
  64. }
  65. zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
  66. if err != nil {
  67. return nil, errors.New("not a valid docx (zip) file")
  68. }
  69. files := map[string][]byte{}
  70. for _, f := range zr.File {
  71. name := path.Clean(f.Name)
  72. if strings.HasSuffix(name, ".xml") || strings.HasSuffix(name, ".rels") ||
  73. strings.HasPrefix(name, "word/media/") || strings.HasPrefix(name, "media/") {
  74. rc, err := f.Open()
  75. if err != nil {
  76. continue
  77. }
  78. b, err := io.ReadAll(rc)
  79. rc.Close()
  80. if err != nil {
  81. continue
  82. }
  83. files[name] = b
  84. }
  85. }
  86. docXML, ok := files["word/document.xml"]
  87. if !ok {
  88. return nil, errors.New("docx is missing word/document.xml")
  89. }
  90. tree, err := parseXMLTree(docXML)
  91. if err != nil {
  92. return nil, errors.New("cannot parse document.xml: " + err.Error())
  93. }
  94. body := tree.first("body")
  95. if body == nil {
  96. return nil, errors.New("document has no body")
  97. }
  98. cv := &docxConv{
  99. files: files,
  100. ss: parseStyleSheet(files["word/styles.xml"]),
  101. nb: parseNumbering(files["word/numbering.xml"]),
  102. bodyNode: body,
  103. fnNumber: map[string]int{},
  104. rv: docxReview{used: map[string]bool{}},
  105. }
  106. docPart := cv.part("word/document.xml")
  107. // Google Docs writes every rsid as zeros and numbers paragraphs from 1
  108. cv.gdocs = bytes.Contains(docXML, []byte(`w:rsidR="00000000"`)) &&
  109. bytes.Contains(docXML, []byte(`w14:paraId="00000001"`))
  110. doc := &Document{}
  111. // the document-wide line spacing every paragraph inherits unless it
  112. // says otherwise (Google Docs: 1.15, Word: 1.08 or single)
  113. cv.defaultLS = 1
  114. if dp, _ := cv.ss.paraStyle(""); dp != nil && dp.line.set && (dp.lineRule == "" || dp.lineRule == "auto") && dp.line.v > 0 {
  115. cv.defaultLS = round3(dp.line.v / 240)
  116. }
  117. doc.LineSpacing = cv.defaultLS
  118. // page geometry (parsed first: margins place anchored pictures and
  119. // multi-column layouts change the HTML conversion)
  120. sect := body.first("sectPr")
  121. if sect != nil {
  122. doc.Page = parseSectPage(sect)
  123. cv.marginL = twipsAttr(sect.first("pgMar"), "left", 1440) / 20
  124. cv.textW = (twipsAttr(sect.first("pgSz"), "w", 11906) -
  125. twipsAttr(sect.first("pgMar"), "left", 1440) -
  126. twipsAttr(sect.first("pgMar"), "right", 1440)) / 20
  127. if sect.first("titlePg") != nil && onOff(sect.first("titlePg")).v {
  128. doc.HFMode = HFModeExceptFirst
  129. }
  130. } else {
  131. cv.marginL, cv.textW = 72, 451.3
  132. }
  133. // Word writes IEEE-style spanning titles as leading single-column
  134. // sections; map those blocks back to .col-span-all
  135. if doc.Page != nil && doc.Page.Columns > 1 {
  136. cv.markSpanSections(body)
  137. }
  138. cv.collectSectionBreaks(body)
  139. doc.HTML = cv.blocks(body, docPart, blockCtx{top: true})
  140. // footnotes, in the order the text references them
  141. if len(cv.fnOrder) > 0 {
  142. if raw, ok := files["word/footnotes.xml"]; ok {
  143. if ft, err := parseXMLTree(raw); err == nil {
  144. fnPart := cv.part("word/footnotes.xml")
  145. byID := map[string]*xnode{}
  146. for _, fn := range ft.all("footnote") {
  147. byID[fn.attr("id")] = fn
  148. }
  149. for _, id := range cv.fnOrder {
  150. fn := byID[id]
  151. if fn == nil {
  152. continue
  153. }
  154. doc.Footnotes = append(doc.Footnotes, Footnote{
  155. ID: id,
  156. HTML: cv.blocks(fn, fnPart, blockCtx{footnote: true}),
  157. })
  158. }
  159. }
  160. }
  161. }
  162. // header / footer: the section's default parts, plus "different first
  163. // page" when it is on
  164. if sect != nil {
  165. hdr := cv.hfPart(sect, "headerReference", "default")
  166. ftr := cv.hfPart(sect, "footerReference", "default")
  167. if hdr != "" {
  168. doc.HeaderHTML, doc.Header = cv.hfHTML(hdr)
  169. }
  170. if ftr != "" {
  171. doc.FooterHTML, doc.Footer = cv.hfHTML(ftr)
  172. doc.PageNumbers = doc.PageNumbers || strings.Contains(doc.FooterHTML, `data-field="PAGE"`)
  173. }
  174. doc.PageNumbers = doc.PageNumbers || cv.autoPageNumber
  175. if doc.HFMode == HFModeExceptFirst {
  176. // a first-page part with real content is a different header,
  177. // not a missing one; the editor only models "blank on page one"
  178. if fh := cv.hfPart(sect, "headerReference", "first"); fh != "" {
  179. if h, txt := cv.hfHTML(fh); txt != "" || strings.Contains(h, "<img") {
  180. doc.HFMode = ""
  181. }
  182. }
  183. }
  184. }
  185. // review: the comments the text anchors, and whether Word was tracking
  186. doc.Comments = parseDocxComments(files, cv.rv.used)
  187. if raw, ok := files["word/settings.xml"]; ok {
  188. if st, err := parseXMLTree(raw); err == nil {
  189. if tr := st.first("trackRevisions"); tr != nil && onOff(tr).v {
  190. doc.TrackChanges = true
  191. }
  192. }
  193. }
  194. return doc, nil
  195. }
  196. func round1(v float64) float64 {
  197. return float64(int(v*10+0.5)) / 10
  198. }
  199. func round3(v float64) float64 {
  200. if v < 0 {
  201. return -round3(-v)
  202. }
  203. return float64(int(v*1000+0.5)) / 1000
  204. }
  205. func abs(v int) int {
  206. if v < 0 {
  207. return -v
  208. }
  209. return v
  210. }
  211. func twipsAttr(n *xnode, name string, def float64) float64 {
  212. if v := numAttr(n, name); v.set {
  213. return v.v
  214. }
  215. return def
  216. }
  217. // parseSectPage reads page size, orientation, margins, header/footer
  218. // distances and columns from a sectPr
  219. func parseSectPage(sect *xnode) *PageConf {
  220. pc := &PageConf{Size: "A4", Orientation: "portrait"}
  221. if sz := sect.first("pgSz"); sz != nil {
  222. w := int(twipsAttr(sz, "w", 11906))
  223. h := int(twipsAttr(sz, "h", 16838))
  224. if sz.attr("orient") == "landscape" || w > h {
  225. pc.Orientation = "landscape"
  226. w, h = h, w
  227. }
  228. best := "A4"
  229. bestD := 1 << 30
  230. for name, dim := range pageSizesTwips {
  231. d := abs(dim[0]-w) + abs(dim[1]-h)
  232. if d < bestD {
  233. bestD = d
  234. best = name
  235. }
  236. }
  237. pc.Size = best
  238. }
  239. if mar := sect.first("pgMar"); mar != nil {
  240. pc.Margins = &MarginsMM{
  241. Top: round1(twipsToMmF(twipsAttr(mar, "top", 1440))),
  242. Right: round1(twipsToMmF(twipsAttr(mar, "right", 1440))),
  243. Bottom: round1(twipsToMmF(twipsAttr(mar, "bottom", 1440))),
  244. Left: round1(twipsToMmF(twipsAttr(mar, "left", 1440))),
  245. }
  246. // Word's top/bottom margin may be negative ("do not move the text
  247. // for the header") - the editor has no such notion
  248. if pc.Margins.Top < 0 {
  249. pc.Margins.Top = -pc.Margins.Top
  250. }
  251. if pc.Margins.Bottom < 0 {
  252. pc.Margins.Bottom = -pc.Margins.Bottom
  253. }
  254. if v := numAttr(mar, "header"); v.set {
  255. d := round1(twipsToMmF(v.v))
  256. pc.HeaderDist = &d
  257. }
  258. if v := numAttr(mar, "footer"); v.set {
  259. d := round1(twipsToMmF(v.v))
  260. pc.FooterDist = &d
  261. }
  262. }
  263. if cols := sect.first("cols"); cols != nil {
  264. if n, err := strconv.Atoi(cols.attr("num")); err == nil && n > 1 {
  265. pc.Columns = n
  266. if sp := numAttr(cols, "space"); sp.set && sp.v > 0 {
  267. pc.ColGap = round1(twipsToMmF(sp.v))
  268. }
  269. }
  270. }
  271. return pc
  272. }
  273. func twipsToMmF(tw float64) float64 { return tw * 25.4 / 1440.0 }
  274. /* ---------------- conversion state ---------------- */
  275. type docxPartCtx struct {
  276. name string
  277. rels map[string]string
  278. ext map[string]bool // rId -> TargetMode External
  279. }
  280. type blockCtx struct {
  281. top bool // direct children of w:body
  282. cell bool
  283. hf bool
  284. footnote bool
  285. }
  286. type fieldFrame struct {
  287. instr string
  288. inResult bool
  289. }
  290. type docxConv struct {
  291. files map[string][]byte
  292. ss *docxStyleSheet
  293. nb *docxNumDefs
  294. bodyNode *xnode
  295. spanIdx map[int]bool // top-level block indexes that span all columns
  296. skipIdx map[int]bool // empty section-divider paragraphs to drop
  297. breakIdx map[int]bool // paragraphs ending a section that starts a new page
  298. defaultLS float64
  299. marginL float64 // pt
  300. textW float64 // pt
  301. fields []fieldFrame
  302. fnNumber map[string]int
  303. fnOrder []string
  304. parts map[string]*docxPartCtx
  305. // Google Docs exports: a handful of its layout habits are imitated so
  306. // the import matches its own PDF (see the gdocs uses)
  307. gdocs bool
  308. // spacing-before the next paragraph gives back (see paragraph)
  309. reduceBefore float64
  310. // a footer carried the page number our export adds (see hfHTML)
  311. autoPageNumber bool
  312. // review state: open comment ranges and the revision mark being walked
  313. // (docx_review.go)
  314. rv docxReview
  315. curRev string // "" | "ins" | "del"
  316. }
  317. // editorTableStyle marks a table BuildDocx wrote from an editor-made one
  318. const editorTableStyle = "ArozEditorTable"
  319. // autoRuleStyle marks the paragraph BuildDocx writes an <hr> as
  320. const autoRuleStyle = "ArozHorizontalRule"
  321. // isAutoRule reports a horizontal rule written by BuildDocx: its style and
  322. // no text
  323. func isAutoRule(p *xnode) bool {
  324. pPr := p.first("pPr")
  325. if pPr == nil {
  326. return false
  327. }
  328. ps := pPr.first("pStyle")
  329. if ps == nil || ps.attr("val") != autoRuleStyle {
  330. return false
  331. }
  332. var texts []string
  333. collectText(p, &texts)
  334. return strings.TrimSpace(strings.Join(texts, "")) == ""
  335. }
  336. // autoPageNumberStyle marks the page-number paragraph BuildDocx adds to a
  337. // footer, so an import turns it back into Document.PageNumbers
  338. const autoPageNumberStyle = "ArozPageNumber"
  339. // part loads the relationships of one XML part
  340. func (cv *docxConv) part(name string) *docxPartCtx {
  341. if cv.parts == nil {
  342. cv.parts = map[string]*docxPartCtx{}
  343. }
  344. if p, ok := cv.parts[name]; ok {
  345. return p
  346. }
  347. dir, file := path.Split(name)
  348. relsName := dir + "_rels/" + file + ".rels"
  349. p := &docxPartCtx{name: name, rels: map[string]string{}, ext: map[string]bool{}}
  350. if raw, ok := cv.files[relsName]; ok {
  351. if tree, err := parseXMLTree(raw); err == nil {
  352. for _, r := range tree.all("Relationship") {
  353. p.rels[r.attr("Id")] = r.attr("Target")
  354. if strings.EqualFold(r.attr("TargetMode"), "External") {
  355. p.ext[r.attr("Id")] = true
  356. }
  357. }
  358. }
  359. }
  360. cv.parts[name] = p
  361. return p
  362. }
  363. // hfPart finds the part path a header/footer reference points at
  364. func (cv *docxConv) hfPart(sect *xnode, kind, typ string) string {
  365. docPart := cv.part("word/document.xml")
  366. for _, ref := range sect.all(kind) {
  367. t := ref.attr("type")
  368. if t == "" {
  369. t = "default"
  370. }
  371. if t != typ {
  372. continue
  373. }
  374. target := docPart.rels[ref.attrNS("relationships", "id")]
  375. if target == "" {
  376. continue
  377. }
  378. return resolvePartPath("word", target)
  379. }
  380. return ""
  381. }
  382. // hfHTML converts a header/footer part; returns its HTML and plain text
  383. func (cv *docxConv) hfHTML(partName string) (string, string) {
  384. raw, ok := cv.files[partName]
  385. if !ok {
  386. return "", ""
  387. }
  388. tree, err := parseXMLTree(raw)
  389. if err != nil {
  390. return "", ""
  391. }
  392. // the page number our own export adds is the editor's page-number
  393. // switch, not footer content
  394. kept := tree.Nodes[:0]
  395. for _, c := range tree.Nodes {
  396. if c.XMLName.Local == "p" {
  397. if pPr := c.first("pPr"); pPr != nil {
  398. if ps := pPr.first("pStyle"); ps != nil && ps.attr("val") == autoPageNumberStyle {
  399. cv.autoPageNumber = true
  400. continue
  401. }
  402. }
  403. }
  404. kept = append(kept, c)
  405. }
  406. tree.Nodes = kept
  407. saved := cv.fields
  408. cv.fields = nil
  409. htmlOut := cv.blocks(tree, cv.part(partName), blockCtx{hf: true})
  410. cv.fields = saved
  411. var texts []string
  412. collectText(tree, &texts)
  413. txt := strings.TrimSpace(strings.Join(texts, ""))
  414. // a header that is only empty paragraphs is no header
  415. if txt == "" && !strings.Contains(htmlOut, "<img") {
  416. return "", ""
  417. }
  418. // the editor's plain header, as BuildDocx writes it, stays plain
  419. if m := plainHFRe.FindStringSubmatch(htmlOut); m != nil && !strings.Contains(m[1], "<") {
  420. return "", txt
  421. }
  422. return htmlOut, txt
  423. }
  424. var plainHFRe = regexp.MustCompile(`^<p><span style="font-size:9pt;color:#6b7078;">(.*)</span></p>$`)
  425. // markSpanSections finds paragraph-embedded sectPr elements (section
  426. // dividers). Blocks belonging to a single-column section of a multi-column
  427. // document are IEEE-style spanning blocks.
  428. func (cv *docxConv) markSpanSections(body *xnode) {
  429. cv.spanIdx = map[int]bool{}
  430. cv.skipIdx = map[int]bool{}
  431. var pending []int
  432. for i := range body.Nodes {
  433. n := &body.Nodes[i]
  434. local := n.XMLName.Local
  435. if local != "p" && local != "tbl" {
  436. continue
  437. }
  438. if local == "p" {
  439. if pPr := n.first("pPr"); pPr != nil {
  440. if sp := pPr.first("sectPr"); sp != nil {
  441. single := true
  442. if cols := sp.first("cols"); cols != nil {
  443. if num, err := strconv.Atoi(cols.attr("num")); err == nil && num > 1 {
  444. single = false
  445. }
  446. }
  447. if single {
  448. for _, j := range pending {
  449. cv.spanIdx[j] = true
  450. }
  451. cv.spanIdx[i] = true
  452. }
  453. if paragraphIsEmpty(n) {
  454. cv.skipIdx[i] = true // pure divider paragraph
  455. }
  456. pending = nil
  457. continue
  458. }
  459. }
  460. }
  461. pending = append(pending, i)
  462. }
  463. }
  464. // collectSectionBreaks marks the paragraphs that close a section whose
  465. // successor starts on a new page (single-column documents only - the
  466. // multi-column mapping above owns those)
  467. func (cv *docxConv) collectSectionBreaks(body *xnode) {
  468. if cv.spanIdx != nil {
  469. return
  470. }
  471. type sp struct {
  472. idx int
  473. typ string
  474. }
  475. var list []sp
  476. for i := range body.Nodes {
  477. n := &body.Nodes[i]
  478. if n.XMLName.Local == "p" {
  479. if s := n.path("pPr", "sectPr"); s != nil {
  480. list = append(list, sp{i, sectType(s)})
  481. }
  482. }
  483. }
  484. if len(list) == 0 {
  485. return
  486. }
  487. cv.breakIdx = map[int]bool{}
  488. for k, s := range list {
  489. nextType := "nextPage"
  490. if k+1 < len(list) {
  491. nextType = list[k+1].typ
  492. } else if bs := body.first("sectPr"); bs != nil {
  493. nextType = sectType(bs)
  494. }
  495. if nextType != "continuous" {
  496. cv.breakIdx[s.idx] = true
  497. }
  498. }
  499. }
  500. func sectType(s *xnode) string {
  501. if t := s.first("type"); t != nil && t.attr("val") != "" {
  502. return t.attr("val")
  503. }
  504. return "nextPage"
  505. }
  506. func paragraphIsEmpty(p *xnode) bool {
  507. var texts []string
  508. collectText(p, &texts)
  509. if strings.TrimSpace(strings.Join(texts, "")) != "" {
  510. return false
  511. }
  512. var d []*xnode
  513. p.findAll("drawing", &d)
  514. return len(d) == 0
  515. }
  516. /* ---------------- blocks ---------------- */
  517. type listFrame struct {
  518. tag string // ol | ul
  519. numID string
  520. ilvl int
  521. indL float64 // pt from the container's left edge
  522. }
  523. // blocks renders the block children of w:body, a table cell, a header,
  524. // footer or footnote
  525. func (cv *docxConv) blocks(parent *xnode, part *docxPartCtx, ctx blockCtx) string {
  526. var sb strings.Builder
  527. var lists []listFrame
  528. lastPara := -1 // where the last plain paragraph starts in sb
  529. closeLists := func(depth int) {
  530. for len(lists) > depth {
  531. sb.WriteString("</" + lists[len(lists)-1].tag + ">")
  532. lists = lists[:len(lists)-1]
  533. }
  534. }
  535. var walk func(children []xnode, top bool)
  536. walk = func(children []xnode, top bool) {
  537. for i := range children {
  538. n := &children[i]
  539. if top && ctx.top {
  540. if cv.skipIdx != nil && cv.skipIdx[i] {
  541. continue
  542. }
  543. }
  544. switch n.XMLName.Local {
  545. case "p":
  546. if isAutoRule(n) {
  547. closeLists(0)
  548. lastPara = -1
  549. sb.WriteString("<hr>")
  550. continue
  551. }
  552. spanAll := top && ctx.top && cv.spanIdx != nil && cv.spanIdx[i]
  553. item := cv.paragraph(n, part, ctx, spanAll)
  554. if item.list != nil {
  555. cv.placeListItem(&sb, &lists, item)
  556. } else {
  557. closeLists(0)
  558. lastPara = sb.Len()
  559. sb.WriteString(item.html)
  560. }
  561. if top && ctx.top && cv.breakIdx != nil && cv.breakIdx[i] {
  562. closeLists(0)
  563. sb.WriteString(pageBreakDiv)
  564. }
  565. case "tbl":
  566. closeLists(0)
  567. spanAll := top && ctx.top && cv.spanIdx != nil && cv.spanIdx[i]
  568. cv.reduceBefore = 0
  569. // Google Docs gives no spacing-after to an empty paragraph
  570. // right above a table
  571. if cv.gdocs && lastPara >= 0 && emptyBlockHTML(sb.String()[lastPara:]) {
  572. cur := sb.String()
  573. tail := dropMarginBottom(cur[lastPara:])
  574. if tail != cur[lastPara:] {
  575. sb.Reset()
  576. sb.WriteString(cur[:lastPara])
  577. sb.WriteString(tail)
  578. }
  579. }
  580. sb.WriteString(cv.table(n, part, spanAll))
  581. case "sdt":
  582. if c := n.first("sdtContent"); c != nil {
  583. walk(c.Nodes, false)
  584. }
  585. case "customXml", "ins", "moveTo", "smartTag":
  586. walk(n.Nodes, false)
  587. case "AlternateContent":
  588. if c := n.first("Choice"); c != nil {
  589. walk(c.Nodes, false)
  590. } else if f := n.first("Fallback"); f != nil {
  591. walk(f.Nodes, false)
  592. }
  593. }
  594. }
  595. }
  596. walk(parent.Nodes, true)
  597. closeLists(0)
  598. return sb.String()
  599. }
  600. var marginBottomRe = regexp.MustCompile(`margin-bottom:[^;"]*;`)
  601. var emptyBlockRe = regexp.MustCompile(`^<[a-z0-9]+[^>]*><br></[a-z0-9]+>$`)
  602. // emptyBlockHTML reports whether s is one block holding nothing but its
  603. // empty line
  604. func emptyBlockHTML(s string) bool {
  605. return emptyBlockRe.MatchString(s)
  606. }
  607. // dropMarginBottom removes the spacing-after from the opening tag of the
  608. // block HTML that starts s (only when s is a single block)
  609. func dropMarginBottom(s string) string {
  610. end := strings.Index(s, ">")
  611. if end < 0 {
  612. return s
  613. }
  614. return marginBottomRe.ReplaceAllString(s[:end], "margin-bottom:0pt;") + s[end:]
  615. }
  616. const pageBreakDiv = `<div class="doc-pagebreak" contenteditable="false"></div>`
  617. type paraOutput struct {
  618. html string // complete block HTML (non-list paragraphs)
  619. list *docxListItem
  620. liAttrs string
  621. liInner string
  622. }
  623. type docxListItem struct {
  624. numID string
  625. ilvl int
  626. fmt string
  627. text string
  628. start int
  629. value int
  630. indL float64 // pt
  631. hang float64 // pt
  632. ordered bool
  633. }
  634. // placeListItem opens/closes list elements around one list paragraph
  635. func (cv *docxConv) placeListItem(sb *strings.Builder, lists *[]listFrame, it paraOutput) {
  636. li := it.list
  637. // a different list instance closes the current one entirely
  638. if len(*lists) > 0 && (*lists)[0].numID != li.numID {
  639. for len(*lists) > 0 {
  640. sb.WriteString("</" + (*lists)[len(*lists)-1].tag + ">")
  641. *lists = (*lists)[:len(*lists)-1]
  642. }
  643. }
  644. for len(*lists) > 0 && (*lists)[len(*lists)-1].ilvl > li.ilvl {
  645. sb.WriteString("</" + (*lists)[len(*lists)-1].tag + ">")
  646. *lists = (*lists)[:len(*lists)-1]
  647. }
  648. tag := "ul"
  649. if li.ordered {
  650. tag = "ol"
  651. }
  652. if n := len(*lists); n > 0 && (*lists)[n-1].ilvl == li.ilvl && (*lists)[n-1].tag != tag {
  653. sb.WriteString("</" + (*lists)[n-1].tag + ">")
  654. *lists = (*lists)[:n-1]
  655. }
  656. if len(*lists) == 0 || (*lists)[len(*lists)-1].ilvl < li.ilvl {
  657. parentL := 0.0
  658. if len(*lists) > 0 {
  659. parentL = (*lists)[len(*lists)-1].indL
  660. }
  661. pad := li.indL - parentL
  662. attrs := ` class="doc-list" data-num="` + xmlEscape(li.numID) + `" data-fmt="` + li.fmt + `"`
  663. if li.text != "" {
  664. attrs += ` data-lvltext="` + xmlEscape(li.text) + `"`
  665. }
  666. if li.ordered && li.value != 1 {
  667. attrs += ` start="` + strconv.Itoa(li.value) + `"`
  668. }
  669. attrs += ` style="padding-left:` + ptStr(pad) + `;--doc-hang:` + ptStr(li.hang) + `;"`
  670. sb.WriteString("<" + tag + attrs + ">")
  671. *lists = append(*lists, listFrame{tag: tag, numID: li.numID, ilvl: li.ilvl, indL: li.indL})
  672. }
  673. sb.WriteString("<li" + it.liAttrs + ">" + it.liInner + "</li>")
  674. }
  675. // ptStr formats a length in points
  676. func ptStr(v float64) string {
  677. return trimFloat(round2(v)) + "pt"
  678. }
  679. /* ---------------- paragraphs ---------------- */
  680. // paragraph converts one w:p
  681. func (cv *docxConv) paragraph(p *xnode, part *docxPartCtx, ctx blockCtx, spanAll bool) paraOutput {
  682. direct := parsePPr(p.first("pPr"))
  683. styleP, styleR := cv.ss.paraStyle(direct.style)
  684. eff := *styleP
  685. eff.merge(direct)
  686. baseR := *styleR
  687. baseR.merge(direct.mark)
  688. if cv.reduceBefore > 0 && !ctx.cell {
  689. b := 0.0
  690. if eff.before.set {
  691. b = eff.before.v - cv.reduceBefore*20
  692. }
  693. if b < 0 {
  694. b = 0
  695. }
  696. eff.before = optNum{set: true, v: b}
  697. }
  698. cv.reduceBefore = 0
  699. level := cv.ss.headingLevel(direct.style)
  700. if direct.style == "" {
  701. level = cv.ss.headingLevel(cv.ss.defPara)
  702. }
  703. // list membership (numbering from the paragraph or its style)
  704. var li *docxListItem
  705. if eff.numSet && cv.nb.exists(eff.numID) && !ctx.hf {
  706. ilvl := 0
  707. if eff.ilvl.set {
  708. ilvl = int(eff.ilvl.v)
  709. }
  710. def := cv.nb.level(eff.numID, ilvl)
  711. li = &docxListItem{numID: eff.numID, ilvl: ilvl, fmt: "bullet", start: 1}
  712. if def != nil {
  713. li.fmt = htmlListFormat(def.fmt)
  714. li.text = def.text
  715. li.start = def.start
  716. // numbering indents sit between the style's and the paragraph's own
  717. ind := *styleP
  718. if def.indL.set {
  719. ind.indL = def.indL
  720. }
  721. if def.indHang.set || def.indFirst.set {
  722. ind.indHang, ind.indFirst = def.indHang, def.indFirst
  723. }
  724. ind.merge(direct)
  725. eff.indL, eff.indHang, eff.indFirst = ind.indL, ind.indHang, ind.indFirst
  726. }
  727. li.ordered = li.fmt != "bullet"
  728. li.value = cv.nb.next(eff.numID, ilvl)
  729. li.indL = eff.indL.v / 20
  730. if eff.indHang.set && eff.indHang.v > 0 {
  731. li.hang = eff.indHang.v / 20
  732. } else if eff.indFirst.set && eff.indFirst.v < 0 {
  733. li.hang = -eff.indFirst.v / 20
  734. } else {
  735. li.hang = 18
  736. }
  737. }
  738. // a run takes its look from the paragraph style and its own rPr; the
  739. // paragraph mark's rPr formats only the mark (the empty line's height,
  740. // a list number), so runs must not inherit it - but they are written
  741. // against the block, which does
  742. runs := cv.runs(p, part, *styleR, baseR)
  743. tag := "p"
  744. var classes []string
  745. switch {
  746. case level >= 1 && level <= 6 && li == nil:
  747. tag = "h" + strconv.Itoa(level)
  748. case level == -1 && li == nil:
  749. tag = "h1"
  750. classes = append(classes, "doc-title")
  751. case level == -2 && li == nil:
  752. classes = append(classes, "doc-subtitle")
  753. }
  754. if spanAll {
  755. classes = append(classes, "col-span-all")
  756. }
  757. style, data := cv.blockStyle(tag, eff, baseR, li != nil, level, runs.preWrap)
  758. attrs := ""
  759. if runs.bookmark != "" {
  760. attrs += ` id="` + xmlEscape(runs.bookmark) + `"`
  761. }
  762. if len(classes) > 0 {
  763. attrs += ` class="` + strings.Join(classes, " ") + `"`
  764. }
  765. if style != "" {
  766. attrs += ` style="` + style + `"`
  767. }
  768. attrs += data
  769. if li != nil {
  770. inner := strings.Join(runs.segments, "")
  771. if strings.TrimSpace(stripTags(inner)) == "" && !strings.Contains(inner, "<img") {
  772. inner += "<br>"
  773. }
  774. return paraOutput{list: li, liAttrs: attrs, liInner: inner}
  775. }
  776. var sb strings.Builder
  777. for i, seg := range runs.segments {
  778. if i > 0 {
  779. sb.WriteString(pageBreakDiv)
  780. }
  781. // an anchored picture sits above/below the text, so a paragraph
  782. // holding only that still has its own (empty) line
  783. flow := anchorImgRe.ReplaceAllString(seg, "")
  784. empty := strings.TrimSpace(stripTags(flow)) == "" && !strings.Contains(flow, "<img") &&
  785. !strings.Contains(flow, "doc-tab")
  786. anchorsOnly := empty && flow != seg
  787. if anchorsOnly {
  788. seg += "<br>"
  789. empty = false
  790. }
  791. if len(runs.segments) > 1 && empty {
  792. // the part of a paragraph before or after a page break that
  793. // holds nothing takes no line (how Google Docs lays it out)
  794. continue
  795. }
  796. if empty && !strings.Contains(seg, "<br>") {
  797. seg += "<br>"
  798. } else if strings.HasSuffix(seg, "<br>") && !anchorsOnly {
  799. // a trailing line break opens one more (empty) line
  800. seg += "<br>"
  801. }
  802. segAttrs := attrs
  803. if i > 0 {
  804. segAttrs = strings.Replace(segAttrs, ` id="`+xmlEscape(runs.bookmark)+`"`, "", 1)
  805. // the text after a page break carries on the paragraph that
  806. // began on the page before: its spacing-before was spent there
  807. noBefore := eff
  808. noBefore.before = optNum{set: true, v: 0}
  809. st2, _ := cv.blockStyle(tag, noBefore, baseR, false, level, runs.preWrap)
  810. if style != "" {
  811. segAttrs = strings.Replace(segAttrs, ` style="`+style+`"`, ` style="`+st2+`"`, 1)
  812. }
  813. }
  814. sb.WriteString("<" + tag + segAttrs + ">" + seg + "</" + tag + ">")
  815. }
  816. // A paragraph that ends in a page break leaves an empty remainder on
  817. // the next page that takes no line - but Google Docs still counts its
  818. // spacing-after against the spacing-before of what follows (a heading
  819. // after a page-break heading starts 4pt higher than one after a
  820. // page-break body paragraph)
  821. if n := len(runs.segments); n > 1 && !ctx.cell && eff.after.set {
  822. last := runs.segments[n-1]
  823. if strings.TrimSpace(stripTags(last)) == "" && !strings.Contains(last, "<img") {
  824. cv.reduceBefore = eff.after.v / 20
  825. }
  826. }
  827. return paraOutput{html: sb.String()}
  828. }
  829. // the editor's own defaults for body text (docs.css) - anything else is
  830. // stated inline
  831. const (
  832. editorBodyPt = 11.0
  833. editorBodyColor = "000000"
  834. )
  835. var editorFontStack = docxFontStack("Arial", "")
  836. var anchorImgRe = regexp.MustCompile(`<img[^>]*class="doc-anchor"[^>]*>`)
  837. // font names that stand for another face in practice: Google Docs writes
  838. // "Arial Unicode MS" for runs holding symbols and lays them out in Arial,
  839. // while a Windows machine that has the old Office font installed would draw
  840. // them 20% taller and wider
  841. var docxFontAlias = map[string]string{
  842. "arial unicode ms": "Arial",
  843. }
  844. // metric twins a word processor substitutes for a font it does not have
  845. var docxMetricFallback = map[string]string{
  846. "sans": "Arial", "serif": "'Times New Roman'", "mono": "'Courier New'",
  847. }
  848. // docxFontStack is fontStackFor with the substitution Google Docs and Word
  849. // make for a font they do not have: a metric-compatible core font right
  850. // behind it. Without that the browser falls through to the shipped Noto
  851. // faces, which are wider and taller, and every line wraps and stacks
  852. // differently from the source.
  853. func docxFontStack(latin, ea string) string {
  854. if alias, ok := docxFontAlias[strings.ToLower(latin)]; ok {
  855. latin = alias
  856. }
  857. if alias, ok := docxFontAlias[strings.ToLower(ea)]; ok {
  858. ea = alias
  859. }
  860. if ea == latin {
  861. ea = ""
  862. }
  863. stack := fontStackFor(latin, ea)
  864. l := strings.ToLower(latin)
  865. kind := "sans"
  866. switch {
  867. case strings.Contains(l, "courier"), strings.Contains(l, "mono"), strings.Contains(l, "consolas"):
  868. kind = "mono"
  869. case strings.Contains(l, "times"), strings.Contains(l, "georgia"), strings.Contains(l, "garamond"),
  870. strings.Contains(l, "cambria"), strings.Contains(l, "book antiqua"),
  871. strings.Contains(l, "serif") && !strings.Contains(l, "sans"):
  872. kind = "serif"
  873. }
  874. fb := docxMetricFallback[kind]
  875. if strings.EqualFold(strings.Trim(fb, "'"), latin) {
  876. return stack
  877. }
  878. first := quoteFontName(latin)
  879. if ea != "" && ea != latin {
  880. first += "," + quoteFontName(ea)
  881. }
  882. if strings.HasPrefix(stack, first+",") {
  883. return first + "," + fb + stack[len(first):]
  884. }
  885. return stack
  886. }
  887. // blockStyle renders a paragraph's layout properties as inline CSS plus
  888. // data attributes
  889. func (cv *docxConv) blockStyle(tag string, eff docxPPr, r docxRPr, isList bool, level int, preWrap bool) (string, string) {
  890. var css []string
  891. add := func(k, v string) { css = append(css, k+":"+v) }
  892. heading := tag != "p"
  893. // a paragraph border sits between the spacing and the text: the text
  894. // keeps its indent and the rule is drawn "space" points outside it
  895. edge := func(side string) (float64, bool) {
  896. b, ok := eff.borders[side]
  897. if !ok || !b.visible() {
  898. return 0, false
  899. }
  900. return borderWidthPt(b) + b.space, true
  901. }
  902. bordered := false
  903. for _, side := range []string{"top", "right", "bottom", "left"} {
  904. if _, ok := edge(side); ok {
  905. bordered = true
  906. }
  907. }
  908. before, after := 0.0, 0.0
  909. if eff.before.set {
  910. before = eff.before.v / 20
  911. }
  912. if eff.after.set {
  913. after = eff.after.v / 20
  914. }
  915. if before != 0 || heading {
  916. // Google Docs collapses a heading's spacing-before with the
  917. // spacing-after above it (the larger wins) but adds a body
  918. // paragraph's to it - margin collapses in CSS, padding does not
  919. if heading || bordered {
  920. // (a bordered paragraph's spacing is outside its rule)
  921. add("margin-top", ptStr(before))
  922. } else {
  923. add("padding-top", ptStr(before))
  924. }
  925. }
  926. if after != 0 || heading {
  927. add("margin-bottom", ptStr(after))
  928. }
  929. if !isList {
  930. left := 0.0
  931. if eff.indL.set {
  932. left = eff.indL.v / 20
  933. }
  934. if shift, ok := edge("left"); ok {
  935. left -= shift
  936. }
  937. if left != 0 {
  938. add("margin-left", ptStr(left))
  939. }
  940. first := 0.0
  941. if eff.indHang.set && eff.indHang.v != 0 {
  942. first = -eff.indHang.v / 20
  943. } else if eff.indFirst.set {
  944. first = eff.indFirst.v / 20
  945. }
  946. if first != 0 {
  947. add("text-indent", ptStr(first))
  948. }
  949. }
  950. right := 0.0
  951. if eff.indR.set {
  952. right = eff.indR.v / 20
  953. }
  954. if shift, ok := edge("right"); ok && !isList {
  955. right -= shift
  956. }
  957. if right != 0 {
  958. add("margin-right", ptStr(right))
  959. }
  960. switch eff.jc {
  961. case "center":
  962. add("text-align", "center")
  963. case "right", "end":
  964. add("text-align", "right")
  965. case "both", "distribute":
  966. add("text-align", "justify")
  967. }
  968. // run defaults of the block
  969. fc := rPrCSS(r)
  970. if fc["font-family"] != editorFontStack || heading {
  971. add("font-family", fc["font-family"])
  972. }
  973. if fc["font-size"] != ptStr(editorBodyPt) || heading {
  974. add("font-size", fc["font-size"])
  975. }
  976. if fc["font-weight"] != "400" || heading {
  977. add("font-weight", fc["font-weight"])
  978. }
  979. if fc["font-style"] != "normal" || heading {
  980. add("font-style", fc["font-style"])
  981. }
  982. if fc["color"] != "#"+strings.ToLower(editorBodyColor) || heading {
  983. add("color", fc["color"])
  984. }
  985. for _, k := range []string{"text-decoration", "font-variant", "text-transform", "background-color"} {
  986. if v := fc[k]; v != "" && v != "none" && v != "normal" {
  987. add(k, v)
  988. }
  989. }
  990. if eff.shd != "" && eff.shd != "auto" {
  991. add("background-color", "#"+strings.ToLower(eff.shd))
  992. }
  993. for _, side := range []string{"top", "right", "bottom", "left"} {
  994. b, ok := eff.borders[side]
  995. if !ok || !b.visible() {
  996. continue
  997. }
  998. add("border-"+side, borderCSS(b))
  999. if b.space > 0 {
  1000. add("padding-"+side, ptStr(b.space))
  1001. }
  1002. }
  1003. if preWrap {
  1004. add("white-space", "pre-wrap")
  1005. }
  1006. var data strings.Builder
  1007. switch {
  1008. case eff.line.set && eff.lineRule == "exact":
  1009. data.WriteString(` data-lsexact="` + ptStr(eff.line.v/20) + `"`)
  1010. case eff.line.set && eff.lineRule == "atLeast":
  1011. data.WriteString(` data-lsmin="` + ptStr(eff.line.v/20) + `"`)
  1012. case eff.line.set && eff.line.v > 0:
  1013. if ls := round3(eff.line.v / 240); ls != cv.defaultLS {
  1014. data.WriteString(` data-ls="` + trimFloat(ls) + `"`)
  1015. }
  1016. case cv.defaultLS != 1:
  1017. data.WriteString(` data-ls="1"`)
  1018. }
  1019. if eff.keepNext.v {
  1020. data.WriteString(` data-keep-next="1"`)
  1021. }
  1022. if eff.keepLines.v {
  1023. data.WriteString(` data-keep-lines="1"`)
  1024. }
  1025. // widow/orphan control is on unless a paragraph turns it off (Word's
  1026. // Normal style and Google Docs both keep two lines together)
  1027. if eff.widow.set && !eff.widow.v {
  1028. data.WriteString(` data-widow="0"`)
  1029. }
  1030. if eff.pageBreakBefore.v {
  1031. data.WriteString(` data-page-break-before="1"`)
  1032. }
  1033. if len(eff.tabs) > 0 {
  1034. tabs := append([]docxTab(nil), eff.tabs...)
  1035. sort.Slice(tabs, func(i, j int) bool { return tabs[i].pos < tabs[j].pos })
  1036. var parts []string
  1037. for _, t := range tabs {
  1038. if t.align == "clear" {
  1039. continue
  1040. }
  1041. align := t.align
  1042. switch align {
  1043. case "start", "":
  1044. align = "left"
  1045. case "end":
  1046. align = "right"
  1047. }
  1048. leader := t.leader
  1049. if leader == "" {
  1050. leader = "none"
  1051. }
  1052. parts = append(parts, align+":"+trimFloat(round2(t.pos/20))+":"+leader)
  1053. }
  1054. if len(parts) > 0 {
  1055. data.WriteString(` data-tabs="` + strings.Join(parts, ";") + `"`)
  1056. }
  1057. }
  1058. if len(css) == 0 {
  1059. return "", data.String()
  1060. }
  1061. return xmlEscape(strings.Join(css, ";") + ";"), data.String()
  1062. }
  1063. // borderWidthPt is the width a border is drawn at, in points
  1064. func borderWidthPt(b docxBorder) float64 {
  1065. w := b.sz / 8
  1066. if w <= 0 {
  1067. w = 0.5
  1068. }
  1069. if b.val == "double" && w < 2.25 {
  1070. w = 2.25
  1071. }
  1072. return w
  1073. }
  1074. func borderCSS(b docxBorder) string {
  1075. w := borderWidthPt(b)
  1076. style := "solid"
  1077. switch b.val {
  1078. case "dotted":
  1079. style = "dotted"
  1080. case "dashed", "dashSmallGap", "dotDash", "dotDotDash":
  1081. style = "dashed"
  1082. case "double":
  1083. style = "double"
  1084. }
  1085. col := b.color
  1086. if len(col) != 6 {
  1087. col = "000000"
  1088. }
  1089. return ptStr(w) + " " + style + " #" + strings.ToLower(col)
  1090. }
  1091. var highlightColors = map[string]string{
  1092. "yellow": "ffff00", "green": "00ff00", "cyan": "00ffff", "magenta": "ff00ff",
  1093. "blue": "0000ff", "red": "ff0000", "darkBlue": "000080", "darkCyan": "008080",
  1094. "darkGreen": "008000", "darkMagenta": "800080", "darkRed": "800000",
  1095. "darkYellow": "808000", "darkGray": "808080", "lightGray": "c0c0c0",
  1096. "black": "000000", "white": "ffffff",
  1097. }
  1098. // rPrCSS renders a fully resolved run's formatting as CSS values
  1099. func rPrCSS(r docxRPr) map[string]string {
  1100. out := map[string]string{}
  1101. font := r.fontASCII
  1102. if font == "" {
  1103. font = "Arial"
  1104. }
  1105. ea := r.fontEA
  1106. if ea == font {
  1107. ea = ""
  1108. }
  1109. out["font-family"] = docxFontStack(font, ea)
  1110. sz := 20.0 // Word's built-in default is 10pt
  1111. if r.sz.set && r.sz.v > 0 {
  1112. sz = r.sz.v
  1113. }
  1114. out["font-size"] = ptStr(sz / 2)
  1115. out["font-weight"] = "400"
  1116. if r.b.v {
  1117. out["font-weight"] = "700"
  1118. }
  1119. out["font-style"] = "normal"
  1120. if r.i.v {
  1121. out["font-style"] = "italic"
  1122. }
  1123. var deco []string
  1124. if r.u != "" && r.u != "none" {
  1125. deco = append(deco, "underline")
  1126. }
  1127. if r.strike.v || r.dstrike.v {
  1128. deco = append(deco, "line-through")
  1129. }
  1130. out["text-decoration"] = "none"
  1131. if len(deco) > 0 {
  1132. out["text-decoration"] = strings.Join(deco, " ")
  1133. }
  1134. col := r.color
  1135. if len(col) != 6 {
  1136. col = editorBodyColor
  1137. }
  1138. out["color"] = "#" + strings.ToLower(col)
  1139. if r.highlight != "" && r.highlight != "none" {
  1140. if h, ok := highlightColors[r.highlight]; ok {
  1141. out["background-color"] = "#" + h
  1142. }
  1143. } else if r.shd != "" && r.shd != "auto" {
  1144. out["background-color"] = "#" + strings.ToLower(r.shd)
  1145. }
  1146. if r.smallCaps.v {
  1147. out["font-variant"] = "small-caps"
  1148. }
  1149. if r.caps.v {
  1150. out["text-transform"] = "uppercase"
  1151. }
  1152. return out
  1153. }
  1154. var cssRunKeys = []string{"font-family", "font-size", "font-weight", "font-style",
  1155. "text-decoration", "color", "background-color", "font-variant", "text-transform"}
  1156. // runCSSDiff renders the properties in which a run differs from its block
  1157. func runCSSDiff(run, block map[string]string) string {
  1158. var parts []string
  1159. for _, k := range cssRunKeys {
  1160. rv, bv := run[k], block[k]
  1161. if rv == bv {
  1162. continue
  1163. }
  1164. if rv == "" {
  1165. switch k {
  1166. case "background-color":
  1167. rv = "transparent"
  1168. case "font-variant", "text-transform":
  1169. rv = "normal"
  1170. if k == "text-transform" {
  1171. rv = "none"
  1172. }
  1173. default:
  1174. continue
  1175. }
  1176. }
  1177. parts = append(parts, k+":"+rv)
  1178. }
  1179. if len(parts) == 0 {
  1180. return ""
  1181. }
  1182. return strings.Join(parts, ";") + ";"
  1183. }
  1184. /* ---------------- runs ---------------- */
  1185. type runsResult struct {
  1186. segments []string // inline HTML, split at page breaks
  1187. preWrap bool
  1188. bookmark string
  1189. midText bool // the text so far ends in a non-space, so a leading space is kept
  1190. }
  1191. type inlinePiece struct {
  1192. css string // run style diff
  1193. vert string
  1194. link string
  1195. rev string // "ins" | "del": a tracked change
  1196. cmt string // the comment anchored here (editor id)
  1197. html string
  1198. raw bool // html is a complete element (no span wrapping)
  1199. }
  1200. // runs renders the inline content of a paragraph
  1201. func (cv *docxConv) runs(p *xnode, part *docxPartCtx, baseR, blockR docxRPr) runsResult {
  1202. res := runsResult{}
  1203. blockCSS := rPrCSS(blockR)
  1204. var pieces []inlinePiece
  1205. var segments []string
  1206. flush := func() {
  1207. segments = append(segments, joinPieces(pieces))
  1208. pieces = nil
  1209. }
  1210. var walk func(n *xnode, link string)
  1211. walk = func(n *xnode, link string) {
  1212. for i := range n.Nodes {
  1213. c := &n.Nodes[i]
  1214. switch c.XMLName.Local {
  1215. case "r":
  1216. cv.run(c, part, baseR, blockCSS, link, &pieces, &res, flush)
  1217. case "hyperlink":
  1218. href := ""
  1219. if id := c.attrNS("relationships", "id"); id != "" {
  1220. href = part.rels[id]
  1221. }
  1222. if a := c.attr("anchor"); a != "" && href == "" {
  1223. href = "#" + a
  1224. }
  1225. walk(c, href)
  1226. case "fldSimple":
  1227. instr := strings.ToUpper(strings.TrimSpace(c.attr("instr")))
  1228. cv.fields = append(cv.fields, fieldFrame{instr: instr, inResult: true})
  1229. walk(c, link)
  1230. cv.fields = cv.fields[:len(cv.fields)-1]
  1231. case "smartTag", "customXml", "bdo", "dir":
  1232. walk(c, link)
  1233. case "ins", "moveTo", "del", "moveFrom":
  1234. prev := cv.curRev
  1235. if cv.curRev == "" {
  1236. cv.curRev = "ins"
  1237. if c.XMLName.Local == "del" || c.XMLName.Local == "moveFrom" {
  1238. cv.curRev = "del"
  1239. }
  1240. }
  1241. walk(c, link)
  1242. cv.curRev = prev
  1243. case "commentRangeStart":
  1244. cv.rv.start(c.attr("id"))
  1245. case "commentRangeEnd":
  1246. cv.rv.end(c.attr("id"))
  1247. case "sdt":
  1248. if sc := c.first("sdtContent"); sc != nil {
  1249. walk(sc, link)
  1250. }
  1251. case "AlternateContent":
  1252. if ch := c.first("Choice"); ch != nil {
  1253. walk(ch, link)
  1254. } else if fb := c.first("Fallback"); fb != nil {
  1255. walk(fb, link)
  1256. }
  1257. case "bookmarkStart":
  1258. name := c.attr("name")
  1259. if res.bookmark == "" && name != "" && name != "_GoBack" {
  1260. res.bookmark = name
  1261. }
  1262. }
  1263. }
  1264. }
  1265. walk(p, "")
  1266. flush()
  1267. res.segments = segments
  1268. return res
  1269. }
  1270. // fieldHidden reports whether we are inside a field's instruction text
  1271. func (cv *docxConv) fieldHidden() bool {
  1272. for _, f := range cv.fields {
  1273. if !f.inResult {
  1274. return true
  1275. }
  1276. }
  1277. return false
  1278. }
  1279. // fieldKind names the innermost PAGE / NUMPAGES field being shown
  1280. func (cv *docxConv) fieldKind() string {
  1281. for i := len(cv.fields) - 1; i >= 0; i-- {
  1282. w := strings.Fields(cv.fields[i].instr)
  1283. if len(w) > 0 && (w[0] == "PAGE" || w[0] == "NUMPAGES") {
  1284. return w[0]
  1285. }
  1286. }
  1287. return ""
  1288. }
  1289. func (cv *docxConv) run(r *xnode, part *docxPartCtx, baseR docxRPr, blockCSS map[string]string,
  1290. link string, pieces *[]inlinePiece, res *runsResult, pageBreak func()) {
  1291. direct := parseRPr(r.first("rPr"))
  1292. eff := baseR
  1293. if direct.rStyle != "" {
  1294. eff.merge(cv.ss.charStyle(direct.rStyle))
  1295. }
  1296. eff.merge(direct)
  1297. if eff.vanish.v {
  1298. return
  1299. }
  1300. css := runCSSDiff(rPrCSS(eff), blockCSS)
  1301. vert := ""
  1302. if eff.vert == "superscript" || eff.vert == "subscript" {
  1303. vert = eff.vert
  1304. }
  1305. emit := func(html string, raw bool) {
  1306. if kind := cv.fieldKind(); kind != "" && !raw {
  1307. html = `<span class="doc-field" data-field="` + kind + `">` + html + `</span>`
  1308. }
  1309. *pieces = append(*pieces, cv.reviewed(inlinePiece{css: css, vert: vert, link: link, html: html, raw: raw}))
  1310. }
  1311. for i := range r.Nodes {
  1312. c := &r.Nodes[i]
  1313. switch c.XMLName.Local {
  1314. case "fldChar":
  1315. switch c.attr("fldCharType") {
  1316. case "begin":
  1317. cv.fields = append(cv.fields, fieldFrame{})
  1318. case "separate":
  1319. if n := len(cv.fields); n > 0 {
  1320. cv.fields[n-1].inResult = true
  1321. }
  1322. case "end":
  1323. if n := len(cv.fields); n > 0 {
  1324. cv.fields = cv.fields[:n-1]
  1325. }
  1326. }
  1327. continue
  1328. case "instrText":
  1329. if n := len(cv.fields); n > 0 && !cv.fields[n-1].inResult {
  1330. cv.fields[n-1].instr += strings.ToUpper(c.Text)
  1331. cv.fields[n-1].instr = strings.TrimSpace(cv.fields[n-1].instr)
  1332. }
  1333. continue
  1334. }
  1335. if cv.fieldHidden() {
  1336. continue
  1337. }
  1338. switch c.XMLName.Local {
  1339. case "t", "delText":
  1340. t := c.Text
  1341. if t == "" {
  1342. continue
  1343. }
  1344. if strings.Contains(t, " ") || strings.Contains(t, "\t") || (strings.HasPrefix(t, " ") && !res.midText) {
  1345. res.preWrap = true
  1346. }
  1347. res.midText = !strings.HasSuffix(t, " ")
  1348. emit(xmlEscape(t), false)
  1349. case "tab":
  1350. emit(`<span class="doc-tab">`+"\t"+`</span>`, false)
  1351. case "ptab":
  1352. emit(`<span class="doc-tab">`+"\t"+`</span>`, false)
  1353. case "br", "cr":
  1354. if c.attr("type") == "page" {
  1355. pageBreak()
  1356. continue
  1357. }
  1358. emit("<br>", true)
  1359. res.midText = false
  1360. case "noBreakHyphen":
  1361. emit("\u2011", false)
  1362. case "softHyphen":
  1363. emit("\u00ad", false)
  1364. case "sym":
  1365. if v, err := strconv.ParseUint(c.attr("char"), 16, 32); err == nil {
  1366. // symbol fonts map glyphs into the private use area
  1367. if v >= 0xF000 && v <= 0xF0FF {
  1368. v -= 0xF000
  1369. }
  1370. if v >= 32 {
  1371. emit(xmlEscape(string(rune(v))), false)
  1372. }
  1373. }
  1374. case "footnoteReference":
  1375. id := c.attr("id")
  1376. if onOff2(c.attr("customMarkFollows")) {
  1377. continue
  1378. }
  1379. num, ok := cv.fnNumber[id]
  1380. if !ok {
  1381. num = len(cv.fnOrder) + 1
  1382. cv.fnNumber[id] = num
  1383. cv.fnOrder = append(cv.fnOrder, id)
  1384. }
  1385. // the reference is its own superscript: the run's vertAlign
  1386. // must not wrap it in a second one
  1387. *pieces = append(*pieces, cv.reviewed(inlinePiece{css: css, link: link, raw: true,
  1388. html: `<sup class="doc-fnref" data-fn="` + xmlEscape(id) + `" contenteditable="false">` + strconv.Itoa(num) + `</sup>`}))
  1389. case "footnoteRef":
  1390. // the number inside the footnote itself - the editor draws it
  1391. continue
  1392. case "drawing":
  1393. if img := cv.drawing(c, part); img != "" {
  1394. emit(img, true)
  1395. }
  1396. case "pict", "object":
  1397. if img := cv.vmlImage(c, part); img != "" {
  1398. emit(img, true)
  1399. }
  1400. case "AlternateContent":
  1401. if ch := c.first("Choice"); ch != nil {
  1402. if d := ch.first("drawing"); d != nil {
  1403. if img := cv.drawing(d, part); img != "" {
  1404. emit(img, true)
  1405. }
  1406. }
  1407. }
  1408. case "ruby":
  1409. var texts []string
  1410. collectText(c.first("rubyBase"), &texts)
  1411. if s := strings.Join(texts, ""); s != "" {
  1412. emit(xmlEscape(s), false)
  1413. }
  1414. }
  1415. }
  1416. }
  1417. // reviewed stamps the review state in force onto a piece
  1418. func (cv *docxConv) reviewed(p inlinePiece) inlinePiece {
  1419. p.rev = cv.curRev
  1420. p.cmt = cv.rv.current()
  1421. if p.cmt != "" {
  1422. cv.rv.used[p.cmt] = true
  1423. }
  1424. return p
  1425. }
  1426. // joinPieces merges adjacent pieces sharing one format into one span.
  1427. // Nesting, outermost first: comment anchor, link, tracked change, style.
  1428. func joinPieces(pieces []inlinePiece) string {
  1429. var sb strings.Builder
  1430. groupBy(len(pieces), func(a, b int) bool { return pieces[a].cmt == pieces[b].cmt }, func(i, j int) {
  1431. inner := joinLinks(pieces[i:j])
  1432. if cmt := pieces[i].cmt; cmt != "" {
  1433. sb.WriteString(`<span class="doc-cmt" data-cid="` + xmlEscape(cmt) + `">` + inner + `</span>`)
  1434. } else {
  1435. sb.WriteString(inner)
  1436. }
  1437. })
  1438. return sb.String()
  1439. }
  1440. // groupBy calls emit(i, j) for every run [i, j) of neighbours same says
  1441. // belong together
  1442. func groupBy(n int, same func(a, b int) bool, emit func(i, j int)) {
  1443. i := 0
  1444. for i < n {
  1445. j := i + 1
  1446. for j < n && same(i, j) {
  1447. j++
  1448. }
  1449. emit(i, j)
  1450. i = j
  1451. }
  1452. }
  1453. func joinLinks(pieces []inlinePiece) string {
  1454. var sb strings.Builder
  1455. groupBy(len(pieces), func(a, b int) bool { return pieces[a].link == pieces[b].link }, func(i, j int) {
  1456. var inner strings.Builder
  1457. groupBy(j-i, func(a, b int) bool { return pieces[i+a].rev == pieces[i+b].rev }, func(ri, rj int) {
  1458. h := joinStyled(pieces[i+ri : i+rj])
  1459. switch pieces[i+ri].rev {
  1460. case "ins":
  1461. h = `<ins class="doc-ins">` + h + `</ins>`
  1462. case "del":
  1463. h = `<del class="doc-del">` + h + `</del>`
  1464. }
  1465. inner.WriteString(h)
  1466. })
  1467. if link := pieces[i].link; link != "" {
  1468. sb.WriteString(`<a href="` + xmlEscape(link) + `" style="color:inherit;text-decoration:inherit;">` + inner.String() + `</a>`)
  1469. } else {
  1470. sb.WriteString(inner.String())
  1471. }
  1472. })
  1473. return sb.String()
  1474. }
  1475. func joinStyled(pieces []inlinePiece) string {
  1476. var sb strings.Builder
  1477. groupBy(len(pieces), func(a, b int) bool {
  1478. return pieces[a].css == pieces[b].css && pieces[a].vert == pieces[b].vert
  1479. }, func(i, j int) {
  1480. var text strings.Builder
  1481. for k := i; k < j; k++ {
  1482. text.WriteString(pieces[k].html)
  1483. }
  1484. h := text.String()
  1485. if css := pieces[i].css; css != "" {
  1486. h = `<span style="` + xmlEscape(css) + `">` + h + `</span>`
  1487. }
  1488. switch pieces[i].vert {
  1489. case "superscript":
  1490. h = "<sup>" + h + "</sup>"
  1491. case "subscript":
  1492. h = "<sub>" + h + "</sub>"
  1493. }
  1494. sb.WriteString(h)
  1495. })
  1496. return sb.String()
  1497. }
  1498. func stripTags(s string) string {
  1499. return tagRe.ReplaceAllString(s, "")
  1500. }
  1501. /* ---------------- pictures ---------------- */
  1502. func (cv *docxConv) mediaData(part *docxPartCtx, rid string) (string, bool) {
  1503. data, ext, ok := cv.mediaBytes(part, rid)
  1504. if !ok {
  1505. return "", false
  1506. }
  1507. return encodeDataURL(data, ext), true
  1508. }
  1509. // mediaBytes resolves an embedded picture to its bytes and image format
  1510. func (cv *docxConv) mediaBytes(part *docxPartCtx, rid string) ([]byte, string, bool) {
  1511. target, ok := part.rels[rid]
  1512. if !ok || part.ext[rid] {
  1513. return nil, "", false
  1514. }
  1515. dir := path.Dir(part.name)
  1516. mediaPath := resolvePartPath(dir, target)
  1517. data, ok := cv.files[mediaPath]
  1518. if !ok {
  1519. return nil, "", false
  1520. }
  1521. ext := strings.TrimPrefix(strings.ToLower(path.Ext(mediaPath)), ".")
  1522. switch ext {
  1523. case "jpg":
  1524. ext = "jpeg"
  1525. case "emf", "wmf":
  1526. // a Windows metafile is rendered to a bitmap the browser can show
  1527. return browserPicture(data, ext)
  1528. case "tif", "tiff":
  1529. // browsers cannot show these - keep the space, lose the picture
  1530. return nil, "", false
  1531. }
  1532. return data, ext, true
  1533. }
  1534. // drawing converts a DrawingML picture (inline or anchored)
  1535. func (cv *docxConv) drawing(n *xnode, part *docxPartCtx) string {
  1536. holder := n.first("inline")
  1537. anchor := false
  1538. if holder == nil {
  1539. holder = n.first("anchor")
  1540. anchor = holder != nil
  1541. }
  1542. if holder == nil {
  1543. return ""
  1544. }
  1545. var blips []*xnode
  1546. holder.findAll("blip", &blips)
  1547. if len(blips) == 0 {
  1548. return ""
  1549. }
  1550. rid := blips[0].attrNS("relationships", "embed")
  1551. if rid == "" {
  1552. rid = blips[0].attr("embed")
  1553. }
  1554. data, format, ok := cv.mediaBytes(part, rid)
  1555. if !ok {
  1556. return ""
  1557. }
  1558. wPt, hPt := 0.0, 0.0
  1559. if ext := holder.first("extent"); ext != nil {
  1560. wPt = twipsAttr(ext, "cx", 0) / emuPerPt
  1561. hPt = twipsAttr(ext, "cy", 0) / emuPerPt
  1562. }
  1563. // a picture turned by quarter turns or mirrored: bake it into the bitmap
  1564. turns, flipH, flipV := 0, false, false
  1565. if spPr := findFirst(holder, "spPr"); spPr != nil {
  1566. if xf := spPr.first("xfrm"); xf != nil {
  1567. if t, ok := pictureTurns(twipsAttr(xf, "rot", 0)); ok {
  1568. turns = t
  1569. }
  1570. flipH, flipV = onOff2(xf.attr("flipH")), onOff2(xf.attr("flipV"))
  1571. }
  1572. }
  1573. if turns != 0 || flipH || flipV {
  1574. if d, f, ok := orientPicture(data, format, turns, flipH, flipV); ok {
  1575. data, format = d, f
  1576. if turns%2 == 1 {
  1577. wPt, hPt = hPt, wPt
  1578. }
  1579. } else {
  1580. turns, flipH, flipV = 0, false, false
  1581. }
  1582. }
  1583. src := encodeDataURL(data, format)
  1584. var css []string
  1585. if wPt > 0 && hPt > 0 {
  1586. css = append(css, "width:"+ptStr(wPt), "height:"+ptStr(hPt))
  1587. }
  1588. // crop: srcRect is in thousandths of a percent of the source
  1589. var rects []*xnode
  1590. holder.findAll("srcRect", &rects)
  1591. if len(rects) > 0 {
  1592. t := twipsAttr(rects[0], "t", 0) / 1000
  1593. r := twipsAttr(rects[0], "r", 0) / 1000
  1594. b := twipsAttr(rects[0], "b", 0) / 1000
  1595. l := twipsAttr(rects[0], "l", 0) / 1000
  1596. if t != 0 || r != 0 || b != 0 || l != 0 {
  1597. o := orientInsets([4]float64{t, r, b, l}, turns, flipH, flipV)
  1598. t, r, b, l = o[0], o[1], o[2], o[3]
  1599. css = append(css, fmt.Sprintf("object-fit:fill;object-view-box:inset(%s%% %s%% %s%% %s%%)",
  1600. trimFloat(round3(t)), trimFloat(round3(r)), trimFloat(round3(b)), trimFloat(round3(l))))
  1601. }
  1602. }
  1603. // a picture outline
  1604. borderPt := 0.0
  1605. if spPr := findFirst(holder, "spPr"); spPr != nil {
  1606. if ln := spPr.first("ln"); ln != nil && ln.first("noFill") == nil {
  1607. if fill := ln.first("solidFill"); fill != nil {
  1608. col := "000000"
  1609. if c := fill.first("srgbClr"); c != nil && len(c.attr("val")) == 6 {
  1610. col = strings.ToLower(c.attr("val"))
  1611. }
  1612. w := twipsAttr(ln, "w", 9525) / emuPerPt
  1613. css = append(css, "border:"+ptStr(w)+" solid #"+col)
  1614. borderPt = w
  1615. }
  1616. }
  1617. }
  1618. if !anchor {
  1619. // room beside the frame: the effect extent beyond the outline (what
  1620. // the docx writer stores a picture's side margins in), else Google
  1621. // Docs' own 1.5pt (the space above and below a picture is the
  1622. // layout engine's business - see pictureLines in docs_layout.js)
  1623. ml, mr := 0.0, 0.0
  1624. if ee := holder.first("effectExtent"); ee != nil && turns%2 == 0 {
  1625. // (a quarter-turned frame keeps its turn in the extent instead)
  1626. ml = twipsAttr(ee, "l", 0)/emuPerPt - borderPt
  1627. mr = twipsAttr(ee, "r", 0)/emuPerPt - borderPt
  1628. }
  1629. if ml < 0.05 && mr < 0.05 && cv.gdocs {
  1630. ml, mr = 1.5, 1.5
  1631. }
  1632. if ml >= 0.05 {
  1633. css = append(css, "margin-left:"+ptStr(ml))
  1634. }
  1635. if mr >= 0.05 {
  1636. css = append(css, "margin-right:"+ptStr(mr))
  1637. }
  1638. }
  1639. alt := ""
  1640. if dp := holder.first("docPr"); dp != nil {
  1641. alt = dp.attr("descr")
  1642. }
  1643. cls := ""
  1644. if anchor {
  1645. x, y := 0.0, 0.0
  1646. if ph := holder.first("positionH"); ph != nil {
  1647. if off := ph.first("posOffset"); off != nil {
  1648. if v, err := strconv.ParseFloat(strings.TrimSpace(off.Text), 64); err == nil {
  1649. x = v / emuPerPt
  1650. }
  1651. }
  1652. switch ph.attr("relativeFrom") {
  1653. case "page":
  1654. x -= cv.marginL
  1655. }
  1656. if al := ph.first("align"); al != nil {
  1657. switch strings.TrimSpace(al.Text) {
  1658. case "center":
  1659. x = (cv.textW - wPt) / 2
  1660. case "right":
  1661. x = cv.textW - wPt
  1662. }
  1663. }
  1664. }
  1665. if pv := holder.first("positionV"); pv != nil {
  1666. if off := pv.first("posOffset"); off != nil && (pv.attr("relativeFrom") == "paragraph" || pv.attr("relativeFrom") == "line") {
  1667. if v, err := strconv.ParseFloat(strings.TrimSpace(off.Text), 64); err == nil {
  1668. y = v / emuPerPt
  1669. }
  1670. }
  1671. }
  1672. square := holder.first("wrapSquare") != nil || holder.first("wrapTight") != nil ||
  1673. holder.first("wrapThrough") != nil
  1674. if square {
  1675. // text flows around it: float to the side it sits on
  1676. side := "left"
  1677. if x+wPt/2 > cv.textW/2 {
  1678. side = "right"
  1679. }
  1680. css = append(css, "float:"+side, "max-width:none")
  1681. if side == "left" && x > 0 {
  1682. css = append(css, "margin-left:"+ptStr(x))
  1683. }
  1684. css = append(css, "margin-right:9pt", "margin-left:9pt")
  1685. } else {
  1686. css = append(css, "display:block", "max-width:none")
  1687. if x != 0 {
  1688. css = append(css, "margin-left:"+ptStr(x))
  1689. }
  1690. if y != 0 {
  1691. css = append(css, "margin-top:"+ptStr(y))
  1692. }
  1693. }
  1694. cls = ` class="doc-anchor"`
  1695. }
  1696. out := `<img src="` + src + `"` + cls
  1697. if alt != "" {
  1698. out += ` alt="` + xmlEscape(alt) + `"`
  1699. }
  1700. if len(css) > 0 {
  1701. out += ` style="` + strings.Join(css, ";") + `;"`
  1702. }
  1703. return out + ">"
  1704. }
  1705. func findFirst(n *xnode, local string) *xnode {
  1706. var all []*xnode
  1707. n.findAll(local, &all)
  1708. if len(all) == 0 {
  1709. return nil
  1710. }
  1711. return all[0]
  1712. }
  1713. // vmlImage converts a legacy VML picture (w:pict / w:object)
  1714. func (cv *docxConv) vmlImage(n *xnode, part *docxPartCtx) string {
  1715. var datas []*xnode
  1716. n.findAll("imagedata", &datas)
  1717. if len(datas) == 0 {
  1718. return ""
  1719. }
  1720. rid := datas[0].attrNS("relationships", "id")
  1721. if rid == "" {
  1722. rid = datas[0].attr("id")
  1723. }
  1724. src, ok := cv.mediaData(part, rid)
  1725. if !ok {
  1726. return ""
  1727. }
  1728. style := ""
  1729. var shapes []*xnode
  1730. n.findAll("shape", &shapes)
  1731. if len(shapes) > 0 {
  1732. st := shapes[0].attr("style")
  1733. w := cssLengthPt(styleProp(st, "width"))
  1734. h := cssLengthPt(styleProp(st, "height"))
  1735. if w > 0 && h > 0 {
  1736. style = ` style="width:` + ptStr(w) + `;height:` + ptStr(h) + `;"`
  1737. }
  1738. }
  1739. return `<img src="` + src + `"` + style + `>`
  1740. }
  1741. // cssLengthPt converts a CSS length (pt, px, in, cm, mm) to points
  1742. func cssLengthPt(s string) float64 {
  1743. s = strings.TrimSpace(strings.ToLower(s))
  1744. units := []struct {
  1745. suf string
  1746. k float64
  1747. }{{"pt", 1}, {"px", 0.75}, {"in", 72}, {"cm", 72 / 2.54}, {"mm", 72 / 25.4}}
  1748. for _, u := range units {
  1749. if strings.HasSuffix(s, u.suf) {
  1750. if v, err := strconv.ParseFloat(strings.TrimSuffix(s, u.suf), 64); err == nil {
  1751. return v * u.k
  1752. }
  1753. }
  1754. }
  1755. if v, err := strconv.ParseFloat(s, 64); err == nil {
  1756. return v * 0.75
  1757. }
  1758. return 0
  1759. }
  1760. /* ---------------- tables ---------------- */
  1761. type docxCell struct {
  1762. node *xnode
  1763. tcPr *xnode
  1764. gridCol int
  1765. span int
  1766. vMerge string // restart | continue | ""
  1767. rowspan int
  1768. }
  1769. func (cv *docxConv) table(tbl *xnode, part *docxPartCtx, spanAll bool) string {
  1770. direct := parseTblPr(tbl.first("tblPr"))
  1771. tp := *cv.ss.tableStyle(direct.style)
  1772. tp.merge(direct)
  1773. // grid
  1774. var grid []float64
  1775. if g := tbl.first("tblGrid"); g != nil {
  1776. for _, gc := range g.all("gridCol") {
  1777. grid = append(grid, twipsAttr(gc, "w", 0)/20)
  1778. }
  1779. }
  1780. // rows and cells with their grid positions
  1781. type rowInfo struct {
  1782. node *xnode
  1783. cells []*docxCell
  1784. }
  1785. var rows []*rowInfo
  1786. for i := range tbl.Nodes {
  1787. tr := &tbl.Nodes[i]
  1788. if tr.XMLName.Local != "tr" {
  1789. continue
  1790. }
  1791. ri := &rowInfo{node: tr}
  1792. col := 0
  1793. if trPr := tr.first("trPr"); trPr != nil {
  1794. if gb := trPr.first("gridBefore"); gb != nil {
  1795. if v, err := strconv.Atoi(gb.attr("val")); err == nil {
  1796. col += v
  1797. }
  1798. }
  1799. }
  1800. var addCells func(parent *xnode)
  1801. addCells = func(parent *xnode) {
  1802. for j := range parent.Nodes {
  1803. tc := &parent.Nodes[j]
  1804. switch tc.XMLName.Local {
  1805. case "tc":
  1806. c := &docxCell{node: tc, tcPr: tc.first("tcPr"), gridCol: col, span: 1, rowspan: 1}
  1807. if c.tcPr != nil {
  1808. if gs := c.tcPr.first("gridSpan"); gs != nil {
  1809. if v, err := strconv.Atoi(gs.attr("val")); err == nil && v > 1 {
  1810. c.span = v
  1811. }
  1812. }
  1813. if vm := c.tcPr.first("vMerge"); vm != nil {
  1814. c.vMerge = vm.attr("val")
  1815. if c.vMerge == "" {
  1816. c.vMerge = "continue"
  1817. }
  1818. }
  1819. }
  1820. ri.cells = append(ri.cells, c)
  1821. col += c.span
  1822. case "sdt":
  1823. if sc := tc.first("sdtContent"); sc != nil {
  1824. addCells(sc)
  1825. }
  1826. case "customXml":
  1827. addCells(tc)
  1828. }
  1829. }
  1830. }
  1831. addCells(tr)
  1832. rows = append(rows, ri)
  1833. }
  1834. // vertical merges -> rowspan on the restarting cell
  1835. for r, ri := range rows {
  1836. for _, c := range ri.cells {
  1837. if c.vMerge != "restart" {
  1838. continue
  1839. }
  1840. for r2 := r + 1; r2 < len(rows); r2++ {
  1841. found := false
  1842. for _, c2 := range rows[r2].cells {
  1843. if c2.gridCol == c.gridCol && c2.vMerge == "continue" {
  1844. found = true
  1845. c.rowspan++
  1846. break
  1847. }
  1848. }
  1849. if !found {
  1850. break
  1851. }
  1852. }
  1853. }
  1854. }
  1855. nCols := len(grid)
  1856. for _, ri := range rows {
  1857. n := 0
  1858. for _, c := range ri.cells {
  1859. n = maxInt(n, c.gridCol+c.span)
  1860. }
  1861. nCols = maxInt(nCols, n)
  1862. }
  1863. for len(grid) < nCols {
  1864. grid = append(grid, cv.textW/float64(maxInt(nCols, 1)))
  1865. }
  1866. totalW := 0.0
  1867. for _, w := range grid {
  1868. totalW += w
  1869. }
  1870. if tp.width.set && tp.widthType == "dxa" && tp.width.v > 0 && totalW == 0 {
  1871. totalW = tp.width.v / 20
  1872. }
  1873. var css []string
  1874. if totalW > 0 {
  1875. // the grid decides the columns, not the content (Word's fixed
  1876. // layout, and what Google Docs always does)
  1877. css = append(css, "width:"+ptStr(totalW), "table-layout:fixed")
  1878. }
  1879. switch tp.jc {
  1880. case "center":
  1881. css = append(css, "margin-left:auto", "margin-right:auto")
  1882. case "right", "end":
  1883. css = append(css, "margin-left:auto", "margin-right:0")
  1884. default:
  1885. if tp.ind.set && tp.ind.v != 0 {
  1886. css = append(css, "margin-left:"+ptStr(tp.ind.v/20))
  1887. }
  1888. }
  1889. cls := "of-table"
  1890. if spanAll {
  1891. cls += " col-span-all"
  1892. }
  1893. // data-docx: the table lays out as Word's (no spacing around it) -
  1894. // except one the editor made, which keeps the editor's own
  1895. docxAttr := ` data-docx="1"`
  1896. if pr := tbl.first("tblPr"); pr != nil {
  1897. if st := pr.first("tblStyle"); st != nil && st.attr("val") == editorTableStyle {
  1898. docxAttr = ""
  1899. }
  1900. }
  1901. var sb strings.Builder
  1902. sb.WriteString(`<table class="` + cls + `"` + docxAttr + ` style="` + strings.Join(css, ";") + `;">`)
  1903. if len(grid) > 0 {
  1904. sb.WriteString("<colgroup>")
  1905. for _, w := range grid {
  1906. sb.WriteString(`<col style="width:` + ptStr(w) + `">`)
  1907. }
  1908. sb.WriteString("</colgroup>")
  1909. }
  1910. sb.WriteString("<tbody>")
  1911. for r, ri := range rows {
  1912. trStyle := ""
  1913. trData := ""
  1914. if trPr := ri.node.first("trPr"); trPr != nil {
  1915. if th := trPr.first("trHeight"); th != nil {
  1916. if v := numAttr(th, "val"); v.set && v.v > 0 {
  1917. trStyle = ` style="height:` + ptStr(v.v/20) + `;"`
  1918. if th.attr("hRule") == "exact" {
  1919. trData += ` data-exact="1"`
  1920. }
  1921. }
  1922. }
  1923. if onOff(trPr.first("cantSplit")).v {
  1924. trData += ` data-cant-split="1"`
  1925. }
  1926. if onOff(trPr.first("tblHeader")).v {
  1927. trData += ` data-header-row="1"`
  1928. }
  1929. }
  1930. sb.WriteString("<tr" + trStyle + trData + ">")
  1931. for _, c := range ri.cells {
  1932. if c.vMerge == "continue" {
  1933. continue
  1934. }
  1935. sb.WriteString(cv.cell(c, tp, r, len(rows), nCols, c.rowspan, part))
  1936. }
  1937. sb.WriteString("</tr>")
  1938. }
  1939. sb.WriteString("</tbody></table>")
  1940. return sb.String()
  1941. }
  1942. func (cv *docxConv) cell(c *docxCell, tp docxTblPr, row, nRows, nCols, rowspan int, part *docxPartCtx) string {
  1943. var tcBorders map[string]docxBorder
  1944. var tcMar map[string]optNum
  1945. shd, vAlign := "", ""
  1946. if c.tcPr != nil {
  1947. tcBorders = parseBorderSet(c.tcPr.first("tcBorders"))
  1948. tcMar = parseMarginSet(c.tcPr.first("tcMar"))
  1949. if s := c.tcPr.first("shd"); s != nil {
  1950. if f := strings.ToLower(s.attr("fill")); len(f) == 6 {
  1951. shd = f
  1952. }
  1953. }
  1954. if va := c.tcPr.first("vAlign"); va != nil {
  1955. vAlign = va.attr("val")
  1956. }
  1957. }
  1958. lastRow := row+rowspan >= nRows
  1959. firstCol := c.gridCol == 0
  1960. lastCol := c.gridCol+c.span >= nCols
  1961. side := func(name, outer, inner string, isOuter bool) string {
  1962. if b, ok := tcBorders[name]; ok {
  1963. if !b.visible() {
  1964. return "none"
  1965. }
  1966. return borderCSS(b)
  1967. }
  1968. key := inner
  1969. if isOuter {
  1970. key = outer
  1971. }
  1972. if b, ok := tp.borders[key]; ok && b.visible() {
  1973. return borderCSS(b)
  1974. }
  1975. return "none"
  1976. }
  1977. var css []string
  1978. css = append(css,
  1979. "border-top:"+side("top", "top", "insideH", row == 0),
  1980. "border-right:"+side("right", "right", "insideV", lastCol),
  1981. "border-bottom:"+side("bottom", "bottom", "insideH", lastRow),
  1982. "border-left:"+side("left", "left", "insideV", firstCol))
  1983. mar := func(name string, def float64) float64 {
  1984. if v, ok := tcMar[name]; ok {
  1985. return v.v / 20
  1986. }
  1987. if v, ok := tp.cellMar[name]; ok {
  1988. return v.v / 20
  1989. }
  1990. return def
  1991. }
  1992. // Word's defaults when nothing states a margin: 0.08" left and right
  1993. css = append(css, "padding:"+ptStr(mar("top", 0))+" "+ptStr(mar("right", 5.4))+" "+
  1994. ptStr(mar("bottom", 0))+" "+ptStr(mar("left", 5.4)))
  1995. switch vAlign {
  1996. case "center":
  1997. css = append(css, "vertical-align:middle")
  1998. case "bottom":
  1999. css = append(css, "vertical-align:bottom")
  2000. default:
  2001. css = append(css, "vertical-align:top")
  2002. }
  2003. if shd != "" && shd != "auto" {
  2004. css = append(css, "background-color:#"+shd)
  2005. }
  2006. attrs := ""
  2007. if c.span > 1 {
  2008. attrs += ` colspan="` + strconv.Itoa(c.span) + `"`
  2009. }
  2010. if rowspan > 1 {
  2011. attrs += ` rowspan="` + strconv.Itoa(rowspan) + `"`
  2012. }
  2013. inner := cv.blocks(c.node, part, blockCtx{cell: true})
  2014. if inner == "" {
  2015. inner = "<p><br></p>"
  2016. }
  2017. return "<td" + attrs + ` style="` + strings.Join(css, ";") + `;">` + inner + "</td>"
  2018. }