-
Notifications
You must be signed in to change notification settings - Fork 0
/
pdf.go
67 lines (60 loc) · 1.56 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
package pdf
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"net/http"
u "net/url"
"os"
"strings"
)
// Gen generates a pdf
// Deprecated: use Create instead
func Gen(url string, key string, isMarginless bool) (*bytes.Buffer, error) {
marginless := ""
if isMarginless {
marginless = "marginless"
}
return Create(url, key, marginless)
}
func Create(urlOrText string, key string, opts ...string) (*bytes.Buffer, error) {
form := u.Values{}
form.Add("url", urlOrText)
for _, opt := range opts {
if opt == "marginless" {
form.Add("nomargin", "1")
}
if opt == "nomargin" {
form.Add("nomargin", "1")
}
if opt == "landscape" {
form.Add("orientation", "landscape")
}
}
client := http.Client{}
pdfURL := os.Getenv("PDF_URL") + ""
if pdfURL == "" {
pdfURL = "https://pdf.nerdy.co.nz/make"
}
r, err := http.NewRequest("POST", pdfURL, strings.NewReader(form.Encode()))
// r, err := http.NewRequest("POST", "http://localhost:5000/api/v1/notes/parse", bytes.NewBufferString(str))
if err != nil {
return nil, errors.New("Couldn't make the request" + err.Error())
}
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
r.Header.Add("key", key)
resp, err := client.Do(r)
if err != nil {
return nil, errors.New("request failed" + err.Error())
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, errors.New("request failed" + err.Error())
}
if resp.StatusCode != 200 {
return nil, fmt.Errorf("Request failed status code: %d %s", resp.StatusCode, string(b))
}
return bytes.NewBuffer(b), err
}