forked from josheyr/svg2png
-
Notifications
You must be signed in to change notification settings - Fork 0
/
html2png.go
89 lines (74 loc) · 1.73 KB
/
html2png.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 html2png
import (
"context"
"github.com/playwright-community/playwright-go"
"os"
"strings"
)
var (
DefaultChromePaths = []string{
"/usr/bin/chromium-browser",
"/usr/bin/chromium",
"/usr/bin/google-chrome-stable",
"/usr/bin/google-chrome",
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
"/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
"/Applications/Chromium.app/Contents/MacOS/Chromium",
"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe",
"C:/Program Files/Google/Chrome/Application/chrome.exe"}
)
func getChromePath() string {
for _, path := range DefaultChromePaths {
if _, err := os.Stat(path); !os.IsNotExist(err) {
return path
}
}
return ""
}
func HtmlToPng(ctx context.Context, html string, height int, width int) ([]byte, error) {
// write val to html in temp
// convert to png
tempDir := os.TempDir()
htmlFile := strings.Replace(tempDir+"\\temp.html", "\\", "/", -1)
f, err := os.Create(htmlFile)
if err != nil {
return nil, err
}
_, err = f.WriteString(html)
if err != nil {
return nil, err
}
err = f.Close()
if err != nil {
return nil, err
}
pw, err := playwright.Run()
if err != nil {
return nil, err
}
client, err := pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
Headless: playwright.Bool(true),
})
if err != nil {
return nil, err
}
// screenshot
page, err := client.NewPage()
if err != nil {
return nil, err
}
_, err = page.Goto("file:///" + htmlFile)
if err != nil {
return nil, err
}
err = page.SetViewportSize(width, height)
if err != nil {
return nil, err
}
screenshot, err := page.Screenshot()
if err != nil {
return nil, err
}
_ = os.Remove(htmlFile)
return screenshot, nil
}