1

Is it possible to generate PDF/screenshots from HTML template instead of URL in chrome dp library?

func printToPDF(urlstr string, res *[]byte) chromedp.Tasks {
    return chromedp.Tasks{
        chromedp.Navigate(urlstr),
        //page.SetDocumentContent("body", "<h1>Hello world</h1>"), Something like this is this possible?
        chromedp.ActionFunc(func(ctx context.Context) error {
            buf, _, err := page.PrintToPDF().WithPrintBackground(false).Do(ctx)
            if err != nil {
                return err
            }
            *res = buf
            return nil
        }),
    }
}

Link to library: https://github.com/chromedp/chromedp

Krishnadas PC
  • 5,981
  • 2
  • 53
  • 54
  • I'm not familiar with chromedp, but from what I can see it uses Chrome (in "headless mode" by default) to render pages, so it definitely needs a fully rendered HTML page to work, a template is not enough. You could maybe use Go's HTTP libraries to set up a local web server to render the pages and point chromedp to a "localhost" URL served by this web server? – rob74 May 28 '21 at 07:43
  • Another way could be to navigate to a data URL like `data:text/html;base64,PGRpdj4gSGVsbG8gPC9kaXY+`, but with large documents this can definitely become problematic (if there are limits on URL length). If you already have the file on disk you can also use the `file://` URL schema to visit it directly. Maybe you can also use an ActionFunc and set the page content like [here](https://github.com/chromedp/chromedp/issues/827) – xarantolus May 28 '21 at 13:02
  • @xarantolus I need to parse the template it's not static. The data comes from db. Now it works as extra requests one for image one for pdf so API is slow. – Krishnadas PC May 28 '21 at 13:12

1 Answers1

0

Answer copied from https://github.com/chromedp/chromedp/issues/836#issuecomment-850244316:

package main

import (
    "context"
    "io/ioutil"
    "log"

    "github.com/chromedp/cdproto/page"
    "github.com/chromedp/chromedp"
)

func main() {
    ctx, cancel := chromedp.NewContext(context.Background())
    defer cancel()

    // construct your html
    html := "<html><body>test</body></html>"
    if err := chromedp.Run(ctx,
        chromedp.Navigate("about:blank"),
        chromedp.ActionFunc(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)
        }),
        chromedp.ActionFunc(func(ctx context.Context) error {
            buf, _, err := page.PrintToPDF().WithPrintBackground(false).Do(ctx)
            if err != nil {
                return err
            }
            return ioutil.WriteFile("sample.pdf", buf, 0644)
        }),
    ); err != nil {
        log.Fatal(err)
    }
}
Zeke Lu
  • 6,349
  • 1
  • 17
  • 23