package docx
/*
writer.go - Build a Word (.docx) file from a Document.
The input is the Docs rich HTML model (see reader.go for the
vocabulary) and every formatting decision in it is written out as
explicit WordprocessingML, so that the file lays out in Word - and back
in the editor - the way it looked in the editor:
blocks spacing before/after (margin/padding), indents, alignment,
line spacing (data-ls / data-lsexact / data-lsmin), shading,
borders, keep-with-next / keep-lines / widow control,
page-break-before and tab stops (data-tabs); headings and
the title/subtitle keep their named styles
runs font family (the first of the stack), size, weight, italic,
underline, strike-through, colour, highlight/shading,
small caps, caps, superscript/subscript, hyperlinks
(external and internal #bookmark), tabs, line breaks,
PAGE / NUMPAGES fields and footnote references
lists one numbering definition per list, with the list's own
number format, marker text, start and indents per level;
a list interrupted by a paragraph keeps counting (data-num)
tables the grid in twips, the table's indent, fixed layout, per
cell borders, margins, shading, vertical alignment, column
and row spans, row heights, cant-split and header rows
pictures inline or anchored (top-and-bottom / square wrap), with the
crop (srcRect) and the picture outline
parts rich header/footer parts with their own pictures, footnotes,
page size, margins and the header/footer distances
What the editor draws with its own CSS defaults (a heading without
inline style, a table cell without borders) is written with those
defaults, mirrored in editorBlockDefaults - change docs.css and change
them too.
*/
import (
"archive/zip"
"bytes"
"crypto/sha256"
"errors"
"fmt"
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"math"
"regexp"
"strconv"
"strings"
"golang.org/x/net/html"
"imuslab.com/arozos/mod/office/internal/fonts"
"imuslab.com/arozos/mod/office/internal/htmlutil"
"imuslab.com/arozos/mod/office/internal/media"
"imuslab.com/arozos/mod/office/internal/xmltree"
"imuslab.com/arozos/mod/office/model"
)
const docxNs = `xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"`
const (
relImage = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"
relHyperlink = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"
)
/* ---------------- CSS reading ---------------- */
// cssDecls parses an inline style attribute (later declarations win)
func cssDecls(style string) map[string]string {
out := map[string]string{}
var cur strings.Builder
quote := byte(0)
flush := func() {
decl := cur.String()
cur.Reset()
kv := strings.SplitN(decl, ":", 2)
if len(kv) != 2 {
return
}
k := strings.ToLower(strings.TrimSpace(kv[0]))
v := strings.TrimSpace(kv[1])
v = strings.TrimSuffix(strings.TrimSpace(strings.TrimSuffix(v, "!important")), ";")
if k != "" {
out[k] = v
}
}
for i := 0; i < len(style); i++ {
c := style[i]
switch {
case quote != 0:
if c == quote {
quote = 0
}
cur.WriteByte(c)
case c == '"' || c == '\'':
quote = c
cur.WriteByte(c)
case c == ';':
flush()
default:
cur.WriteByte(c)
}
}
flush()
return out
}
// cssPt converts a CSS length to points; em is relative to emPt; ok=false
// when the value is not a length
func cssPt(v string, emPt float64) (float64, bool) {
v = strings.TrimSpace(strings.ToLower(v))
if v == "" || v == "auto" || v == "normal" {
return 0, false
}
if v == "0" {
return 0, true
}
units := []struct {
suf string
k float64
}{{"pt", 1}, {"px", 0.75}, {"mm", 72 / 25.4}, {"cm", 72 / 2.54}, {"in", 72}, {"em", 0}, {"rem", 11}}
for _, u := range units {
if strings.HasSuffix(v, u.suf) {
n, err := strconv.ParseFloat(strings.TrimSpace(strings.TrimSuffix(v, u.suf)), 64)
if err != nil {
return 0, false
}
if u.suf == "em" {
return n * emPt, true
}
return n * u.k, true
}
}
if n, err := strconv.ParseFloat(v, 64); err == nil {
return n * 0.75, true
}
return 0, false
}
// cssFontSizePt resolves font-size (absolute, %, em, keywords)
func cssFontSizePt(v string, parentPt float64) (float64, bool) {
v = strings.TrimSpace(strings.ToLower(v))
if strings.HasSuffix(v, "%") {
if n, err := strconv.ParseFloat(strings.TrimSuffix(v, "%"), 64); err == nil {
return parentPt * n / 100, true
}
return 0, false
}
switch v {
case "smaller":
return parentPt * 0.83, true
case "larger":
return parentPt * 1.2, true
case "xx-small":
return 7, true
case "x-small":
return 7.5, true
case "small":
return 10, true
case "medium":
return 12, true
case "large":
return 13.5, true
case "x-large":
return 18, true
case "xx-large":
return 24, true
case "xxx-large":
return 36, true
}
return cssPt(v, parentPt)
}
// cssBorder parses "1pt solid #000" into a Word border (sz in eighths)
type wBorder struct {
val string
sz int
color string
space float64 // pt between a paragraph border and its text
}
func cssBorder(v string) (wBorder, bool) {
v = strings.TrimSpace(strings.ToLower(v))
if v == "" {
return wBorder{}, false
}
if v == "none" || v == "0" || strings.HasPrefix(v, "none ") || strings.Contains(v, " none") || v == "hidden" {
return wBorder{val: "nil"}, true
}
b := wBorder{val: "single", sz: 4, color: "000000"}
for _, tok := range splitCSSValue(v) {
switch tok {
case "solid":
b.val = "single"
case "dotted":
b.val = "dotted"
case "dashed":
b.val = "dashed"
case "double":
b.val = "double"
case "thin":
b.sz = 4
case "medium":
b.sz = 12
case "thick":
b.sz = 18
default:
if pt, ok := cssPt(tok, 11); ok {
b.sz = int(math.Round(pt * 8))
if b.sz < 2 {
b.sz = 2
}
if pt == 0 {
return wBorder{val: "nil"}, true
}
continue
}
if c := htmlutil.CSSColorHex(tok); c != "" {
b.color = c
}
}
}
return b, true
}
/*
cssBorderSides reads the borders a style gives each side, the way CSS
cascades them: the border shorthand, each side's own shorthand, then the
longhands - border-width / -style / -color with one to four values, which is
how the browser writes a uniform border back once it has been edited, and
the per-side ones. Only the sides the style mentions are returned; a side
given a width or colour but never a style has none, as in CSS.
*/
func cssBorderSides(css map[string]string) map[string]wBorder {
sides := []string{"top", "right", "bottom", "left"}
out := map[string]wBorder{}
if v, ok := css["border"]; ok {
if bd, ok := cssBorder(v); ok {
for _, side := range sides {
out[side] = bd
}
}
}
for _, side := range sides {
if v, ok := css["border-"+side]; ok {
if bd, ok := cssBorder(v); ok {
out[side] = bd
}
}
}
set := func(side, prop, v string) {
v = strings.TrimSpace(strings.ToLower(v))
bd, ok := out[side]
if !ok {
bd = wBorder{sz: 4, color: "000000"} // no style yet
}
switch prop {
case "style":
switch v {
case "none", "hidden":
bd.val = "nil"
case "dotted", "dashed", "double":
bd.val = v
default:
bd.val = "single"
}
case "width":
switch v {
case "thin":
bd.sz = 4
case "medium":
bd.sz = 12
case "thick":
bd.sz = 18
default:
if pt, ok := cssPt(v, 11); ok {
if pt == 0 {
bd.val = "nil"
}
bd.sz = int(math.Max(2, math.Round(pt*8)))
}
}
case "color":
if c := htmlutil.CSSColorHex(v); c != "" {
bd.color = c
}
}
out[side] = bd
}
for _, prop := range []string{"style", "width", "color"} {
if v, ok := css["border-"+prop]; ok {
vals := splitCSSValue(strings.TrimSpace(v))
for i, side := range sides {
// 1 to 4 values, top right bottom left, as in padding
switch len(vals) {
case 1:
set(side, prop, vals[0])
case 2:
set(side, prop, vals[i%2])
case 3:
set(side, prop, vals[[]int{0, 1, 2, 1}[i]])
case 4:
set(side, prop, vals[i])
}
}
}
for _, side := range sides {
if v, ok := css["border-"+side+"-"+prop]; ok {
set(side, prop, v)
}
}
}
for side, bd := range out {
if bd.val == "" {
delete(out, side)
}
}
return out
}
// borderSpace is a border's w:space: whole points, 0 to 31
func borderSpace(pt float64) int {
return int(math.Max(0, math.Min(31, math.Round(pt))))
}
// splitCSSValue splits a shorthand on spaces, keeping rgb(...) whole
func splitCSSValue(v string) []string {
var out []string
depth := 0
var cur strings.Builder
for _, r := range v {
switch {
case r == '(':
depth++
cur.WriteRune(r)
case r == ')':
depth--
cur.WriteRune(r)
case r == ' ' && depth == 0:
if cur.Len() > 0 {
out = append(out, cur.String())
cur.Reset()
}
default:
cur.WriteRune(r)
}
}
if cur.Len() > 0 {
out = append(out, cur.String())
}
return out
}
// boxSides expands a 1-4 value shorthand (padding, margin) into t r b l
func boxSides(v string, emPt float64) ([4]float64, bool) {
var out [4]float64
toks := splitCSSValue(strings.TrimSpace(v))
var vals []float64
for _, t := range toks {
pt, ok := cssPt(t, emPt)
if !ok {
return out, false
}
vals = append(vals, pt)
}
switch len(vals) {
case 1:
out = [4]float64{vals[0], vals[0], vals[0], vals[0]}
case 2:
out = [4]float64{vals[0], vals[1], vals[0], vals[1]}
case 3:
out = [4]float64{vals[0], vals[1], vals[2], vals[1]}
case 4:
out = [4]float64{vals[0], vals[1], vals[2], vals[3]}
default:
return out, false
}
return out, true
}
func twip(pt float64) int { return int(math.Round(pt * 20)) }
func hasClass(n *html.Node, cls string) bool {
return strings.Contains(" "+htmlutil.Attr(n, "class")+" ", " "+cls+" ")
}
/* ---------------- inherited formatting ---------------- */
type wRunStyle struct {
font string
sizePt float64
bold, italic bool
underline, strike bool
smallCaps, caps bool
color string // RRGGBB
shade string // RRGGBB background
vert string // superscript | subscript
preWrap bool
link string
}
// applyBlockCSS folds a container's inline style into the run style; its
// background belongs to the paragraph or cell, not to every run inside
func (rs wRunStyle) applyBlockCSS(css map[string]string) wRunStyle {
if _, ok := css["background-color"]; !ok {
return rs.applyCSS(css)
}
own := make(map[string]string, len(css))
for k, v := range css {
if k != "background-color" {
own[k] = v
}
}
return rs.applyCSS(own)
}
// applyCSS folds an element's inline style into the inherited run style
func (rs wRunStyle) applyCSS(css map[string]string) wRunStyle {
if v, ok := css["font-family"]; ok {
if f := fonts.FirstFamily(v); f != "" {
rs.font = f
}
}
if v, ok := css["font-size"]; ok {
if pt, ok := cssFontSizePt(v, rs.sizePt); ok && pt > 0 {
rs.sizePt = pt
}
}
if v, ok := css["font-weight"]; ok {
switch v {
case "bold", "bolder", "600", "700", "800", "900":
rs.bold = true
case "normal", "lighter", "100", "200", "300", "400", "500":
rs.bold = false
}
}
if v, ok := css["font-style"]; ok {
rs.italic = v == "italic" || v == "oblique"
}
for _, k := range []string{"text-decoration", "text-decoration-line"} {
if v, ok := css[k]; ok {
if v == "none" {
rs.underline, rs.strike = false, false
} else {
if strings.Contains(v, "underline") {
rs.underline = true
}
if strings.Contains(v, "line-through") {
rs.strike = true
}
}
}
}
if v, ok := css["color"]; ok && v != "inherit" {
if c := htmlutil.CSSColorHex(v); c != "" {
rs.color = c
}
}
if v, ok := css["background-color"]; ok {
rs.shade = htmlutil.CSSColorHex(v)
}
if v, ok := css["font-variant"]; ok {
rs.smallCaps = strings.Contains(v, "small-caps")
}
if v, ok := css["text-transform"]; ok {
rs.caps = v == "uppercase"
}
if v, ok := css["white-space"]; ok {
rs.preWrap = strings.HasPrefix(v, "pre") || v == "break-spaces"
}
return rs
}
func (rs wRunStyle) rPr() string {
var sb strings.Builder
sb.WriteString("")
if rs.font != "" {
f := xmltree.Escape(rs.font)
sb.WriteString(``)
}
if rs.bold {
sb.WriteString(``)
} else {
sb.WriteString(``)
}
if rs.italic {
sb.WriteString(``)
} else {
sb.WriteString(``)
}
if rs.caps {
sb.WriteString(``)
}
if rs.smallCaps {
sb.WriteString(``)
}
if rs.strike {
sb.WriteString(``)
}
col := rs.color
if col == "" {
col = "000000"
}
sb.WriteString(``)
if rs.sizePt > 0 {
hp := int(math.Round(rs.sizePt * 2))
sb.WriteString(fmt.Sprintf(``, hp, hp))
}
if rs.underline {
sb.WriteString(``)
} else {
sb.WriteString(``)
}
if rs.shade != "" {
sb.WriteString(``)
}
if rs.vert != "" {
sb.WriteString(``)
}
sb.WriteString("")
return sb.String()
}
/*
The editor's own look for elements that state nothing (docs.css). The
writer starts every element from these, then applies its inline style.
*/
type blockDefault struct {
sizePt, beforePt, afterPt float64
bold, italic bool
color string
style string
}
var editorBlockDefaults = map[string]blockDefault{
"p": {sizePt: 11, color: "000000"},
"h1": {sizePt: 20, beforePt: 14, afterPt: 6, bold: true, color: "1F2328", style: "Heading1"},
"h2": {sizePt: 16, beforePt: 14, afterPt: 6, bold: true, color: "1F2328", style: "Heading2"},
"h3": {sizePt: 13, beforePt: 14, afterPt: 6, bold: true, color: "1F2328", style: "Heading3"},
"h4": {sizePt: 11, beforePt: 14, afterPt: 6, bold: true, italic: true, color: "1F2328", style: "Heading4"},
"h5": {sizePt: 11, beforePt: 14, afterPt: 6, bold: true, color: "1F2328", style: "Heading5"},
"h6": {sizePt: 11, beforePt: 14, afterPt: 6, bold: true, italic: true, color: "1F2328", style: "Heading6"},
"doc-title": {sizePt: 26, afterPt: 12, color: "1F2328", style: "Title"},
"doc-subtitle": {sizePt: 15, afterPt: 16, color: "666666", style: "Subtitle"},
}
// editorBlockCSS is docs.css for the blocks it boxes (longhands only, so an
// inline shorthand can replace them): the export starts from what the
// editor draws before the element's own style is applied
var editorBlockCSS = map[string]map[string]string{
"blockquote": {
"margin-top": "8pt", "margin-bottom": "8pt",
"border-left": "3px solid #c3c7cc",
"padding-top": "2pt", "padding-bottom": "2pt", "padding-left": "12px",
"color": "#5f6368",
},
"pre": {
"margin-top": "8pt", "margin-bottom": "8pt",
"background-color": "#f1f3f4",
"border-top": "1px solid #e2e5e9", "border-right": "1px solid #e2e5e9",
"border-bottom": "1px solid #e2e5e9", "border-left": "1px solid #e2e5e9",
"padding-top": "10px", "padding-right": "12px", "padding-bottom": "10px", "padding-left": "12px",
"font-family": "Consolas, 'Courier New', monospace", "font-size": "10pt",
"white-space": "pre-wrap",
},
}
// withDefaultCSS lays an element's inline declarations over defaults; a
// shorthand ("margin", "border") replaces the defaults it covers
func withDefaultCSS(defaults, inline map[string]string) map[string]string {
out := make(map[string]string, len(defaults)+len(inline))
for k, v := range defaults {
out[k] = v
}
for k := range inline {
for d := range defaults {
if strings.HasPrefix(d, k+"-") {
delete(out, d)
}
}
}
for k, v := range inline {
out[k] = v
}
return out
}
/* ---------------- relationships and media ---------------- */
type docxPart struct {
rels []string
next int
}
func (p *docxPart) add(typ, target string, external bool) string {
p.next++
id := fmt.Sprintf("rId%d", 100+p.next)
mode := ""
if external {
mode = ` TargetMode="External"`
}
p.rels = append(p.rels, ``)
return id
}
func (p *docxPart) relsXML(fixed string) string {
return `` + "\n" +
`` +
fixed + strings.Join(p.rels, "") + ``
}
/* ---------------- numbering ---------------- */
type numLevelDef struct {
fmt, text string
start int
leftPt, hangPt float64
set bool
}
type numInstance struct {
id int
levels [9]numLevelDef
}
type docxNumbering struct {
list []*numInstance
byKey map[string]*numInstance
}
func (nb *docxNumbering) instance(key string) *numInstance {
if nb.byKey == nil {
nb.byKey = map[string]*numInstance{}
}
if key != "" {
if in, ok := nb.byKey[key]; ok {
return in
}
}
in := &numInstance{id: len(nb.list) + 1}
nb.list = append(nb.list, in)
if key != "" {
nb.byKey[key] = in
}
return in
}
func (nb *docxNumbering) xml() string {
var sb strings.Builder
sb.WriteString(`` + "\n")
sb.WriteString(``)
for _, in := range nb.list {
sb.WriteString(fmt.Sprintf(``, in.id))
for l := 0; l < 9; l++ {
d := in.levels[l]
if !d.set {
d = defaultNumLevel(in.levels[0].fmt == "bullet", l)
}
start := d.start
if start < 0 {
start = 1
}
sb.WriteString(fmt.Sprintf(``+
``,
l, start, d.fmt, xmltree.Escape(d.text), twip(d.leftPt), twip(d.hangPt)))
if d.fmt == "bullet" {
sb.WriteString(``)
}
sb.WriteString(``)
}
sb.WriteString(``)
}
for _, in := range nb.list {
sb.WriteString(fmt.Sprintf(``, in.id, in.id))
}
sb.WriteString(``)
return sb.String()
}
var defaultBullets = []string{"\u25cf", "\u25cb", "\u25a0"}
var defaultOrdered = []string{"decimal", "lowerLetter", "lowerRoman"}
func defaultNumLevel(bullet bool, level int) numLevelDef {
d := numLevelDef{start: 1, leftPt: float64(level+1) * 36, hangPt: 18, set: true}
if bullet {
d.fmt = "bullet"
d.text = defaultBullets[level%3]
} else {
d.fmt = defaultOrdered[level%3]
d.text = "%" + strconv.Itoa(level+1) + "."
}
return d
}
/* ---------------- the builder ---------------- */
type docxBuilder struct {
doc *model.Document
textWPt float64 // the width a block at hand may take (a column or the page)
// the indent of the containers the block at hand sits in
containerLeft, containerRight float64
fullWPt float64 // the page's text width
colWPt float64 // one column of a multi-column page
media []media.Entry
imgCount int
mediaByHash map[[32]byte]int
// resolves the media?file= links pictures carry (nil = data URLs only)
readVpath func(string) ([]byte, error)
// review markup (review.go): pieces per comment anchor, pieces
// written so far, Word ids, and the revision counter
cmtTotal map[string]int
cmtSeen map[string]int
cmtWordID map[string]int
cmtOrder []*model.DocComment
revID int
inRev bool
docPrID int
num docxNumbering
fnIDs map[string]int
fnOrder []string
bookmarkN int
// multi-column documents: blocks with class "col-span-all" (IEEE-style
// title/author rows) are emitted into their own single-column section,
// separated from the columned body by a continuous section break
multiCol bool
sectDivider string
lastSpan bool
anyBlock bool
usedDivider bool
// runs the next paragraph writes before and after its text: the
// begin and end of a table of contents' TOC field
paraPre, paraPost string
}
// Build serializes a Document into a complete .docx file; pictures
// must be inline data URLs
func Build(doc *model.Document) ([]byte, error) {
return BuildMedia(doc, nil)
}
// BuildMedia serializes a Document, reading pictures that are
// media?file= links through readVpath
func BuildMedia(doc *model.Document, readVpath func(string) ([]byte, error)) ([]byte, error) {
if doc == nil {
return nil, errors.New("nil document")
}
b := &docxBuilder{doc: doc, fnIDs: map[string]int{}, mediaByHash: map[[32]byte]int{}, readVpath: readVpath,
cmtTotal: map[string]int{}, cmtSeen: map[string]int{}, cmtWordID: map[string]int{}}
b.fullWPt = textWidthPt(doc.Page)
b.colWPt = b.fullWPt
b.textWPt = b.fullWPt
if doc.Page != nil && doc.Page.Columns > 1 {
// a block inside the column flow is as wide as one column
gap := doc.Page.ColGap * 72 / 25.4
b.colWPt = (b.fullWPt - gap*float64(doc.Page.Columns-1)) / float64(doc.Page.Columns)
b.multiCol = true
b.sectDivider = `` +
pgGeometry(doc.Page) + ``
}
docPart := &docxPart{}
body, err := b.convertBlocks(doc.HTML, docPart, true)
if err != nil {
return nil, err
}
// header / footer parts, each with its own relationships
hfOn := doc.HFMode != model.HFModeNone
type hfOut struct {
xml string
part *docxPart
}
var header, footer *hfOut
if hfOn {
if h := b.hfBody(doc.HeaderHTML, doc.Header, false); h != nil {
header = &hfOut{xml: h.xml, part: h.part}
}
}
if f := b.hfBody(doc.FooterHTML, doc.Footer, doc.PageNumbers); f != nil {
if !hfOn {
// "none" drops the text but a page counter is its own setting
f = b.hfBody("", "", doc.PageNumbers)
}
if f != nil {
footer = &hfOut{xml: f.xml, part: f.part}
}
}
// footnotes referenced by the text (and the notes inside them)
var fnXML string
fnPart := &docxPart{}
if len(b.fnOrder) > 0 {
fnXML, err = b.footnotesXML(fnPart)
if err != nil {
return nil, err
}
}
cmtXML, cmtExtXML := b.commentsXML()
buf := new(bytes.Buffer)
zw := zip.NewWriter(buf)
add := func(name string, data []byte) error {
w, err := zw.Create(name)
if err != nil {
return err
}
_, err = w.Write(data)
return err
}
addS := func(name, content string) error { return add(name, []byte(content)) }
var ct strings.Builder
ct.WriteString(`` + "\n")
ct.WriteString(``)
ct.WriteString(``)
ct.WriteString(``)
ct.WriteString(``)
ct.WriteString(``)
ct.WriteString(``)
ct.WriteString(``)
ct.WriteString(``)
ct.WriteString(``)
ct.WriteString(``)
if header != nil {
ct.WriteString(``)
}
if footer != nil {
ct.WriteString(``)
}
if fnXML != "" {
ct.WriteString(``)
}
if cmtXML != "" {
ct.WriteString(``)
}
if cmtExtXML != "" {
ct.WriteString(``)
}
ct.WriteString(``)
if err := addS("[Content_Types].xml", ct.String()); err != nil {
return nil, err
}
if err := addS("_rels/.rels", ``+"\n"+
``+
``+
``); err != nil {
return nil, err
}
fixed := `` +
`` +
``
headerRef, footerRef := "", ""
if header != nil {
fixed += ``
headerRef = ``
}
if footer != nil {
fixed += ``
footerRef = ``
}
if fnXML != "" {
fixed += ``
}
if cmtXML != "" {
fixed += ``
}
if cmtExtXML != "" {
fixed += ``
}
if err := addS("word/_rels/document.xml.rels", docPart.relsXML(fixed)); err != nil {
return nil, err
}
sect := buildSectPr(doc.Page, headerRef, footerRef, b.usedDivider, doc.HFMode == model.HFModeExceptFirst)
if err := addS("word/document.xml", ``+"\n"+
``+body+sect+``); err != nil {
return nil, err
}
if err := addS("word/styles.xml", docxStylesXML(doc)); err != nil {
return nil, err
}
settings := docxSettings
if doc.TrackChanges {
// "Suggest edits" on: Word goes on tracking where the editor left off
settings = strings.Replace(settings, `" + src + "