forked from robarchibald/pdf2txt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
extract.go
111 lines (97 loc) · 2.54 KB
/
extract.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
package pdf2txt
import (
"fmt"
"io/ioutil"
"os"
"path"
"github.com/robarchibald/peekingReader"
)
// extract the compressed streams into text files for debugging
func extract(filename string) error {
f, err := os.Open(filename)
if err != nil {
return err
}
fileWithoutExt := path.Base(filename)[:len(path.Base(filename))-len(path.Ext(filename))]
outDir := path.Join(path.Dir(filename), fileWithoutExt)
os.Mkdir(outDir, 0755)
uncategorized := make(map[string]*object)
contents := []string{}
fonts := make(map[string]*font)
toUnicode := []string{}
var decodeError error
tchan := make(chan interface{}, 15)
go tokenize(peekingReader.NewBufReader(f), tchan)
for t := range tchan {
switch v := t.(type) {
case error:
return v
case *object:
oType := v.name("/Type")
switch oType {
case "/Page":
page := v.getPage()
contents = append(contents, page.Contents...)
case "/Font":
if _, ok := fonts[v.refString]; !ok {
font := v.getFont()
fonts[v.refString] = font
if font.ToUnicode != "" {
toUnicode = append(toUnicode, font.ToUnicode)
}
}
case "/ObjStm":
if decodeError == nil {
decodeError = v.decodeStream()
}
if err := ioutil.WriteFile(path.Join(outDir, fmt.Sprintf("objStm %s.txt", v.refString)), v.stream, 0644); err != nil {
return err
}
if decodeError != nil {
continue
}
objs, err := v.getObjectStream()
if err != nil {
return err
}
for i := range objs {
err := ioutil.WriteFile(path.Join(outDir, fmt.Sprintf("decoded %s.txt", objs[i].refString)), []byte(fmt.Sprintf("%v", objs[i])), 0644)
if err != nil {
return err
}
}
default:
uncategorized[v.refString] = v
}
}
}
for i := range toUnicode {
ref := toUnicode[i]
if err := uncategorized[ref].decodeStream(); err != nil {
return err
}
if err := ioutil.WriteFile(path.Join(outDir, "toUnicode "+ref+".txt"), uncategorized[ref].stream, 0644); err != nil {
return err
}
delete(uncategorized, ref)
}
for i := range contents {
ref := contents[i]
if err := uncategorized[ref].decodeStream(); err != nil {
return err
}
if err := ioutil.WriteFile(path.Join(outDir, "contents "+ref+".txt"), uncategorized[ref].stream, 0644); err != nil {
return err
}
delete(uncategorized, ref)
}
for ref, item := range uncategorized {
if err := item.decodeStream(); err != nil {
return err
}
if err := ioutil.WriteFile(path.Join(outDir, "uncategorized "+ref+".txt"), item.stream, 0644); err != nil {
return err
}
}
return nil
}