# Screenshots and PDFs

> Take a screenshot of one element and of the whole page, and print the page to a PDF file.

The page: https://chromedp.dev/tutorials/screenshots/

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.

Recording: Screenshots and PDFs. It shows `tutorials/screenshots/run.go` while it drives Chrome/158.0.8127.88. Its frames and protocol messages are in /recordings/screenshots/timeline.json. The steps:

1. Line 26: `if err := chromedp.Do(ctx,`
2. Line 34: `card, err := chromedp.Run(ctx, chromedp.Screenshot(chromedp.CSS("#card")))`
3. Line 46: `full, err := chromedp.Run(ctx, chromedp.FullScreenshot(100))`
4. Line 57: `pdf, err := chromedp.Run(ctx, chromedp.PrintToPDF())`

## The program

````go title="run.go"
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
}
````

````go title="main.go"
// 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)
	}
}
````

````go title="page.go"
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](https://github.com/chromedp/chromedp-site/blob/main/tutorials/screenshots/page.html). In a folder with the four files, `go run .` prints:

````text title="Output"
card.png: 400 by 240 pixels
page.png: 960 pixels wide, and taller than the viewport: true
page.pdf: a PDF file: true
the files are in chromedp-screenshots
````

## How it works

- `chromedp.EmulateViewport` sets the size of the viewport, so that the
  screenshots have the same size on every computer.
- `chromedp.Screenshot` takes a PNG image of the first element that the
  selector finds.
- `chromedp.FullScreenshot` takes an image of the whole page, also the part
  below the viewport. A quality of 100 gives PNG, and less gives JPEG.
- `chromedp.PrintToPDF` prints the page as the print dialog of Chrome does.
  With no option, it prints on Letter paper, in portrait. The `PDF` options,
  such as the size of the paper, change that. See the
  [documentation of PrintToPDF](https://pkg.go.dev/github.com/chromedp/chromedp#PrintToPDF).

The recording does not show the files. The program prints their names and
sizes.
