-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdocxtpl.go
230 lines (195 loc) · 4.4 KB
/
docxtpl.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
package docxtpl
import (
"archive/zip"
"bytes"
"encoding/xml"
"fmt"
"io"
"os"
"reflect"
"text/template"
"github.com/fumiama/go-docx"
)
type DocxTmpl struct {
*docx.Docx
funcMap *template.FuncMap
contentTypes *ContentTypes
}
// Parse the document from a reader and store it in memory.
// You can it invoke from a file.
//
// reader, err := os.Open(FILE_PATH)
// if err != nil {
// panic(err)
// }
// fileinfo, err := reader.Stat()
// if err != nil {
// panic(err)
// }
// size := fileinfo.Size()
// doc, err := docxtpl.Parse(reader, int64(size))
func Parse(reader io.ReaderAt, size int64) (*DocxTmpl, error) {
doc, err := docx.Parse(reader, size)
if err != nil {
return nil, err
}
contentTypes, err := getContentTypes(reader, size)
if err != nil {
return nil, err
}
funcMap := defaultFuncMap
return &DocxTmpl{doc, &funcMap, contentTypes}, nil
}
// Parse the document from a filename and store it in memory.
func ParseFromFilename(filename string) (*DocxTmpl, error) {
reader, err := os.Open(filename)
if err != nil {
return nil, err
}
fileinfo, err := reader.Stat()
if err != nil {
return nil, err
}
size := fileinfo.Size()
doxtpl, err := Parse(reader, size)
if err != nil {
return nil, err
}
return doxtpl, nil
}
func (d *DocxTmpl) RegisterFunction(name string, fn any) error {
if !goodName(name) {
return fmt.Errorf("function name %q is not a valid identifier", name)
}
// Check that fn is a function
v := reflect.ValueOf(fn)
if v.Kind() != reflect.Func {
return fmt.Errorf("value for " + name + " not a function")
}
// Check the function signature
err := goodFunc(name, v.Type())
if err != nil {
return err
}
// Add to the function map
(*d.funcMap)[name] = fn
return nil
}
// Replace the placeholders in the document with passed in data.
func (d *DocxTmpl) Render(data interface{}) error {
// Ensure that there are no 'part tags' in the XML document
err := d.mergeTags()
if err != nil {
return err
}
// Process the template data
proccessedData, err := d.processData(data)
if err != nil {
return err
}
// Get the document XML
documentXmlString, err := d.getDocumentXml()
if err != nil {
return err
}
// Prepare the XML for tag replacement
documentXmlString, err = prepareXmlForTagReplacement(documentXmlString)
if err != nil {
return err
}
// Replace the tags in XML
documentXmlString, err = replaceTagsInText(documentXmlString, proccessedData, d.funcMap)
if err != nil {
return err
}
// Fix any issues in the XML
documentXmlString = fixXmlIssuesPostTagReplacement(documentXmlString)
// Unmarshal the modified XML and replace the document body with it
decoder := xml.NewDecoder(bytes.NewBufferString(documentXmlString))
for {
t, err := decoder.Token()
if err == io.EOF {
break
}
if err != nil {
return err
}
if start, ok := t.(xml.StartElement); ok {
if start.Name.Local == "Body" {
clear(d.Document.Body.Items)
err = d.Document.Body.UnmarshalXML(decoder, start)
if err != nil {
return err
}
break
}
}
}
return nil
}
func (d *DocxTmpl) getDocumentXml() (string, error) {
out, err := xml.Marshal(d.Document.Body)
if err != nil {
return "", nil
}
return string(out), err
}
// Save the document to a writer.
// This could be a new file.
//
// f, err := os.Create(FILE_PATH)
// if err != nil {
// panic(err)
// }
// err = doc.Save(f)
// if err != nil {
// panic(err)
// }
// err = f.Close()
// if err != nil {
// panic(err)
// }
func (d *DocxTmpl) Save(writer io.Writer) error {
var buf bytes.Buffer
_, err := d.WriteTo(&buf)
if err != nil {
return err
}
reader := bytes.NewReader(buf.Bytes())
zipReader, err := zip.NewReader(reader, int64(buf.Len()))
if err != nil {
return err
}
generatedZip := zip.NewWriter(writer)
for _, f := range zipReader.File {
newFile, err := generatedZip.Create(f.Name)
if err != nil {
return err
}
// Override content types with out calculated types
// Copy across all other files
if f.Name == "[Content_Types].xml" {
contentTypesXml, err := d.contentTypes.marshalXml()
if err != nil {
return err
}
_, err = newFile.Write([]byte(contentTypesXml))
if err != nil {
return err
}
} else {
zf, err := f.Open()
if err != nil {
return err
}
defer zf.Close()
if _, err := io.Copy(newFile, zf); err != nil {
return err
}
}
}
if err := generatedZip.Close(); err != nil {
return err
}
return nil
}