-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
89 lines (73 loc) · 1.77 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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"os/exec"
"strings"
)
func Error(w http.ResponseWriter, e error, code int) {
log.Printf("Error: %q", e)
w.WriteHeader(code)
_, err := fmt.Fprintf(w, "%v", e)
if err != nil {
panic(err)
}
}
func main() {
http.HandleFunc("/pdfunite", func(w http.ResponseWriter, r *http.Request) {
log.Println(r.URL)
pdfNames := []string{}
// Copie de la requête dans le fichier HTML
d := json.NewDecoder(r.Body)
defer r.Body.Close()
d.Decode(&pdfNames)
// Unit les PDFs entre eux
cmd := exec.Command("pdfunite", pdfNames...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
e := cmd.Run()
if e != nil {
Error(w, e, http.StatusInternalServerError)
return
}
log.Printf("PDF done with %q\n", pdfNames)
w.WriteHeader(http.StatusOK)
})
http.HandleFunc("/pdf", func(w http.ResponseWriter, r *http.Request) {
log.Println(r.URL)
v := r.URL.Query()
htmlPath := v.Get("file")
header := v.Get("header")
footer := v.Get("footer")
pdfPath := strings.Replace(htmlPath, ".html", ".pdf", 1)
fmt.Printf("html: %q\n", htmlPath)
fmt.Printf("pdf : %q\n", pdfPath)
cmds := []string{
"wkhtmltopdf",
}
if header != "" {
cmds = append(cmds, "--header-html", header)
}
if footer != "" {
cmds = append(cmds, "--footer-html", footer)
}
cmds = append(cmds, string(htmlPath), pdfPath)
// Transformation du HTML en PDF
cmd := exec.Command(cmds[0], cmds[1:]...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
e := cmd.Run()
if e != nil {
Error(w, e, http.StatusInternalServerError)
return
}
log.Printf("PDF done for %q\n", pdfPath)
w.WriteHeader(http.StatusOK)
w.Write([]byte(pdfPath))
})
log.Printf("listening on port :8000")
http.ListenAndServe(":8000", nil)
}