-
Notifications
You must be signed in to change notification settings - Fork 0
/
docx.go
87 lines (76 loc) · 1.4 KB
/
docx.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
package main
import (
"archive/zip"
"bytes"
"io"
"os"
"strings"
)
type Docx struct {
files []*zip.File
content string
}
func (d *Docx) AppendText(text string) {
d.content += text
}
func (d *Docx) WriteToFile(path string) (err error) {
var target *os.File
target, err = os.Create(path)
if err != nil {
return
}
defer target.Close()
err = d.Write(target)
return
}
func (d *Docx) Write(ioWriter io.Writer) (err error) {
w := zip.NewWriter(ioWriter)
for _, file := range d.files {
var writer io.Writer
var readCloser io.ReadCloser
writer, err = w.Create(file.Name)
if err != nil {
return err
}
readCloser, err = file.Open()
if err != nil {
return err
}
if file.Name == "word/document.xml" {
writer.Write([]byte(d.content))
} else {
writer.Write(streamToByte(readCloser))
}
}
w.Close()
return
}
func streamToByte(stream io.Reader) []byte {
buf := new(bytes.Buffer)
buf.ReadFrom(stream)
return buf.Bytes()
}
func ReadDocxFromFS(file string) (*Docx, error) {
zipReader, err := zip.OpenReader(file)
if err != nil {
return nil, err
}
content := ""
for _, f := range zipReader.File {
if f.Name == "word/document.xml" {
rc, err := f.Open()
if err != nil {
return nil, err
}
buf := new(bytes.Buffer)
buf.ReadFrom(rc)
content = buf.String()
break
}
}
docx := &Docx{
files: zipReader.File,
content: content,
}
return docx, nil
}