-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpdftotext.go
187 lines (147 loc) · 4.24 KB
/
pdftotext.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
package pdftotext
import (
"bufio"
"bytes"
"fmt"
"os/exec"
"reflect"
"strconv"
"strings"
"github.com/Masterminds/semver/v3"
)
// Extract PDF text content in simplified format
func Extract(pdfBytes []byte) (pdfPages []PdfPage, err error) {
var tsv []PopplerTsvRow
if tsv, err = ExtractInPopplerTsv(pdfBytes); err != nil {
return nil, err
}
prevPage := 1
prevContent := ""
for i, row := range tsv {
if row.Conf != -1 { // Seems to indicate control sequences
prevContent += row.Text + " "
}
var pageChanged = prevPage != row.PageNum
var lastIteration = i == len(tsv)-1
if pageChanged || lastIteration {
pdfPages = append(pdfPages, PdfPage{
Content: prevContent,
Number: prevPage,
})
prevPage = row.PageNum
prevContent = ""
}
}
return pdfPages, nil
}
// ExtractOrError Just like Extract, but indicates issues with errors
func ExtractOrError(pdfBytes []byte) (pages []PdfPage, err error) {
if pages, err = Extract(pdfBytes); err != nil {
return pages, err
}
if len(pages) == 0 {
return pages, fmt.Errorf("no pages extracted")
}
hasContent := false
for _, p := range pages {
if p.Content != "" {
hasContent = true
break
}
}
if !hasContent {
return pages, fmt.Errorf("no page text extracted")
}
return pages, err
}
// ExtractInPopplerTsv Access raw stdout content from Poppler
func ExtractInPopplerTsv(pdfBytes []byte) (tsvRows []PopplerTsvRow, err error) {
params := []string{
"-tsv",
"-", // Read from stdin
"-", // Write to stdout
}
cmd := exec.Command("pdftotext", params...)
cmd.Stdin = bytes.NewReader(pdfBytes)
var out bytes.Buffer
cmd.Stdout = &out
if err = cmd.Run(); err != nil {
return nil, fmt.Errorf("error executing pdftotext binary: %w", err)
}
tsvT := reflect.TypeOf(PopplerTsvRow{})
scanner := bufio.NewScanner(strings.NewReader(string(out.Bytes())))
scanner.Scan() // Ignore TSV header
for scanner.Scan() {
var (
line = scanner.Text()
fields = strings.Fields(line)
)
newTsv := PopplerTsvRow{}
for i := 0; i < tsvT.NumField(); i++ {
if i >= len(fields) {
continue
}
field := reflect.ValueOf(&newTsv).Elem().Field(i)
var col int
if col, err = strconv.Atoi(tsvT.Field(i).Tag.Get("col")); err != nil {
return nil, fmt.Errorf(string("cannot parse tag as int: %w"), err)
}
switch field.Interface().(type) {
case int:
var newInteger int
if newInteger, err = strconv.Atoi(fields[col]); err != nil {
return nil, fmt.Errorf("cannot convert value to int: %w", err)
}
field.SetInt(int64(newInteger))
case float64:
var newFloat float64
if newFloat, err = strconv.ParseFloat(fields[col], 64); err != nil {
return nil, fmt.Errorf("cannot convert value to float32: %w", err)
}
field.SetFloat(newFloat)
break
case string:
field.SetString(fields[col])
default:
panic("don't know how to map " + field.Type().String())
}
}
tsvRows = append(tsvRows, newTsv)
}
return tsvRows, nil
}
func CheckPopplerVersion() (fullVersionString string, err error) {
cmd := exec.Command("pdftotext", "-v")
var out bytes.Buffer
cmd.Stderr = &out
if err = cmd.Run(); err != nil {
panic(fmt.Errorf("error executing binary: %w", err))
}
scanner := bufio.NewScanner(strings.NewReader(string(out.Bytes())))
scanner.Scan()
line := scanner.Text()
fields := strings.Fields(line)
if len(fields) < 2 {
panic("No version information extracted")
}
fullVersionString = fields[2]
var constraint *semver.Constraints
var version *semver.Version
// https://poppler.freedesktop.org/releases.html
// poppler introduced the "tsv" parameter with this version:
const popplerVersionConstraint = ">= 22.05.0"
if constraint, err = semver.NewConstraint(popplerVersionConstraint); err != nil {
panic(fmt.Sprintf("Cannot parse constraint string \"%s\"", popplerVersionConstraint))
}
if version, err = semver.NewVersion(fullVersionString); err != nil {
panic(fmt.Sprintf("Cannot parse version string \"%s\"", fullVersionString))
}
if constraint.Check(version) {
// poppler is compatible
return fullVersionString, nil
}
panic(fmt.Sprintf("Incompatible poppler version: require version \"%s\", but found version \"%s\"", constraint.String(), version.String()))
}
func init() {
CheckPopplerVersion()
}