Created
March 13, 2020 19:30
-
-
Save fortytw2/95c515f18e3266aed7623e3aedf2768d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
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
})
}
<3
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
renderPDF
function is missing.