-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhmtl2pdf.go
121 lines (107 loc) · 2.96 KB
/
hmtl2pdf.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package html2pdf
import (
"context"
"errors"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
"log"
"os"
"os/signal"
"sync"
"syscall"
)
// PDFGeneratorInterface defines the methods for generating PDFs.
type PDFGeneratorInterface interface {
GeneratePDF(html *string) ([]byte, error)
Close()
}
// PDFGenerator holds the browser context and manages PDF generation.
type PDFGenerator struct {
browserCtx context.Context
browserCancel context.CancelFunc
mu sync.Mutex
}
// New creates a new PDFGenerator and initializes the browser context.
func New() (*PDFGenerator, error) {
ctx, cancel := chromedp.NewContext(context.Background())
// Start the browser
log.Println("starting the chromium on the background for PDF generation")
if err := chromedp.Run(ctx); err != nil {
cancel()
return nil, err
}
instance := &PDFGenerator{
browserCtx: ctx,
browserCancel: cancel,
}
closeHandler(instance)
return instance, nil
}
// Close shuts down the browser context.
func (p *PDFGenerator) Close() {
p.mu.Lock()
defer p.mu.Unlock()
if p.browserCancel != nil {
p.browserCancel()
p.browserCancel = nil
log.Println("Chromium instance closed")
}
}
// GeneratePDF converts HTML content to a PDF buffer.
func (p *PDFGenerator) GeneratePDF(html *string) ([]byte, error) {
if html == nil {
return nil, errors.New("html content is required")
}
p.mu.Lock()
defer p.mu.Unlock()
if p.browserCtx == nil || p.browserCtx.Err() != nil {
return nil, errors.New("browser context is not initialized or has been closed")
}
ctx, cancel := chromedp.NewContext(p.browserCtx)
defer cancel()
var pdfBuffer []byte
if err := chromedp.Run(ctx, generatePDFTasks(html, &pdfBuffer)...); err != nil {
return nil, err
}
return pdfBuffer, nil
}
// generatePDFTasks returns a sequence of tasks to generate a PDF from HTML content.
func generatePDFTasks(html *string, pdfBuffer *[]byte) chromedp.Tasks {
return chromedp.Tasks{
chromedp.Navigate("about:blank"),
setDocumentContent(*html),
printToPDF(pdfBuffer),
}
}
// setDocumentContent sets the document content of the current page.
func setDocumentContent(html string) chromedp.ActionFunc {
return func(ctx context.Context) error {
frameTree, err := page.GetFrameTree().Do(ctx)
if err != nil {
return err
}
return page.SetDocumentContent(frameTree.Frame.ID, html).Do(ctx)
}
}
// printToPDF prints the current page to PDF.
func printToPDF(pdfBuffer *[]byte) chromedp.ActionFunc {
return func(ctx context.Context) error {
buf, _, err := page.PrintToPDF().WithPrintBackground(true).Do(ctx)
if err != nil {
return err
}
*pdfBuffer = buf
return nil
}
}
// CloseHandler sets up a signal handler to gracefully shut down the PDFGenerator on interrupt signals.
func closeHandler(pdfGen PDFGeneratorInterface) {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
log.Println("gracefully shutting down the chromium")
pdfGen.Close()
os.Exit(0)
}()
}