/
main.go
90 lines (80 loc) · 2.73 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
90
package main
import (
"context"
"flag"
"fmt"
"log"
"os"
"github.com/liuminhaw/renderer"
)
func main() {
landscape := flag.Bool("landscape", false, "create pdf in landscape layout")
headerFooter := flag.Bool("headerFooter", false, "show header and footer")
paperWidth := flag.Float64("paperWidth", 0, "paper width in centimeter")
paperHeight := flag.Float64("paperHeight", 0, "paper height in centimeter")
marginTop := flag.Float64("marginTop", 1, "top margin in centimeter")
marginBottom := flag.Float64("marginBottom", 1, "bottom margin in centimeter")
marginLeft := flag.Float64("marginLeft", 1, "left margin in centimeter")
marginRight := flag.Float64("marginRight", 1, "right margin in centimeter")
idleType := flag.String("idleType", "networkIdle",
"how to determine loading idle and return, valid input: networkIdle, InteractiveTime")
browserExecPath := flag.String("browserPath", "", "manually set browser executable path")
container := flag.Bool(
"container",
false,
"indicate if running in container (docker / lambda) environment",
)
debug := flag.Bool("debug", false, "turn on for outputing debug message")
flag.Parse()
if *paperWidth < 0 || *paperHeight < 0 {
fmt.Println("Paper width / height value should be greater than 0")
os.Exit(1)
}
if *marginTop < 0 || *marginBottom < 0 || *marginLeft < 0 || *marginRight < 0 {
fmt.Println("Margins value should be greater than 0")
os.Exit(1)
}
if *idleType != "networkIdle" && *idleType != "InteractiveTime" {
fmt.Println("Valid idleType value: networkIdle, InteractiveTime")
os.Exit(1)
}
if len(flag.Args()) != 1 {
fmt.Printf("Usage: %s url\n", os.Args[0])
os.Exit(1)
}
url := flag.Arg(0)
// Explicit set browserContext if need to modify settings
// otherwise no need to additional set it up
browserContext := renderer.BrowserContext{
IdleType: *idleType,
BrowserExecPath: *browserExecPath,
Container: *container,
DebugMode: *debug,
}
pdfContext := renderer.PdfContext{
Landscape: *landscape,
DisplayHeaderFooter: *headerFooter,
PaperWidthCm: *paperWidth,
PaperHeightCm: *paperHeight,
MarginTopCm: *marginTop,
MarginBottomCm: *marginBottom,
MarginLeftCm: *marginLeft,
MarginRightCm: *marginRight,
}
ctx := context.Background()
ctx = renderer.WithBrowserContext(ctx, &browserContext)
ctx = renderer.WithPdfContext(ctx, &pdfContext)
context, err := renderer.RenderPdf(ctx, url)
if err != nil {
log.Fatalf("RenderPDf test: %s", err)
}
if err := os.MkdirAll("result", 0775); err != nil {
log.Fatalf("RenderPDF test: %s", err)
}
f, err := os.Create("result/result.pdf")
if err != nil {
log.Fatalf("RenderPDF test: %s", err)
}
defer f.Close()
f.Write(context)
}