-1

我有本地 html 文件,我需要渲染它们并获取它们的屏幕截图。

我找不到在 chromedp 中加载 html 代码的任何解决方案

那可能吗?

4

1 回答 1

1

是的。在chromedp文档中有一个很好的例子https://github.com/chromedp/examples/blob/master/screenshot/main.go。唯一的区别是,您将使用 "file:///<absolute_path_to_your_file>" 代替在 urlstring 中使用 "https://..." 。

代码示例,我主要从示例链接中获取并用于制作存储在本地系统上的 html 的屏幕截图:

package main

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

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

func main() {
    // create context
    ctx, cancel := chromedp.NewContext(context.Background())
    defer cancel()
    //if you want to use html from your local filesystem use file:/// + absolute path to your html file
    url :=  "file:///home/oktogen/Documents/Notebooks/2020/May/AnalysisJobs/FlaskApp/templates/index.html"
    // capture screenshot of an element
    var buf []byte
    // capture entire browser viewport, returning png with quality=90
    if err := chromedp.Run(ctx, fullScreenshot(url, 90, &buf)); err != nil {
        log.Fatal(err)
    }
    if err := ioutil.WriteFile("fullScreenshot.png", buf, 0644); err != nil {
        log.Fatal(err)
    }
}

// fullScreenshot takes a screenshot of the entire browser viewport.
//
// Liberally copied from puppeteer's source.
//
// Note: this will override the viewport emulation settings.
func fullScreenshot(urlstr string, quality int64, res *[]byte) chromedp.Tasks {
    return chromedp.Tasks{
        chromedp.Navigate(urlstr),
        chromedp.ActionFunc(func(ctx context.Context) error {
            // get layout metrics
            _, _, contentSize, err := page.GetLayoutMetrics().Do(ctx)
            if err != nil {
                return err
            }

            width, height := int64(math.Ceil(contentSize.Width)), int64(math.Ceil(contentSize.Height))

            // force viewport emulation
            err = emulation.SetDeviceMetricsOverride(width, height, 1, false).
                WithScreenOrientation(&emulation.ScreenOrientation{
                    Type:  emulation.OrientationTypePortraitPrimary,
                    Angle: 0,
                }).
                Do(ctx)
            if err != nil {
                return err
            }

            // capture screenshot
            *res, err = page.CaptureScreenshot().
                WithQuality(quality).
                WithClip(&page.Viewport{
                    X:      contentSize.X,
                    Y:      contentSize.Y,
                    Width:  contentSize.Width,
                    Height: contentSize.Height,
                    Scale:  1,
                }).Do(ctx)
            if err != nil {
                return err
            }
            return nil
        }),
    }
}
于 2020-07-12T11:06:44.243 回答