Krishnadas PC
Krishnadas PC

Reputation: 6539

chromedp golang: How to create screenshot and pdf from template HTML string instead of URL?

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

Upvotes: 1

Views: 2859

Answers (1)

Zeke Lu
Zeke Lu

Reputation: 7475

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)
    }
}

Upvotes: 1

Related Questions