-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathDOCX 2 Text.go
133 lines (110 loc) · 2.58 KB
/
DOCX 2 Text.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
/*
File Name: DOCX 2 Text.go
Copyright: 2018 Kleissner Investments s.r.o.
Author: Peter Kleissner
This code is forked from https://github.com/guylaor/goword and extracts text from DOCX files.
*/
package fileconversion
import (
"archive/zip"
"bytes"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"strings"
)
// models.go
// WordDocument is a full word doc
type WordDocument struct {
Paragraphs []WordParagraph
}
// WordParagraph is a single paragraph
type WordParagraph struct {
Style WordStyle `xml:"pPr>pStyle"`
Rows []WordRow `xml:"r"`
}
// WordStyle ...
type WordStyle struct {
Val string `xml:"val,attr"`
}
// WordRow ...
type WordRow struct {
Text string `xml:"t"`
}
// AsText returns all text in the document
func (w WordDocument) AsText() string {
text := ""
for _, v := range w.Paragraphs {
for _, rv := range v.Rows {
text += rv.Text
}
text += "\n"
}
return text
}
// goword.go
// DOCX2Text extracts text of a Word document
// Size is the full size of the input file.
func DOCX2Text(file io.ReaderAt, size int64) (string, error) {
doc, err := openWordFile(file, size)
if err != nil {
return "", err
}
docx, err := WordParse(doc)
if err != nil {
return "", err
}
return docx.AsText(), nil
}
// WordParse parses a word file
func WordParse(doc string) (WordDocument, error) {
docx := WordDocument{}
r := strings.NewReader(string(doc))
decoder := xml.NewDecoder(r)
for {
t, _ := decoder.Token()
if t == nil {
break
}
switch se := t.(type) {
case xml.StartElement:
if se.Name.Local == "p" {
var p WordParagraph
decoder.DecodeElement(&p, &se)
docx.Paragraphs = append(docx.Paragraphs, p)
}
}
}
return docx, nil
}
func openWordFile(file io.ReaderAt, size int64) (string, error) {
// Open a zip archive for reading. word files are zip archives
r, err := zip.NewReader(file, size)
if err != nil {
return "", err
}
// Iterate through the files in the archive,
// find document.xml
for _, f := range r.File {
//fmt.Printf("Contents of %s:\n", f.Name)
rc, err := f.Open()
if err != nil {
return "", err
}
defer rc.Close()
if f.Name == "word/document.xml" {
doc, err := ioutil.ReadAll(rc)
if err != nil {
return "", err
}
return fmt.Sprintf("%s", doc), nil
}
}
return "", nil
}
// IsFileDOCX checks if the data indicates a DOCX file
// DOCX has a signature of 50 4B 03 04
func IsFileDOCX(data []byte) bool {
return bytes.HasPrefix(data, []byte{0x50, 0x4B, 0x03, 0x04})
}