-
Notifications
You must be signed in to change notification settings - Fork 13
/
pdf.go
84 lines (71 loc) · 1.62 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
83
84
package pdf
import (
"context"
"sync"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
)
type ServiceInterface interface {
HTMLToPdf(html string) []byte
}
//TODO
//nolint
type PDFService struct {
chromeWebSocketURL string
}
func NewPDFService(chromeWebSocketURL string) *PDFService {
return &PDFService{
chromeWebSocketURL: chromeWebSocketURL,
}
}
func (c *PDFService) HTMLToPdf(html string) []byte {
allocatorContext, cancel := chromedp.NewRemoteAllocator(context.Background(), c.chromeWebSocketURL)
defer cancel()
ctx, cancel := chromedp.NewContext(allocatorContext)
defer cancel()
// do this first so that its page.EventLoadEventFired event won't be caught
if err := chromedp.Run(ctx,
chromedp.Navigate("about:blank"),
); err != nil {
panic(err)
}
var buf []byte
var wg sync.WaitGroup
wg.Add(1)
// waiting to page load event
chromedp.ListenTarget(ctx, func(ev interface{}) {
switch ev.(type) {
case *page.EventLoadEventFired:
go func() {
if err := chromedp.Run(ctx, printToPDF(&buf)); err != nil {
panic(err)
}
wg.Done()
}()
}
})
if err := chromedp.Run(ctx,
chromedp.PollFunction(
"(html) => {document.open();document.write(html);document.close();return true;}",
nil,
chromedp.WithPollingArgs(html),
),
); err != nil {
panic(err)
}
wg.Wait()
page.Close()
return buf
}
func printToPDF(res *[]byte) chromedp.Tasks {
return chromedp.Tasks{
chromedp.ActionFunc(func(ctx context.Context) error {
buf, _, err := page.PrintToPDF().WithPrintBackground(false).Do(ctx)
if err != nil {
return err
}
*res = buf
return nil
}),
}
}