Files
Docwell/Server/internal/convert/docx_export.go
T
tajniak81andClaude Opus 5.5 e441880f2f
CI / desktop (ubuntu-latest) (push) Successful in 1h15m48s
CI / mobile (push) Failing after 3m6s
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
CI / go (Media) (push) Successful in 10m21s
CI / go (Server) (push) Failing after 19m16s
CI / go (Web-App) (push) Successful in 10m27s
CI / frontend (push) Failing after 7m25s
CI / docker (push) Successful in 46m48s
Add the block types Docmost has and Docwell lacked
The slash menu gains Video, Audio, Page break, Footnote, Tabs, Status,
Emoji, Subpages, Synced block and a fifth column size:
- Video and audio upload a file that plays on the page.
- Page breaks show as a labelled line and start a new page in print,
  Word and PDF.
- Footnotes are numbered in reading order and listed at the end of the
  page. Their notes hold bold, italic, code and links, with a plain copy
  kept for search.
- Tabs hold blocks on several named tabs; which one shows is each
  reader's own choice.
- Status badges are coloured words in the text.
- Typing ":" and a word picks an emoji, from the list the page icon
  picker uses, now kept in the editor package.
- Subpages lists the page's child pages, read afresh from the page tree.
- A synced block is a synced page that shows one block of another page,
  made from a copied block link.

Exports (HTML, Markdown, Word, PDF) and search handle every new block.
Page and space exports list a page's subpages. Labels are translated in
all five languages.

The phone toolbar gets Tabs, Footnote, Status, Emoji, Subpages and Page
break, and the app answers the editor's request for the page's
subpages. The bridge protocol goes to version 5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:37:32 +01:00

