Skip to content

Instantly share code, notes, and snippets.

@yosida95
Created May 22, 2020 14:36
Show Gist options
  • Save yosida95/2a473d8c77c46f00d8d965a1e034078d to your computer and use it in GitHub Desktop.
Save yosida95/2a473d8c77c46f00d8d965a1e034078d to your computer and use it in GitHub Desktop.
Save a webpage as a PDF file using Headless Google Chrome with Go's chromedp/chromedp
package main
import (
"context"
"flag"
"io/ioutil"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/cdproto/runtime"
"github.com/chromedp/chromedp"
)
func main() {
flagURL := flag.String("url", "https://example.com/", "URL")
flagFilename := flag.String("filename", "./out.pdf", "PDF filename")
flag.Parse()
actx, cancel := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.DisableGPU,
)...)
defer cancel()
ctx, cancel := chromedp.NewContext(actx)
defer cancel()
if err := chromedp.Run(ctx,
chromedp.Navigate(*flagURL),
chromedp.ActionFunc(func(ctx context.Context) error {
_, exc, err := runtime.Evaluate(`document.fonts.ready`).
WithAwaitPromise(true).
Do(ctx)
if err != nil {
return err
} else if exc != nil {
return exc
}
data, _, err := page.PrintToPDF().
WithPrintBackground(true).
WithPaperHeight(11.69).
WithPaperWidth(8.27).
WithTransferMode(page.PrintToPDFTransferModeReturnAsBase64).
Do(ctx)
if err != nil {
return err
}
return ioutil.WriteFile(*flagFilename, data, 0644)
}),
); err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment