-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
127 lines (94 loc) · 2.37 KB
/
main.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
package main
import (
"encoding/json"
"os"
"os/exec"
"strconv"
"strings"
"github.com/gin-gonic/gin"
)
type Field struct {
FieldType string
FieldName string
FieldFlags float64
FieldJustification string
}
func main() {
gin.SetMode(gin.ReleaseMode)
r := gin.Default()
r.GET("/dump-data-fields", func(c *gin.Context) {
file, err := c.FormFile("file")
if err != nil {
c.Error(err)
return
}
// Create the tempdir and tempfile for pdftk to operate on
tempdir := os.TempDir()
tempfile := tempdir + "/temp.pdf"
err = c.SaveUploadedFile(file, tempfile)
args := []string{
tempfile,
"dump_data_fields",
}
out, err := exec.Command("pdftk", args...).Output()
if err != nil {
c.Error(err)
return
}
output := string(out[:])
pdftkFields := strings.Split(output, "---\n")
// Remove the empty string from the start of the fields list
_, pdftkFields = pdftkFields[0], pdftkFields[1:]
var fields []Field
for _, pdftkField := range pdftkFields[0:] {
fieldData := strings.Split(pdftkField, "\n")
// Remove the empty string at the end of the field data list
fieldData = fieldData[:len(fieldData)-1]
fieldDataMap := make(map[string]string)
for _, data := range fieldData {
parts := strings.Split(data, ": ")
keyPart := parts[0]
valuePart := parts[1]
fieldDataMap[keyPart] = valuePart
}
fieldFlags, err := strconv.ParseFloat(fieldDataMap["FieldFlags"], 64)
if err != nil {
c.Error(err)
return
}
field := Field{
FieldType: fieldDataMap["FieldType"],
FieldName: fieldDataMap["FieldName"],
FieldFlags: fieldFlags,
FieldJustification: fieldDataMap["FieldJustification"],
}
fields = append(fields, field)
}
c.JSON(200, fields)
})
r.POST("/fill-pdf", func(c *gin.Context) {
file, err := c.FormFile("file")
if err != nil {
c.Error(err)
return
}
jsonString := c.PostForm("json")
dynamic := make(map[string]interface{})
json.Unmarshal([]byte(jsonString), &dynamic)
tempdir := os.TempDir()
tempfile := tempdir + "/temp.pdf"
tempfilefilled := tempdir + "/temp.pdf"
err = c.SaveUploadedFile(file, tempfile)
if err != nil {
c.Error(err)
return
}
err = Fill(dynamic, tempfile, tempfilefilled, true)
if err != nil {
c.Error(err)
return
}
c.File(tempfilefilled)
})
r.Run(":80")
}