// 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/, 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 = 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{}) return w.pack(title) } // ---- Package --------------------------------------------------------------- const ( docxTypes = ` ` + `` + `` + `` + `` + `` + `` + `` + `` + `` docxRootRels = ` ` + `` + `` + `` 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 := ` ` + `` + `` for _, r := range w.rels { mode := "" if r.external { mode = ` TargetMode="External"` } rels += `` } rels += `` document := ` ` + w.b.String() + `` + `` + `` core := ` ` + `` + xmlText(title) + `Docwell` + `` + time.Now().UTC().Format(time.RFC3339) + `` + `` 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(` ` + `` + `` + `` + `` + `` + ``) sizes := []int{36, 30, 26, 24, 22, 20} for i, sz := range sizes { fmt.Fprintf(&b, ``+ ``+ ``, i+1, i+1, i, sz) } b.WriteString(`` + `` + `` + `` + `` + `` + `` + `` + `` + `` + `` + `` + `` + `` + `` + `` + `` + `` + `` + ``) 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(` `) bullets := []string{"•", "◦", "▪"} for abs, ordered := range []bool{false, true} { fmt.Fprintf(&b, ``, abs+1) for lvl := range 9 { if ordered { fmt.Fprintf(&b, ``, lvl, lvl+1) } else { fmt.Fprintf(&b, ``, lvl, bullets[lvl%3]) } fmt.Fprintf(&b, ``, 720+lvl*360) } b.WriteString(``) } for i, n := range w.nums { abs := 1 if n.ordered { abs = 2 } fmt.Fprintf(&b, ``, i+1, abs) if n.ordered && n.start != 1 { fmt.Fprintf(&b, ``, n.level, n.start) } b.WriteString(``) } b.WriteString(``) 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("") if p.style != "" { w.b.WriteString(``) } if p.numID > 0 { fmt.Fprintf(&w.b, ``, p.ilvl, p.numID) } if p.border != "" || p.rule { w.b.WriteString("") if p.border != "" { w.b.WriteString(``) } if p.rule { w.b.WriteString(``) } w.b.WriteString("") } if p.shading != "" { w.b.WriteString(``) } if p.indent > 0 { fmt.Fprintf(&w.b, ``, p.indent) } if p.align != "" { w.b.WriteString(``) } w.b.WriteString("") if content != nil { content() } w.b.WriteString("") } // 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 "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.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(`` + ``) for range cols { fmt.Fprintf(&w.b, ``, total/cols) } w.b.WriteString("") for _, row := range n.Content { header := len(row.Content) > 0 for _, c := range row.Content { header = header && c.Type == "tableHeader" } w.b.WriteString("") if header { w.b.WriteString("") } for _, c := range row.Content { span := max(c.intAttr("colspan", 1), 1) fmt.Fprintf(&w.b, ``, total/cols*span) if span > 1 { fmt.Fprintf(&w.b, ``, span) } if c.Type == "tableHeader" { w.b.WriteString(``) } w.b.WriteString("") 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(), "") { // A cell must end with a paragraph. w.para(paraProps{}, nil) } w.b.WriteString("") } w.b.WriteString("") } w.b.WriteString("") // 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("") 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}) 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.b.WriteString("") if p.href != "" { w.b.WriteString(``) } if p.code { w.b.WriteString(``) } if p.bold { w.b.WriteString("") } if p.italic { w.b.WriteString("") } if p.strike { w.b.WriteString("") } if p.color != "" { w.b.WriteString(``) } if p.underline { w.b.WriteString(``) } if p.shade != "" { w.b.WriteString(``) } w.b.WriteString("") for i, line := range strings.Split(s, "\n") { if i > 0 { w.b.WriteString("") } for j, part := range strings.Split(line, "\t") { if j > 0 { w.b.WriteString("") } if part != "" { w.b.WriteString(`` + xmlText(part) + ``) } } } w.b.WriteString("") if p.href != "" { w.b.WriteString("") } } // 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, ``+ ``+ ``+ ``+ ``+ ``+ ``+ ``, 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("&") case r == '<': b.WriteString("<") case r == '>': b.WriteString(">") case r == '"': b.WriteString(""") case r < 0x20 && r != '\t' && r != '\n' && r != '\r', r == 0xFFFE, r == 0xFFFF: default: b.WriteRune(r) } } return b.String() }