diff --git a/converter/converter.go b/converter/converter.go index 9ca5065..907a95c 100644 --- a/converter/converter.go +++ b/converter/converter.go @@ -17,10 +17,11 @@ import ( // html to pdf converter structure for type Converter struct { - chromePath string - ctx context.Context - cancel context.CancelFunc - progress func(progress int) + chromePath string + ctx context.Context + cancel context.CancelFunc + allocCancel context.CancelFunc + progress func(progress int) } // NewConverter starts a new converter instance with a chrome headless shell executable @@ -44,7 +45,7 @@ func NewConverter(chromePath string) (*Converter, error) { var allocCtx context.Context allocCtx, c.cancel = chromedp.NewExecAllocator(context.Background(), opts...) - c.ctx, c.cancel = chromedp.NewContext(allocCtx) + c.ctx, c.allocCancel = chromedp.NewContext(allocCtx) return c, nil } @@ -81,10 +82,11 @@ func (c *Converter) Convert(files ...models.File) error { htmlURL.WriteString(filepath.ToSlash(absPath)) - c.ctx, c.cancel = context.WithTimeout(c.ctx, 60*time.Second) + ctx, cancel := context.WithTimeout(c.ctx, 60*time.Second) + defer cancel() var pdfData []byte - err = chromedp.Run(c.ctx, + err = chromedp.Run(ctx, chromedp.Navigate(htmlURL.String()), chromedp.WaitReady("body", chromedp.ByQuery), chromedp.ActionFunc(func(ctx context.Context) error { @@ -116,6 +118,12 @@ func (c *Converter) Convert(files ...models.File) error { return nil } +func (c *Converter) Close() { + if c.cancel != nil { + c.cancel() + } +} + // getChromePath checks for system Chrome, else falls back to bundled headless shell func (c *Converter) getChromePath() (string, error) {