-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
rendering.go
52 lines (42 loc) · 1.25 KB
/
rendering.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
// Package rendering provides a function to render HTML to images. It uses the
// Chrome Debug Protocol through the rod package. It will download a headless
// Chrome version if needed that matches the current platform.
//
// If the environment variable SND_DEBUG=1 it will start the chrome instances
// in non-headless mode.
package rendering
import (
"bytes"
"image"
_ "image/png"
"net/url"
"os"
"github.com/go-rod/rod/lib/launcher"
"github.com/go-rod/rod"
"github.com/go-rod/rod/lib/proto"
)
var browser *rod.Browser
func init() {
if os.Getenv("SND_DEBUG") == "1" {
l := launcher.New().
Headless(false).
Devtools(true)
browser = rod.New().ControlURL(l.MustLaunch()).MustConnect()
} else {
browser = rod.New().MustConnect()
}
}
// RenderHTML renders the element #content into a image.
func RenderHTML(html string, width int) (image.Image, error) {
page := browser.MustPage("data:text/html," + url.PathEscape(html))
page.MustWaitLoad().MustWaitIdle()
imageData, err := page.MustSetViewport(width, 100000, 1.0, false).MustElement("body").Screenshot(proto.PageCaptureScreenshotFormatPng, 100)
if err != nil {
return nil, err
}
img, _, err := image.Decode(bytes.NewBuffer(imageData))
if err != nil {
return nil, err
}
return img, nil
}