1
0
mirror of https://github.com/fumiama/go-docx.git synced 2026-06-11 11:04:54 +08:00

feat: embed template xmls

This commit is contained in:
源文雨
2023-02-09 14:05:31 +08:00
parent 20d91d61a4
commit 2d8e706815
17 changed files with 481 additions and 429 deletions

40
pack.go
View File

@@ -2,29 +2,37 @@ package docxlib
import (
"archive/zip"
"bytes"
"encoding/xml"
"strings"
)
// This receives a zip file writer (word documents are a zip with multiple xml inside)
// and writes the relevant files. Some of them come from the empty_constants file,
// others from the actual in-memory structure
func (f *Docx) pack(zipWriter *zip.Writer) (err error) {
files := map[string]string{}
fileslst := []string{
"_rels/.rels",
"docProps/app.xml",
"docProps/core.xml",
"word/theme/theme1.xml",
"word/styles.xml",
"[Content_Types].xml",
}
files := make(map[string][]byte, 64)
files["_rels/.rels"] = TEMP_REL
files["docProps/app.xml"] = TEMP_DOCPROPS_APP
files["docProps/core.xml"] = TEMP_DOCPROPS_CORE
files["word/theme/theme1.xml"] = TEMP_WORD_THEME_THEME
files["word/styles.xml"] = TEMP_WORD_STYLE
files["[Content_Types].xml"] = TEMP_CONTENT
for _, name := range fileslst {
files[name], err = TEMP_XML_FS.ReadFile("xml/" + name)
if err != nil {
return
}
}
files["word/_rels/document.xml.rels"], err = marshal(f.DocRelation)
if err != nil {
return err
return
}
files["word/document.xml"], err = marshal(f.Document)
if err != nil {
return err
return
}
for path, data := range files {
@@ -33,7 +41,7 @@ func (f *Docx) pack(zipWriter *zip.Writer) (err error) {
return err
}
_, err = w.Write(StringToBytes(data))
_, err = w.Write(data)
if err != nil {
return err
}
@@ -42,13 +50,13 @@ func (f *Docx) pack(zipWriter *zip.Writer) (err error) {
return
}
func marshal(data interface{}) (out string, err error) {
sb := strings.Builder{}
sb.WriteString(xml.Header)
err = xml.NewEncoder(&sb).Encode(data)
func marshal(data interface{}) (out []byte, err error) {
buf := bytes.NewBuffer(make([]byte, 0, 1024))
buf.WriteString(xml.Header)
err = xml.NewEncoder(buf).Encode(data)
if err != nil {
return
}
out = sb.String()
out = buf.Bytes()
return
}