Files
Docwell/Server/internal/convert/docx.go
T
tajniak81andClaude Opus 5.5 ec2c1661b0 Add Word and Notion import and PDF export
Import (Import on a space's page list, or POST /spaces/{id}/import):
- Word (.docx, up to 25 MB): Title and heading styles, bulleted and
  numbered lists with nesting, quotes, code styles, bold, italic,
  underline, strikethrough, links (including HYPERLINK fields) and
  images, which are stored as attachments of the new page. Tables come in
  as one paragraph per row, as in HTML import.
- Notion export (.zip, Markdown & CSV or HTML, up to 100 MB and 2000
  pages, split exports included): rebuilds the page tree, points links
  between the pages (relative and notion.so ones) at the new pages, and
  stores images and files as attachments. A database becomes a page that
  lists its rows, with the row pages under it. The response lists the
  pages made at the parent's level.
- Every file is read before any page is made, so a bad file leaves
  nothing behind. Archives are capped by bytes actually unpacked, not by
  the sizes they declare.

PDF export (page menu, or ?format=pdf): A4 with the Go fonts (Latin,
Polish, Greek, Cyrillic), a bookmark per heading and page numbers.
Images on the page are drawn in (JPEG as is; PNG, GIF and WebP redrawn);
images on other sites are not fetched. Diagrams become a link to their
file and Mermaid charts show their source. Emoji are left out, since the
fonts have none.

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

741 lines
18 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package convert
import (
"archive/zip"
"bytes"
"encoding/xml"
"errors"
"fmt"
"io"
"path"
"regexp"
"strconv"
"strings"
)
// Asset is a file an imported document refers to. The document uses Ref as
// the file's URL until the importer has stored it and calls RewriteURLs.
type Asset struct {
Ref string
Name string
Data []byte
}
// AssetRef is the placeholder URL of the n-th asset of an import.
func AssetRef(n int) string { return "asset:" + strconv.Itoa(n) }
// RewriteURLs replaces image sources, file and diagram URLs and link targets
// through fn, which returns the new URL (or "" to drop a link mark, or an
// image or file block).
func RewriteURLs(n Node, fn func(string) string) Node {
switch n.Type {
case "image", "drawio", "excalidraw":
if src := n.attr("src"); src != "" {
n.Attrs = cloneAttrs(n.Attrs)
n.Attrs["src"] = fn(src)
}
case "fileAttachment":
if u := n.attr("url"); u != "" {
n.Attrs = cloneAttrs(n.Attrs)
n.Attrs["url"] = fn(u)
}
}
if len(n.Marks) > 0 {
marks := make([]Mark, 0, len(n.Marks))
for _, m := range n.Marks {
if m.Type == "link" {
href := fn(m.attr("href"))
if href == "" {
continue
}
m.Attrs = cloneAttrs(m.Attrs)
m.Attrs["href"] = href
}
marks = append(marks, m)
}
n.Marks = marks
}
if len(n.Content) > 0 {
kids := make([]Node, 0, len(n.Content))
for _, c := range n.Content {
c = RewriteURLs(c, fn)
if (c.Type == "image" && c.attr("src") == "") || (c.Type == "fileAttachment" && c.attr("url") == "") {
continue
}
kids = append(kids, c)
}
n.Content = kids
}
return n
}
func cloneAttrs(a map[string]any) map[string]any {
out := make(map[string]any, len(a)+1)
for k, v := range a {
out[k] = v
}
return out
}
// ---- Zip limits ------------------------------------------------------------
// ErrTooLarge is returned when an archive unpacks to more than its limits.
var ErrTooLarge = errors.New("the archive is too large")
// readZipFile reads one archive entry, failing past limit bytes, so a small
// archive cannot unpack into an unbounded amount of memory.
func readZipFile(f *zip.File, limit int64) ([]byte, error) {
if f.UncompressedSize64 > uint64(limit) {
return nil, ErrTooLarge
}
rc, err := f.Open()
if err != nil {
return nil, err
}
defer func() { _ = rc.Close() }()
data, err := io.ReadAll(io.LimitReader(rc, limit+1))
if err != nil {
return nil, err
}
if int64(len(data)) > limit {
return nil, ErrTooLarge
}
return data, nil
}
// ---- A small XML tree ------------------------------------------------------
// xnode is an XML element with attributes keyed by local name.
type xnode struct {
name string
attrs map[string]string
kids []*xnode
text string
}
func parseXML(data []byte) (*xnode, error) {
d := xml.NewDecoder(bytes.NewReader(data))
d.Strict = false
root := &xnode{}
stack := []*xnode{root}
for {
tok, err := d.Token()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
top := stack[len(stack)-1]
switch t := tok.(type) {
case xml.StartElement:
n := &xnode{name: t.Name.Local, attrs: map[string]string{}}
for _, a := range t.Attr {
n.attrs[a.Name.Local] = a.Value
}
top.kids = append(top.kids, n)
stack = append(stack, n)
case xml.EndElement:
if len(stack) > 1 {
stack = stack[:len(stack)-1]
}
case xml.CharData:
top.text += string(t)
}
}
return root, nil
}
func (n *xnode) child(name string) *xnode {
if n == nil {
return nil
}
for _, k := range n.kids {
if k.name == name {
return k
}
}
return nil
}
func (n *xnode) val(name string) string {
if c := n.child(name); c != nil {
return c.attrs["val"]
}
return ""
}
// on tells whether a toggle property (<w:b/>, <w:i w:val="0"/>) is set.
func (n *xnode) on(name string) bool {
c := n.child(name)
if c == nil {
return false
}
v, ok := c.attrs["val"]
return !ok || (v != "0" && v != "false" && v != "none")
}
func (n *xnode) find(name string) *xnode {
if n == nil {
return nil
}
if n.name == name {
return n
}
for _, k := range n.kids {
if f := k.find(name); f != nil {
return f
}
}
return nil
}
// ---- DOCX ------------------------------------------------------------------
// maxDocxPart caps one unpacked part of a Word file (the document XML, one image).
const maxDocxPart = 50 << 20
// FromDOCX reads a Word document. Headings, lists, quotes, code, bold,
// italic, underline, strikethrough, links and images are kept; tables become
// one paragraph per row, as in HTML import. Images come back as assets.
func FromDOCX(data []byte) (Node, []Asset, error) {
zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
return Node{}, nil, fmt.Errorf("not a Word file: %w", err)
}
files := map[string]*zip.File{}
for _, f := range zr.File {
files[strings.TrimPrefix(f.Name, "/")] = f
}
part := func(name string) (*xnode, error) {
f := files[name]
if f == nil {
return nil, nil
}
b, err := readZipFile(f, maxDocxPart)
if err != nil {
return nil, err
}
return parseXML(b)
}
body, err := part("word/document.xml")
if err != nil {
return Node{}, nil, err
}
if body == nil {
return Node{}, nil, errors.New("not a Word file: word/document.xml is missing")
}
d := &docxReader{files: files, rels: map[string]rel{}, styles: map[string]docxStyle{}, numFmt: map[string]bool{}}
if x, err := part("word/_rels/document.xml.rels"); err == nil && x != nil {
for _, r := range x.find("Relationships").kids {
d.rels[r.attrs["Id"]] = rel{target: r.attrs["Target"], external: r.attrs["TargetMode"] == "External"}
}
}
if x, err := part("word/styles.xml"); err == nil && x != nil {
d.readStyles(x)
}
if x, err := part("word/numbering.xml"); err == nil && x != nil {
d.readNumbering(x)
}
b := body.find("body")
if b == nil {
return Node{}, nil, errors.New("not a Word file: the document has no body")
}
doc := Node{Type: "doc", Content: d.blocks(b.kids)}
if d.err != nil {
return Node{}, nil, d.err
}
if len(doc.Content) == 0 {
doc.Content = []Node{{Type: "paragraph"}}
}
return doc, d.assets, nil
}
type rel struct {
target string
external bool
}
type docxStyle struct {
name string
basedOn string
outline int // heading level from w:outlineLvl, 0 when none
numID string
}
type docxReader struct {
files map[string]*zip.File
rels map[string]rel
styles map[string]docxStyle
// numFmt is true for an ordered list level, keyed "numId/ilvl".
numFmt map[string]bool
assets []Asset
images map[string]string // zip path -> asset ref
err error
}
func (d *docxReader) readStyles(x *xnode) {
root := x.find("styles")
if root == nil {
return
}
for _, s := range root.kids {
if s.name != "style" || s.attrs["type"] != "paragraph" {
continue
}
st := docxStyle{name: strings.ToLower(s.val("name")), basedOn: s.val("basedOn")}
if ppr := s.child("pPr"); ppr != nil {
if v, err := strconv.Atoi(ppr.val("outlineLvl")); err == nil && v < 9 {
st.outline = v + 1
}
if np := ppr.child("numPr"); np != nil {
st.numID = np.val("numId")
}
}
d.styles[s.attrs["styleId"]] = st
}
}
func (d *docxReader) readNumbering(x *xnode) {
root := x.find("numbering")
if root == nil {
return
}
abstract := map[string]map[string]bool{}
for _, a := range root.kids {
if a.name != "abstractNum" {
continue
}
levels := map[string]bool{}
for _, l := range a.kids {
if l.name == "lvl" {
f := l.val("numFmt")
levels[l.attrs["ilvl"]] = f != "" && f != "bullet" && f != "none"
}
}
abstract[a.attrs["abstractNumId"]] = levels
}
for _, n := range root.kids {
if n.name != "num" {
continue
}
for lvl, ordered := range abstract[n.val("abstractNumId")] {
d.numFmt[n.attrs["numId"]+"/"+lvl] = ordered
}
}
}
// style resolves a paragraph style through basedOn, with a depth guard
// against style loops.
func (d *docxReader) style(id string) (name string, outline int, numID string) {
for i := 0; id != "" && i < 10; i++ {
st, ok := d.styles[id]
if !ok {
break
}
if name == "" {
name = st.name
}
if outline == 0 {
outline = st.outline
}
if numID == "" {
numID = st.numID
}
id = st.basedOn
}
if name == "" {
name = strings.ToLower(id)
}
return name, outline, numID
}
var headingStyle = regexp.MustCompile(`^heading\s*([1-9])$`)
// para is a Word paragraph after its style is known.
type para struct {
kind string // paragraph, heading, quote, code, list
level int // heading level, or list depth
ordered bool
inline []Node
text string // code paragraphs keep their plain text
blocks []Node // images and other blocks lifted out of the paragraph
}
func (d *docxReader) blocks(nodes []*xnode) []Node {
var out []Node
var list []para
var code []string
flushList := func() {
for len(list) > 0 {
var l Node
l, list = buildList(list, list[0].level)
out = append(out, l)
}
}
flushCode := func() {
if code != nil {
c := Node{Type: "codeBlock", Attrs: map[string]any{"language": nil}}
if t := strings.Join(code, "\n"); t != "" {
c.Content = []Node{{Type: "text", Text: t}}
}
out = append(out, c)
code = nil
}
}
for _, n := range nodes {
switch n.name {
case "p":
p := d.paragraph(n)
if p.kind != "list" {
flushList()
}
if p.kind != "code" {
flushCode()
}
switch p.kind {
case "list":
list = append(list, p)
case "code":
code = append(code, p.text)
case "heading":
if inl := trimInline(p.inline); len(inl) > 0 {
out = append(out, Node{Type: "heading", Attrs: map[string]any{"level": float64(min(p.level, 3))}, Content: inl})
}
case "quote":
if inl := trimInline(p.inline); len(inl) > 0 {
q := Node{Type: "paragraph", Content: inl}
if l := len(out) - 1; l >= 0 && out[l].Type == "blockquote" {
out[l].Content = append(out[l].Content, q)
} else {
out = append(out, Node{Type: "blockquote", Content: []Node{q}})
}
}
default:
if inl := trimInline(p.inline); len(inl) > 0 {
out = append(out, Node{Type: "paragraph", Content: inl})
}
}
out = append(out, p.blocks...)
case "tbl":
flushList()
flushCode()
out = append(out, d.table(n)...)
case "sdt":
flushList()
flushCode()
out = append(out, d.blocks(n.child("sdtContent").kidsOrNil())...)
}
}
flushList()
flushCode()
return out
}
func (n *xnode) kidsOrNil() []*xnode {
if n == nil {
return nil
}
return n.kids
}
func (d *docxReader) table(t *xnode) []Node {
var out []Node
for _, tr := range t.kids {
if tr.name != "tr" {
continue
}
var cells []Node
for _, tc := range tr.kids {
if tc.name != "tc" {
continue
}
var cell []Node
for _, b := range d.blocks(tc.kids) {
if len(cell) > 0 {
cell = append(cell, Node{Type: "text", Text: " "})
}
if b.Type == "image" {
out = append(out, b)
continue
}
cell = append(cell, inlineOf(b)...)
}
if len(cells) > 0 {
cells = append(cells, Node{Type: "text", Text: " · "})
}
cells = append(cells, cell...)
}
if c := trimInline(cells); len(c) > 0 {
out = append(out, Node{Type: "paragraph", Content: c})
}
}
return out
}
// inlineOf flattens a block to its inline content.
func inlineOf(b Node) []Node {
switch b.Type {
case "paragraph", "heading":
return b.Content
case "text", "hardBreak":
return []Node{b}
}
var out []Node
for _, c := range b.Content {
if len(out) > 0 && (c.Type == "paragraph" || c.Type == "listItem") {
out = append(out, Node{Type: "text", Text: " "})
}
out = append(out, inlineOf(c)...)
}
return out
}
func (d *docxReader) paragraph(p *xnode) para {
ppr := p.child("pPr")
name, outline, styleNum := d.style(ppr.val("pStyle"))
out := para{kind: "paragraph"}
if v, err := strconv.Atoi(ppr.val("outlineLvl")); err == nil && v < 9 {
outline = v + 1
}
switch {
case name == "title":
out.kind, out.level = "heading", 1
case headingStyle.MatchString(name):
lvl, _ := strconv.Atoi(headingStyle.FindStringSubmatch(name)[1])
out.kind, out.level = "heading", lvl
case outline > 0:
out.kind, out.level = "heading", outline
case name == "subtitle":
out.kind, out.level = "heading", 2
case strings.Contains(name, "quote"):
out.kind = "quote"
case strings.Contains(name, "code") || strings.Contains(name, "preformatted") || name == "source":
out.kind = "code"
}
numID, ilvl := styleNum, "0"
if np := ppr.child("numPr"); np != nil {
if v := np.val("numId"); v != "" {
numID = v
}
if v := np.val("ilvl"); v != "" {
ilvl = v
}
}
if numID != "" && numID != "0" && out.kind == "paragraph" {
out.kind = "list"
out.level, _ = strconv.Atoi(ilvl)
ordered, known := d.numFmt[numID+"/"+ilvl]
if !known {
ordered = strings.Contains(name, "number")
}
out.ordered = ordered
}
r := &runReader{d: d}
r.children(p.kids, nil)
out.inline, out.blocks = r.inline, r.blocks
if out.kind == "code" {
out.text = PlainText(Node{Content: r.inline})
}
return out
}
// buildList nests list paragraphs by depth, starting a new list where the
// kind (bulleted or numbered) changes.
func buildList(items []para, level int) (Node, []para) {
list := newList(items[0].ordered)
for len(items) > 0 {
it := items[0]
if it.level < level {
break
}
if it.level == level {
if it.ordered != (list.Type == "orderedList") {
break
}
p := Node{Type: "paragraph", Content: trimInline(it.inline)}
item := Node{Type: "listItem", Content: append([]Node{p}, it.blocks...)}
list.Content = append(list.Content, item)
items = items[1:]
continue
}
var sub Node
sub, items = buildList(items, it.level)
if len(list.Content) == 0 {
list.Content = []Node{{Type: "listItem", Content: []Node{{Type: "paragraph"}}}}
}
last := &list.Content[len(list.Content)-1]
last.Content = append(last.Content, sub)
}
return list, items
}
func newList(ordered bool) Node {
if ordered {
return Node{Type: "orderedList", Attrs: map[string]any{"start": float64(1)}}
}
return Node{Type: "bulletList"}
}
// runReader collects a paragraph's runs, following hyperlinks (both
// <w:hyperlink> and HYPERLINK fields) and lifting images out as blocks.
type runReader struct {
d *docxReader
inline []Node
blocks []Node
// A complex field: instr gathers the instruction, link is its target
// once the field's result starts.
inField bool
instr string
link string
}
var hyperlinkField = regexp.MustCompile(`^\s*HYPERLINK\s+"([^"]+)"`)
var monoFont = regexp.MustCompile(`(?i)courier|consolas|mono|menlo|monaco`)
func (r *runReader) children(nodes []*xnode, marks []Mark) {
for _, n := range nodes {
switch n.name {
case "r":
r.run(n, marks)
case "hyperlink":
m := marks
if rl, ok := r.d.rels[n.attrs["id"]]; ok && rl.external && safeURL.MatchString(rl.target) {
m = withLink(marks, rl.target)
}
r.children(n.kids, m)
case "fldSimple":
m := marks
if f := hyperlinkField.FindStringSubmatch(n.attrs["instr"]); f != nil && safeURL.MatchString(f[1]) {
m = withLink(marks, f[1])
}
r.children(n.kids, m)
case "smartTag", "customXml", "ins", "sdt", "sdtContent":
r.children(n.kids, marks)
}
}
}
func withLink(marks []Mark, href string) []Mark {
return append(append([]Mark(nil), marks...), Mark{Type: "link", Attrs: map[string]any{
"href": href, "target": "_blank", "rel": "noopener noreferrer nofollow", "class": nil,
}})
}
func (r *runReader) run(n *xnode, marks []Mark) {
rpr := n.child("rPr")
add := func(t string) {
for _, m := range marks {
if m.Type == t {
return
}
}
marks = append(append([]Mark(nil), marks...), Mark{Type: t})
}
if rpr != nil {
if rpr.on("b") {
add("bold")
}
if rpr.on("i") {
add("italic")
}
if u := rpr.child("u"); u != nil && u.attrs["val"] != "none" && u.attrs["val"] != "0" {
add("underline")
}
if rpr.on("strike") || rpr.on("dstrike") {
add("strike")
}
if f := rpr.child("rFonts"); f != nil && monoFont.MatchString(f.attrs["ascii"]) {
add("code")
}
if s := strings.ToLower(rpr.val("rStyle")); strings.Contains(s, "code") {
add("code")
}
}
if r.link != "" {
marks = withLink(marks, r.link)
}
for _, c := range n.kids {
switch c.name {
case "fldChar":
switch c.attrs["fldCharType"] {
case "begin":
r.inField, r.instr, r.link = true, "", ""
case "separate":
if f := hyperlinkField.FindStringSubmatch(r.instr); f != nil && safeURL.MatchString(f[1]) {
r.link = f[1]
}
r.inField = false
case "end":
r.inField, r.link = false, ""
}
case "instrText":
if r.inField {
r.instr += c.text
}
case "t":
if !r.inField && c.text != "" {
r.inline = append(r.inline, Node{Type: "text", Text: c.text, Marks: marks})
}
case "tab":
r.inline = append(r.inline, Node{Type: "text", Text: " ", Marks: marks})
case "br", "cr":
if c.attrs["type"] != "page" && c.attrs["type"] != "column" {
r.inline = append(r.inline, Node{Type: "hardBreak"})
}
case "drawing", "pict":
r.image(c)
}
}
}
func (r *runReader) image(n *xnode) {
id := ""
if blip := n.find("blip"); blip != nil {
id = blip.attrs["embed"]
} else if im := n.find("imagedata"); im != nil {
id = im.attrs["id"]
}
rl, ok := r.d.rels[id]
if !ok || rl.external {
return
}
alt := ""
if dp := n.find("docPr"); dp != nil {
alt = dp.attrs["descr"]
}
ref := r.d.asset(path.Clean(path.Join("word", rl.target)))
if ref == "" {
return
}
r.blocks = append(r.blocks, Node{Type: "image", Attrs: map[string]any{"src": ref, "alt": alt, "title": nil}})
}
// asset adds a file from the archive (once) and returns its ref, or "".
func (d *docxReader) asset(name string) string {
if ref, ok := d.images[name]; ok {
return ref
}
f := d.files[strings.TrimPrefix(name, "/")]
if f == nil {
return ""
}
data, err := readZipFile(f, maxDocxPart)
if err != nil {
if d.err == nil && errors.Is(err, ErrTooLarge) {
d.err = err
}
return ""
}
if d.images == nil {
d.images = map[string]string{}
}
ref := AssetRef(len(d.assets))
d.assets = append(d.assets, Asset{Ref: ref, Name: path.Base(name), Data: data})
d.images[name] = ref
return ref
}