Screenshots and PDFs
This program takes a screenshot of a card on the page and of the whole page, prints the page to a PDF file, and writes the three files to a folder in the temporary directory of the system.
A report

tutorials/screenshots/run.go in Chrome/158.0.8127.88. Step through it to see the line of Go, the page and the protocol messages of each step.The steps of the recording
- line 26
if err := chromedp.Do(ctx, - line 34
card, err := chromedp.Run(ctx, chromedp.Screenshot(chromedp.CSS("#card"))) - line 46
full, err := chromedp.Run(ctx, chromedp.FullScreenshot(100)) - line 57
pdf, err := chromedp.Run(ctx, chromedp.PrintToPDF())
The program
Section titled “The program”package main
import (
"bytes"
"context"
"fmt"
"image"
_ "image/png"
"io"
"os"
"path/filepath"
"github.com/chromedp/chromedp"
)
// run takes a screenshot of the card of the page at url and of the whole
// page, prints the page to a PDF file, and writes the three files to a folder
// in the temporary directory.
func run(ctx context.Context, w io.Writer, url string) error {
dir := filepath.Join(os.TempDir(), "chromedp-screenshots")
if err := os.MkdirAll(dir, 0o755); err != nil {
return fmt.Errorf("making the folder: %w", err)
}
// A fixed size of the viewport gives screenshots of a fixed size.
if err := chromedp.Do(ctx,
chromedp.EmulateViewport(960, 600),
chromedp.Navigate(url),
); err != nil {
return fmt.Errorf("loading the page: %w", err)
}
// Screenshot takes a PNG image of one element.
card, err := chromedp.Run(ctx, chromedp.Screenshot(chromedp.CSS("#card")))
if err != nil {
return fmt.Errorf("taking the screenshot of the card: %w", err)
}
size, err := save(dir, "card.png", card)
if err != nil {
return err
}
fmt.Fprintf(w, "card.png: %d by %d pixels\n", size.X, size.Y)
// FullScreenshot takes an image of the whole page, also the part below
// the viewport. A quality of 100 gives a PNG image, and less gives JPEG.
full, err := chromedp.Run(ctx, chromedp.FullScreenshot(100))
if err != nil {
return fmt.Errorf("taking the screenshot of the page: %w", err)
}
size, err = save(dir, "page.png", full)
if err != nil {
return err
}
fmt.Fprintf(w, "page.png: %d pixels wide, and taller than the viewport: %t\n", size.X, size.Y > 600)
// PrintToPDF prints the page as the print dialog of Chrome does.
pdf, err := chromedp.Run(ctx, chromedp.PrintToPDF())
if err != nil {
return fmt.Errorf("printing the page: %w", err)
}
if _, err := save(dir, "page.pdf", pdf); err != nil {
return err
}
fmt.Fprintf(w, "page.pdf: a PDF file: %t\n", bytes.HasPrefix(pdf, []byte("%PDF-")))
fmt.Fprintf(w, "the files are in %s\n", filepath.Base(dir))
return nil
}
// save writes buf to the file name in dir. For an image, it returns its size
// in pixels.
func save(dir, name string, buf []byte) (image.Point, error) {
if err := os.WriteFile(filepath.Join(dir, name), buf, 0o644); err != nil {
return image.Point{}, fmt.Errorf("writing %s: %w", name, err)
}
if filepath.Ext(name) != ".png" {
return image.Point{}, nil
}
cfg, _, err := image.DecodeConfig(bytes.NewReader(buf))
if err != nil {
return image.Point{}, fmt.Errorf("reading %s: %w", name, err)
}
return image.Pt(cfg.Width, cfg.Height), nil
}// Command screenshots is the program of the tutorial "Screenshots and PDFs" on
// https://chromedp.dev. It takes a screenshot of an element and of the page, and prints the page to a PDF file.
//
// go run .
package main
import (
"context"
"log"
"net/http/httptest"
"os"
"time"
"github.com/chromedp/chromedp"
)
func main() {
// Serve the page of the tutorial on this computer, so that the program
// needs no internet.
srv := httptest.NewServer(handler())
defer srv.Close()
// The context holds the browser. The first call on it starts Chrome, and
// cancel stops Chrome.
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
// A timeout keeps the program from waiting for ever.
ctx, cancel = context.WithTimeout(ctx, 30*time.Second)
defer cancel()
if err := run(ctx, os.Stdout, srv.URL); err != nil {
log.Fatal(err)
}
}package main
import (
_ "embed"
"net/http"
)
//go:embed page.html
var page []byte
// handler serves the page of the tutorial.
func handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write(page)
})
return mux
}The page of the program is page.html. In a folder with the four files, go run . prints:
card.png: 400 by 240 pixelspage.png: 960 pixels wide, and taller than the viewport: truepage.pdf: a PDF file: truethe files are in chromedp-screenshotsHow it works
Section titled “How it works”chromedp.EmulateViewportsets the size of the viewport, so that the screenshots have the same size on every computer.chromedp.Screenshottakes a PNG image of the first element that the selector finds.chromedp.FullScreenshottakes an image of the whole page, also the part below the viewport. A quality of 100 gives PNG, and less gives JPEG.chromedp.PrintToPDFprints the page as the print dialog of Chrome does. With no option, it prints on Letter paper, in portrait. ThePDFoptions, such as the size of the paper, change that. See the documentation of PrintToPDF.
The recording does not show the files. The program prints their names and sizes.