-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpdf.go
82 lines (67 loc) · 1.76 KB
/
pdf.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
package main
import (
"fmt"
"os/exec"
"strings"
"time"
)
type MetaResult struct {
meta map[string]string
err error
}
type BodyResult struct {
body string
err error
}
func ConvertPDFText(path string) (BodyResult, MetaResult, error) {
metaResult := MetaResult{meta: make(map[string]string)}
bodyResult := BodyResult{}
mr := make(chan MetaResult, 1)
go func() {
metaStr, err := exec.Command("pdfinfo", path).Output()
if err != nil {
metaResult.err = err
mr <- metaResult
return
}
// Parse meta output
for _, line := range strings.Split(string(metaStr), "\n") {
if parts := strings.SplitN(line, ":", 2); len(parts) > 1 {
metaResult.meta[strings.ToLower(strings.TrimSpace(parts[0]))] = strings.TrimSpace(parts[1])
}
}
// Convert parsed meta
if x, ok := metaResult.meta["ModDate"]; ok {
if t, ok := pdfTimeLayouts.Parse(x); ok {
metaResult.meta["modifiedDate"] = fmt.Sprintf("%d", t.Unix())
}
}
if x, ok := metaResult.meta["CreationDate"]; ok {
if t, ok := pdfTimeLayouts.Parse(x); ok {
metaResult.meta["createdDate"] = fmt.Sprintf("%d", t.Unix())
}
}
mr <- metaResult
}()
br := make(chan BodyResult, 1)
go func() {
body, err := exec.Command("pdftotext", "-x", "0", "-y", "50", "-W", "595", "-H", "770", "-q", "-nopgbrk", "-layout", "-enc", "UTF-8", "-eol", "unix", path, "-").Output()
if err != nil {
bodyResult.err = err
}
bodyResult.body = string(body)
br <- bodyResult
}()
return <-br, <-mr, nil
}
var pdfTimeLayouts = timeLayouts{time.ANSIC, "Mon Jan _2 15:04:05 2006 MST"}
type timeLayouts []string
func (tl timeLayouts) Parse(x string) (time.Time, bool) {
for _, layout := range tl {
t, err := time.Parse(layout, x)
if err == nil {
return t, true
}
}
return time.Time{}, false
}