Skip to content

Instantly share code, notes, and snippets.

@fortytw2
Created March 13, 2020 19:30
Show Gist options
  • Save fortytw2/95c515f18e3266aed7623e3aedf2768d to your computer and use it in GitHub Desktop.
Save fortytw2/95c515f18e3266aed7623e3aedf2768d to your computer and use it in GitHub Desktop.
func CreatePDFFromHTML(inputHTML []byte) ([]byte, error) {
dirName, err := ioutil.TempDir("", "pdf-generator")
if err != nil {
return nil, err
}
// remove this and log the dirName if you need to debug the HTML
defer os.RemoveAll(dirName)
// log.Println(dirName)
tmpFile, err := os.Create(dirName + "/html-to-print.html")
if err != nil {
return nil, err
}
_, err = tmpFile.Write(inputHTML)
if err != nil {
return nil, err
}
err = tmpFile.Close()
if err != nil {
return nil, err
}
opts := []chromedp.ExecAllocatorOption{
chromedp.NoFirstRun,
chromedp.NoDefaultBrowserCheck,
chromedp.Headless,
chromedp.DisableGPU,
chromedp.UserDataDir(dirName),
}
allocCtx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
defer cancel()
// also set up a custom logger
ctx, cancel := chromedp.NewContext(allocCtx, chromedp.WithLogf(log.Printf))
defer cancel()
// run task list
var output []byte
err = chromedp.Run(ctx, renderPDF("file://"+tmpFile.Name(), `#main`, &output))
if err != nil {
return nil, err
}
return output, nil
}
@ndabAP
Copy link

ndabAP commented Apr 28, 2020

renderPDF function is missing.

@fortytw2
Copy link
Author

fortytw2 commented Apr 28, 2020

Oh!

func renderPDF(urlstr, sel string, res *[]byte) chromedp.Tasks {
	return chromedp.Tasks{
		chromedp.Navigate(urlstr),
		chromedp.WaitReady(sel, chromedp.ByID),
		chromedp.Sleep(time.Second),
		pdf(res),
	}
}

func pdf(pdfbuf *[]byte) chromedp.Action {
	return chromedp.ActionFunc(func(ctx context.Context) error {
		buf, _, err := page.PrintToPDF().Do(ctx)
		if err != nil {
			return err
		}
		*pdfbuf = buf
		return nil
	})
}

@ndabAP

@ndabAP
Copy link

ndabAP commented Apr 28, 2020

<3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment