Created
October 21, 2019 06:55
-
-
Save NaniteFactory/16124ad6d60fb78f97bc4f0f60bbea52 to your computer and use it in GitHub Desktop.
chromedp screenshot example
This file contains 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
package main | |
import ( | |
"context" | |
"io/ioutil" | |
"log" | |
"math" | |
"time" | |
"github.com/chromedp/cdproto/emulation" | |
"github.com/chromedp/cdproto/page" | |
"github.com/chromedp/chromedp" | |
) | |
func main() { | |
// create chrome instance | |
ctx, cancel := chromedp.NewContext( | |
context.Background(), | |
chromedp.WithLogf(log.Printf), | |
) | |
defer cancel() | |
// create a timeout | |
ctx, cancel = context.WithTimeout(ctx, 15*time.Second) | |
defer cancel() | |
var img []byte | |
err := chromedp.Run(ctx, | |
chromedp.Navigate(`https://golang.org/pkg/time/`), | |
chromedp.WaitVisible(`body > footer`), // wait for footer element is visible (ie, page is loaded) | |
FullScreenshot(90, &img), | |
) | |
if err != nil { | |
log.Fatal(err) | |
} | |
if err := ioutil.WriteFile("fullScreenshot.png", img, 0644); err != nil { | |
log.Fatal(err) | |
} | |
} | |
func FullScreenshot(quality int64, result *[]byte) chromedp.Action { | |
return 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 | |
*result, 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 | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
contentSize
isnil
with recent versions of chromerdp / chromium