717 lines
25 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package convert
import (
"archive/zip"
"bytes"
"fmt"
"strconv"
"strings"
"time"
)
// DOCXOptions adjust a Word export.
type DOCXOptions struct {
Options
// BaseURL makes server paths (/p/<id>, attachments) absolute links.
BaseURL string
// Image loads an image by its document URL; nil, or an error, leaves a
// link to the image in its place.
Image func(src string) ([]byte, error)
}
// DOCX renders a page as a Word document with the title on top. Headings,
// lists, to-dos, quotes, callouts, code, tables, alignment, text colours and
// highlights, links and images are kept in a form FromDOCX reads back.
// Diagrams and embeds become links, formulas their LaTeX.
func DOCX(title string, doc Node, o DOCXOptions) ([]byte, error) {
doc, notes := numberFootnotes(withoutSuggestions(expandDatabases(doc)))
w := &docxWriter{o: o}
if strings.TrimSpace(title) != "" {
w.para(paraProps{style: "Title"}, func() { w.text(title, runProps{}) })
}
w.blocks(doc.Content, blockCtx{})
// Footnotes are listed at the end, numbered like their marks in the text.
if len(notes) > 0 {
w.para(paraProps{rule: true}, nil)
for i, note := range notes {
w.para(paraProps{}, func() {
w.text(strconv.Itoa(i+1)+". ", runProps{bold: true})
w.inline(note, runProps{})
})
}
}
return w.pack(title)
}
// ---- Package ---------------------------------------------------------------
const (
docxTypes = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">` +
`<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>` +
`<Default Extension="xml" ContentType="application/xml"/>` +
`<Default Extension="png" ContentType="image/png"/>` +
`<Default Extension="jpeg" ContentType="image/jpeg"/>` +
`<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>` +
`<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>` +
`<Override PartName="/word/numbering.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml"/>` +
`<Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>` +
`</Types>`
docxRootRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
`<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>` +
`<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>` +
`</Relationships>`
relStyles = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"
relNumbering = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering"
relLink = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"
relImage = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"
)
func (w *docxWriter) pack(title string) ([]byte, error) {
var buf bytes.Buffer
z := zip.NewWriter(&buf)
put := func(name, body string) error {
f, err := z.Create(name)
if err == nil {
_, err = f.Write([]byte(body))
}
return err
}
rels := `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
`<Relationship Id="rId1" Type="` + relStyles + `" Target="styles.xml"/>` +
`<Relationship Id="rId2" Type="` + relNumbering + `" Target="numbering.xml"/>`
for _, r := range w.rels {
mode := ""
if r.external {
mode = ` TargetMode="External"`
}
rels += `<Relationship Id="` + r.id + `" Type="` + r.typ + `" Target="` + xmlText(r.target) + `"` + mode + `/>`
}
rels += `</Relationships>`
document := `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document 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"><w:body>` +
w.b.String() +
`<w:sectPr><w:pgSz w:w="11906" w:h="16838"/>` +
`<w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="708" w:footer="708" w:gutter="0"/>` +
`</w:sectPr></w:body></w:document>`
core := `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" ` +
`xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" ` +
`xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">` +
`<dc:title>` + xmlText(title) + `</dc:title><dc:creator>Docwell</dc:creator>` +
`<dcterms:created xsi:type="dcterms:W3CDTF">` + time.Now().UTC().Format(time.RFC3339) + `</dcterms:created>` +
`</cp:coreProperties>`
for _, p := range []struct{ name, body string }{
{"[Content_Types].xml", docxTypes}, {"_rels/.rels", docxRootRels}, {"docProps/core.xml", core},
{"word/document.xml", document}, {"word/_rels/document.xml.rels", rels},
{"word/styles.xml", docxStyles}, {"word/numbering.xml", w.numbering()},
} {
if err := put(p.name, p.body); err != nil {
return nil, err
}
}
for _, m := range w.media {
f, err := z.Create("word/media/" + m.name)
if err != nil {
return nil, err
}
if _, err := f.Write(m.data); err != nil {
return nil, err
}
}
if err := z.Close(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// The styles FromDOCX recognises by name: headings, Title, Quote, Code and
// Callout, plus the Hyperlink character style and a bordered table style.
var docxStyles = func() string {
var b strings.Builder
b.WriteString(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">` +
`<w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="Calibri" w:hAnsi="Calibri" w:eastAsia="Calibri" w:cs="Calibri"/>` +
`<w:sz w:val="22"/><w:szCs w:val="22"/><w:lang w:val="en-US"/></w:rPr></w:rPrDefault>` +
`<w:pPrDefault><w:pPr><w:spacing w:after="120" w:line="276" w:lineRule="auto"/></w:pPr></w:pPrDefault></w:docDefaults>` +
`<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/><w:qFormat/></w:style>` +
`<w:style w:type="paragraph" w:styleId="Title"><w:name w:val="Title"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:qFormat/>` +
`<w:pPr><w:spacing w:after="240"/></w:pPr><w:rPr><w:b/><w:sz w:val="48"/></w:rPr></w:style>`)
sizes := []int{36, 30, 26, 24, 22, 20}
for i, sz := range sizes {
fmt.Fprintf(&b, `<w:style w:type="paragraph" w:styleId="Heading%d"><w:name w:val="heading %d"/><w:basedOn w:val="Normal"/>`+
`<w:next w:val="Normal"/><w:qFormat/><w:pPr><w:keepNext/><w:spacing w:before="240" w:after="80"/><w:outlineLvl w:val="%d"/></w:pPr>`+
`<w:rPr><w:b/><w:sz w:val="%d"/></w:rPr></w:style>`, i+1, i+1, i, sz)
}
b.WriteString(`<w:style w:type="paragraph" w:styleId="Quote"><w:name w:val="Quote"/><w:basedOn w:val="Normal"/><w:qFormat/>` +
`<w:pPr><w:pBdr><w:left w:val="single" w:sz="18" w:space="8" w:color="C8C8C8"/></w:pBdr><w:ind w:left="284"/></w:pPr>` +
`<w:rPr><w:color w:val="5F5F5F"/></w:rPr></w:style>` +
`<w:style w:type="paragraph" w:styleId="Code"><w:name w:val="Code"/><w:basedOn w:val="Normal"/>` +
`<w:pPr><w:shd w:val="clear" w:color="auto" w:fill="F4F4F1"/><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr>` +
`<w:rPr><w:rFonts w:ascii="Consolas" w:hAnsi="Consolas" w:cs="Consolas"/><w:sz w:val="19"/></w:rPr></w:style>` +
`<w:style w:type="paragraph" w:styleId="Callout"><w:name w:val="Callout"/><w:basedOn w:val="Normal"/>` +
`<w:pPr><w:ind w:left="170" w:right="170"/></w:pPr></w:style>` +
`<w:style w:type="paragraph" w:styleId="TableHeading"><w:name w:val="Table Heading"/><w:basedOn w:val="Normal"/>` +
`<w:rPr><w:b/></w:rPr></w:style>` +
`<w:style w:type="paragraph" w:styleId="ListParagraph"><w:name w:val="List Paragraph"/><w:basedOn w:val="Normal"/>` +
`<w:pPr><w:spacing w:after="40"/></w:pPr></w:style>` +
`<w:style w:type="character" w:styleId="Hyperlink"><w:name w:val="Hyperlink"/>` +
`<w:rPr><w:color w:val="2F6FBF"/><w:u w:val="single"/></w:rPr></w:style>` +
`<w:style w:type="table" w:styleId="TableGrid"><w:name w:val="Table Grid"/><w:tblPr><w:tblBorders>` +
`<w:top w:val="single" w:sz="4" w:space="0" w:color="BFBFBF"/><w:left w:val="single" w:sz="4" w:space="0" w:color="BFBFBF"/>` +
`<w:bottom w:val="single" w:sz="4" w:space="0" w:color="BFBFBF"/><w:right w:val="single" w:sz="4" w:space="0" w:color="BFBFBF"/>` +
`<w:insideH w:val="single" w:sz="4" w:space="0" w:color="BFBFBF"/><w:insideV w:val="single" w:sz="4" w:space="0" w:color="BFBFBF"/>` +
`</w:tblBorders><w:tblCellMar><w:left w:w="100" w:type="dxa"/><w:right w:w="100" w:type="dxa"/></w:tblCellMar></w:tblPr></w:style>` +
`</w:styles>`)
return b.String()
}()
// numbering lists a bulleted and a numbered pattern, and one list instance
// per list in the document so each numbered list counts from its own start.
func (w *docxWriter) numbering() string {
var b strings.Builder
b.WriteString(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">`)
bullets := []string{"•", "◦", "▪"}
for abs, ordered := range []bool{false, true} {
fmt.Fprintf(&b, `<w:abstractNum w:abstractNumId="%d"><w:multiLevelType w:val="hybridMultilevel"/>`, abs+1)
for lvl := range 9 {
if ordered {
fmt.Fprintf(&b, `<w:lvl w:ilvl="%d"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%%%d."/>`, lvl, lvl+1)
} else {
fmt.Fprintf(&b, `<w:lvl w:ilvl="%d"><w:start w:val="1"/><w:numFmt w:val="bullet"/><w:lvlText w:val="%s"/>`, lvl, bullets[lvl%3])
}
fmt.Fprintf(&b, `<w:lvlJc w:val="left"/><w:pPr><w:ind w:left="%d" w:hanging="360"/></w:pPr></w:lvl>`, 720+lvl*360)
}
b.WriteString(`</w:abstractNum>`)
}
for i, n := range w.nums {
abs := 1
if n.ordered {
abs = 2
}
fmt.Fprintf(&b, `<w:num w:numId="%d"><w:abstractNumId w:val="%d"/>`, i+1, abs)
if n.ordered && n.start != 1 {
fmt.Fprintf(&b, `<w:lvlOverride w:ilvl="%d"><w:startOverride w:val="%d"/></w:lvlOverride>`, n.level, n.start)
}
b.WriteString(`</w:num>`)
}
b.WriteString(`</w:numbering>`)
return b.String()
}
// ---- Document --------------------------------------------------------------
type docxRel struct {
id, typ, target string
external bool
}
type docxNum struct {
ordered bool
level int
start int
}
type docxWriter struct {
o DOCXOptions
b strings.Builder
rels []docxRel
media []struct {
name string
data []byte
}
nums []docxNum
images int
}
// blockCtx is what surrounds a block: a quote, a callout, list depth.
type blockCtx struct {
quote bool
callout string // the callout's colour, "" outside one
depth int // list nesting, for indentation
}
type paraProps struct {
style string
align string
numID int
ilvl int
indent int // left indent in twips
shading string // background "rrggbb"
border string // left border colour "rrggbb"
rule bool // a horizontal line under the paragraph
}
type runProps struct {
bold, italic, underline, strike, code bool
color, shade, href string
}
func (w *docxWriter) rel(typ, target string, external bool) string {
id := "rId" + strconv.Itoa(len(w.rels)+3)
w.rels = append(w.rels, docxRel{id: id, typ: typ, target: target, external: external})
return id
}
// link makes a document URL something Word can open, or "".
func (w *docxWriter) link(href string) string {
href = w.o.file(href)
if strings.HasPrefix(href, "/") && !strings.HasPrefix(href, "//") {
if w.o.BaseURL == "" {
return ""
}
href = strings.TrimRight(w.o.BaseURL, "/") + href
}
if !safeURL.MatchString(href) || strings.HasPrefix(href, "#") {
return ""
}
return href
}
func (w *docxWriter) para(p paraProps, content func()) {
w.b.WriteString("<w:p><w:pPr>")
if p.style != "" {
w.b.WriteString(`<w:pStyle w:val="` + p.style + `"/>`)
}
if p.numID > 0 {
fmt.Fprintf(&w.b, `<w:numPr><w:ilvl w:val="%d"/><w:numId w:val="%d"/></w:numPr>`, p.ilvl, p.numID)
}
if p.border != "" || p.rule {
w.b.WriteString("<w:pBdr>")
if p.border != "" {
w.b.WriteString(`<w:left w:val="single" w:sz="24" w:space="8" w:color="` + p.border + `"/>`)
}
if p.rule {
w.b.WriteString(`<w:bottom w:val="single" w:sz="6" w:space="1" w:color="D2D2D2"/>`)
}
w.b.WriteString("</w:pBdr>")
}
if p.shading != "" {
w.b.WriteString(`<w:shd w:val="clear" w:color="auto" w:fill="` + p.shading + `"/>`)
}
if p.indent > 0 {
fmt.Fprintf(&w.b, `<w:ind w:left="%d"/>`, p.indent)
}
if p.align != "" {
w.b.WriteString(`<w:jc w:val="` + p.align + `"/>`)
}
w.b.WriteString("</w:pPr>")
if content != nil {
content()
}
w.b.WriteString("</w:p>")
}
// textPara is the paragraph style a text block gets where it is.
func (w *docxWriter) textPara(ctx blockCtx) paraProps {
switch {
case ctx.callout != "":
bg := strings.TrimPrefix(paletteBackground[ctx.callout], "#")
fg := strings.TrimPrefix(paletteText[ctx.callout], "#")
return paraProps{style: "Callout", shading: bg, border: fg}
case ctx.quote:
return paraProps{style: "Quote"}
case ctx.depth > 0:
return paraProps{indent: 720 + (ctx.depth-1)*360}
}
return paraProps{}
}
func (w *docxWriter) blocks(nodes []Node, ctx blockCtx) {
for _, n := range nodes {
w.block(n, ctx)
}
}
func (w *docxWriter) block(n Node, ctx blockCtx) {
switch n.Type {
case "paragraph":
p := w.textPara(ctx)
p.align = docxAlign(n)
w.para(p, func() { w.inline(n.Content, runProps{}) })
case "heading":
level := min(max(n.intAttr("level", 1), 1), 6)
w.para(paraProps{style: "Heading" + strconv.Itoa(level), align: docxAlign(n)}, func() { w.inline(n.Content, runProps{}) })
case "bulletList", "orderedList":
w.list(n, ctx)
case "taskList":
// FromDOCX reads paragraphs starting with a ballot box back as to-dos.
for _, item := range n.Content {
box := "☐ "
if item.Attrs["checked"] == true {
box = "☒ "
}
for i, c := range item.Content {
if i == 0 && c.Type == "paragraph" {
p := paraProps{style: "ListParagraph", indent: 360 + ctx.depth*360}
w.para(p, func() {
w.text(box, runProps{})
w.inline(c.Content, runProps{})
})
continue
}
w.block(c, blockCtx{depth: ctx.depth + 1})
}
}
case "blockquote":
ctx.quote = true
w.blocks(n.Content, ctx)
case "callout":
emoji, color := calloutParts(n)
ctx.callout = color
body := n.Content
// The emoji leads the first paragraph, where FromDOCX lifts it off again.
if len(body) > 0 && body[0].Type == "paragraph" {
first := body[0]
first.Content = append([]Node{{Type: "text", Text: emoji + " "}}, first.Content...)
body = append([]Node{first}, body[1:]...)
} else {
body = append([]Node{{Type: "paragraph", Content: []Node{{Type: "text", Text: emoji}}}}, body...)
}
w.blocks(body, ctx)
case "codeBlock":
w.code(PlainText(n))
case "mermaid":
w.code(n.attr("code"))
case "blockMath":
w.para(paraProps{align: "center"}, func() { w.text(n.attr("latex"), runProps{code: true}) })
case "horizontalRule":
w.para(paraProps{rule: true}, nil)
case "pageBreak":
w.b.WriteString(`<w:p><w:r><w:br w:type="page"/></w:r></w:p>`)
case "tabs":
for i, tab := range n.Content {
w.para(w.textPara(ctx), func() { w.text(tabTitle(tab, i), runProps{bold: true}) })
w.blocks(tab.Content, ctx)
}
case "video", "audio":
name := n.attr("name")
if name == "" {
name = n.Type
}
w.para(paraProps{}, func() { w.text(name, runProps{href: w.link(n.attr("src"))}) })
case "subpages":
for _, p := range w.o.Subpages {
w.para(paraProps{style: "ListParagraph", indent: 360 + ctx.depth*360}, func() {
w.text(p.label(), runProps{href: w.link("/p/" + p.ID)})
})
}
case "image":
w.image(n.attr("src"), n.attr("alt"))
case "drawio", "excalidraw":
label := "Draw.io diagram"
if n.Type == "excalidraw" {
label = "Excalidraw drawing"
}
w.para(paraProps{}, func() { w.text(label, runProps{italic: true, href: w.link(n.attr("src"))}) })
case "fileAttachment":
w.para(paraProps{}, func() { w.text(n.attr("name"), runProps{href: w.link(n.attr("url"))}) })
case "embed", "linkCard", "syncedPage":
href, title := n.card()
w.para(paraProps{}, func() {
w.text(title, runProps{href: w.link(href)})
if d := n.attr("description"); d != "" {
w.b.WriteString("<w:r><w:br/></w:r>")
w.text(d, runProps{color: "787878"})
}
})
case "tableOfContents":
// Word builds its own from the headings (References > Table of Contents).
case "details":
for _, c := range n.Content {
if c.Type == "detailsSummary" {
w.para(w.textPara(ctx), func() { w.inline(c.Content, runProps{bold: true}) })
} else {
w.blocks(c.Content, ctx)
}
}
case "table":
w.table(n)
default:
w.blocks(n.Content, ctx)
}
}
func docxAlign(n Node) string {
switch alignOf(n) {
case "center":
return "center"
case "right":
return "right"
}
return ""
}
// list writes a bulleted or numbered list as numbered paragraphs, nesting
// by level; more blocks in an item follow indented under it.
func (w *docxWriter) list(n Node, ctx blockCtx) {
w.nums = append(w.nums, docxNum{ordered: n.Type == "orderedList", level: ctx.depth, start: n.intAttr("start", 1)})
id := len(w.nums)
for _, item := range n.Content {
for i, c := range item.Content {
if i == 0 && c.Type == "paragraph" {
w.para(paraProps{style: "ListParagraph", numID: id, ilvl: min(ctx.depth, 8)}, func() { w.inline(c.Content, runProps{}) })
continue
}
w.block(c, blockCtx{depth: ctx.depth + 1})
}
}
}
func (w *docxWriter) code(text string) {
for _, line := range strings.Split(strings.ReplaceAll(text, "\t", " "), "\n") {
w.para(paraProps{style: "Code"}, func() { w.text(line, runProps{}) })
}
// A little room after the block.
w.para(paraProps{}, nil)
}
// table writes a bordered table across the page. A row of header cells
// repeats on every page, which is also how FromDOCX tells header rows.
func (w *docxWriter) table(n Node) {
cols := 0
for _, row := range n.Content {
width := 0
for _, c := range row.Content {
width += max(c.intAttr("colspan", 1), 1)
}
cols = max(cols, width)
}
if cols == 0 {
return
}
const total = 9026 // the text width of an A4 page with 1" margins, in twips
w.b.WriteString(`<w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/><w:tblW w:w="5000" w:type="pct"/>` +
`<w:tblLook w:val="04A0" w:firstRow="1" w:lastRow="0" w:firstColumn="0" w:lastColumn="0" w:noHBand="0" w:noVBand="1"/></w:tblPr><w:tblGrid>`)
for range cols {
fmt.Fprintf(&w.b, `<w:gridCol w:w="%d"/>`, total/cols)
}
w.b.WriteString("</w:tblGrid>")
for _, row := range n.Content {
header := len(row.Content) > 0
for _, c := range row.Content {
header = header && c.Type == "tableHeader"
}
w.b.WriteString("<w:tr>")
if header {
w.b.WriteString("<w:trPr><w:tblHeader/></w:trPr>")
}
for _, c := range row.Content {
span := max(c.intAttr("colspan", 1), 1)
fmt.Fprintf(&w.b, `<w:tc><w:tcPr><w:tcW w:w="%d" w:type="dxa"/>`, total/cols*span)
if span > 1 {
fmt.Fprintf(&w.b, `<w:gridSpan w:val="%d"/>`, span)
}
if c.Type == "tableHeader" {
w.b.WriteString(`<w:shd w:val="clear" w:color="auto" w:fill="F4F4F1"/>`)
}
w.b.WriteString("</w:tcPr>")
start := w.b.Len()
for _, b := range c.Content {
if b.Type == "paragraph" && c.Type == "tableHeader" {
w.para(paraProps{style: "TableHeading", align: docxAlign(b)}, func() { w.inline(b.Content, runProps{}) })
continue
}
w.block(b, blockCtx{})
}
if w.b.Len() == start || !strings.HasSuffix(w.b.String(), "</w:p>") {
// A cell must end with a paragraph.
w.para(paraProps{}, nil)
}
w.b.WriteString("</w:tc>")
}
w.b.WriteString("</w:tr>")
}
w.b.WriteString("</w:tbl>")
// Word joins tables that touch; a paragraph keeps the next block apart.
w.para(paraProps{}, nil)
}
func (w *docxWriter) inline(nodes []Node, base runProps) {
for _, n := range nodes {
switch n.Type {
case "text":
p := base
for _, m := range n.Marks {
switch m.Type {
case "bold":
p.bold = true
case "italic":
p.italic = true
case "underline":
p.underline = true
case "strike":
p.strike = true
case "code":
p.code = true
case "textColor":
if c, ok := paletteText[m.attr("color")]; ok {
p.color = strings.TrimPrefix(c, "#")
}
case "highlight":
c, ok := paletteBackground[m.attr("color")]
if !ok {
c = paletteBackground["yellow"]
}
p.shade = strings.TrimPrefix(c, "#")
case "link":
p.href = w.link(m.attr("href"))
}
}
w.text(n.Text, p)
case "hardBreak":
w.b.WriteString("<w:r><w:br/></w:r>")
case "inlineMath":
w.text(n.attr("latex"), runProps{code: true})
case "mention":
w.text("@"+mentionLabel(n), runProps{bold: true})
case "dateMention":
w.text(n.attr("date"), runProps{bold: true})
case "status":
w.text(statusText(n), runProps{bold: true, shade: strings.TrimPrefix(paletteBackground[statusColor(n)], "#")})
case "footnote":
w.text("["+footnoteNumber(n)+"]", runProps{color: "787878"})
default:
w.inline(n.Content, base)
}
}
}
// text writes one run, inside a hyperlink when it links somewhere.
func (w *docxWriter) text(s string, p runProps) {
if s == "" {
return
}
if p.href != "" {
w.b.WriteString(`<w:hyperlink r:id="` + w.rel(relLink, p.href, true) + `" w:history="1">`)
}
w.b.WriteString("<w:r><w:rPr>")
if p.href != "" {
w.b.WriteString(`<w:rStyle w:val="Hyperlink"/>`)
}
if p.code {
w.b.WriteString(`<w:rFonts w:ascii="Consolas" w:hAnsi="Consolas" w:cs="Consolas"/>`)
}
if p.bold {
w.b.WriteString("<w:b/>")
}
if p.italic {
w.b.WriteString("<w:i/>")
}
if p.strike {
w.b.WriteString("<w:strike/>")
}
if p.color != "" {
w.b.WriteString(`<w:color w:val="` + strings.ToUpper(p.color) + `"/>`)
}
if p.underline {
w.b.WriteString(`<w:u w:val="single"/>`)
}
if p.shade != "" {
w.b.WriteString(`<w:shd w:val="clear" w:color="auto" w:fill="` + strings.ToUpper(p.shade) + `"/>`)
}
w.b.WriteString("</w:rPr>")
for i, line := range strings.Split(s, "\n") {
if i > 0 {
w.b.WriteString("<w:br/>")
}
for j, part := range strings.Split(line, "\t") {
if j > 0 {
w.b.WriteString("<w:tab/>")
}
if part != "" {
w.b.WriteString(`<w:t xml:space="preserve">` + xmlText(part) + `</w:t>`)
}
}
}
w.b.WriteString("</w:r>")
if p.href != "" {
w.b.WriteString("</w:hyperlink>")
}
}
// image embeds a picture at its size (96 pixels to the inch), shrunk to the
// page width, or links to it when it cannot be loaded.
func (w *docxWriter) image(src, alt string) {
fallback := func() {
text := "Image"
if alt != "" {
text += ": " + alt
}
w.para(paraProps{}, func() { w.text("["+text+"]", runProps{italic: true, href: w.link(src)}) })
}
if w.o.Image == nil || src == "" {
fallback()
return
}
data, err := w.o.Image(src)
if err != nil {
fallback()
return
}
kind, body, px, py, err := pdfImage(data)
if err != nil {
fallback()
return
}
const emuPerPx, maxW = 9525, 5731510 // 6.27" in EMU
cx, cy := int64(px)*emuPerPx, int64(py)*emuPerPx
if cx > maxW {
cx, cy = maxW, cy*maxW/cx
}
w.images++
ext := "png"
if kind == "JPG" {
ext = "jpeg"
}
name := "image" + strconv.Itoa(w.images) + "." + ext
w.media = append(w.media, struct {
name string
data []byte
}{name, body})
rid := w.rel(relImage, "media/"+name, false)
id := strconv.Itoa(w.images)
w.para(paraProps{}, func() {
fmt.Fprintf(&w.b, `<w:r><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0">`+
`<wp:extent cx="%d" cy="%d"/><wp:docPr id="%s" name="Picture %s" descr="%s"/>`+
`<wp:cNvGraphicFramePr><a:graphicFrameLocks noChangeAspect="1"/></wp:cNvGraphicFramePr>`+
`<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">`+
`<pic:pic><pic:nvPicPr><pic:cNvPr id="%s" name="%s"/><pic:cNvPicPr/></pic:nvPicPr>`+
`<pic:blipFill><a:blip r:embed="%s"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill>`+
`<pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="%d" cy="%d"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr>`+
`</pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>`,
cx, cy, id, id, xmlText(alt), id, name, rid, cx, cy)
})
}
// xmlText escapes text for XML and leaves out the control characters XML
// cannot hold.
func xmlText(s string) string {
var b strings.Builder
for _, r := range s {
switch {
case r == '&':
b.WriteString("&amp;")
case r == '<':
b.WriteString("&lt;")
case r == '>':
b.WriteString("&gt;")
case r == '"':
b.WriteString("&quot;")
case r < 0x20 && r != '\t' && r != '\n' && r != '\r', r == 0xFFFE, r == 0xFFFF:
default:
b.WriteRune(r)
}
}
return b.String()
}