feat(chromium): screenshot a single element via the selector form field (#947)

This commit is contained in:
Julien Neuhart
2026-08-13 13:56:17 +02:00
parent 2f6818d3df
commit 8d1eeaa73a
9 changed files with 184 additions and 2 deletions

View File

@@ -15,6 +15,7 @@ body:multipart-form {
~width: 800
~height: 600
~clip: false
~selector:
~format: png
~quality: 100
~optimizeForSpeed: false

View File

@@ -16,6 +16,7 @@ body:multipart-form {
~width: 800
~height: 600
~clip: false
~selector:
~format: png
~quality: 100
~optimizeForSpeed: false

View File

@@ -15,6 +15,7 @@ body:multipart-form {
~width: 800
~height: 600
~clip: false
~selector:
~format: png
~quality: 100
~optimizeForSpeed: false

View File

@@ -43,6 +43,10 @@ var (
// or undefined.
ErrInvalidSelectorQuery = errors.New("invalid selector query")
// ErrScreenshotSelectorNotFound happens when the CSS selector of a
// screenshot matches no element with a rendered box.
ErrScreenshotSelectorNotFound = errors.New("screenshot selector not found")
// ErrRpccMessageTooLarge happens when the messages received by
// ChromeDevTools are larger than 100 MB.
ErrRpccMessageTooLarge = errors.New("rpcc message too large")
@@ -347,6 +351,11 @@ type ScreenshotOptions struct {
// dimensions.
Clip bool
// Selector clips the screenshot to the bounding box of the first element
// matching this CSS selector. Empty captures the whole page. Takes
// precedence over Clip.
Selector string
// Format is the image compression format, either "png" or "jpeg" or
// "webp".
Format string
@@ -370,6 +379,7 @@ func DefaultScreenshotOptions() ScreenshotOptions {
Width: 800,
Height: 600,
Clip: false,
Selector: "",
Format: "png",
Quality: 100,
OptimizeForSpeed: false,

View File

@@ -366,6 +366,7 @@ func FormDataChromiumScreenshotOptions(ctx *api.Context) (*api.FormData, Screens
var (
width, height int
clip bool
selector string
format string
quality int
optimizeForSpeed bool
@@ -376,6 +377,7 @@ func FormDataChromiumScreenshotOptions(ctx *api.Context) (*api.FormData, Screens
Int("width", &width, defaultScreenshotOptions.Width).
Int("height", &height, defaultScreenshotOptions.Height).
Bool("clip", &clip, defaultScreenshotOptions.Clip).
String("selector", &selector, defaultScreenshotOptions.Selector).
Custom("format", func(value string) error {
if value == "" {
format = defaultScreenshotOptions.Format
@@ -420,6 +422,7 @@ func FormDataChromiumScreenshotOptions(ctx *api.Context) (*api.FormData, Screens
Width: width,
Height: height,
Clip: clip,
Selector: selector,
Format: format,
Quality: quality,
OptimizeForSpeed: optimizeForSpeed,
@@ -963,7 +966,17 @@ func screenshotUrl(ctx *api.Context, chromium Api, url string, options Screensho
outputPath := ctx.GeneratePath(ext)
err := chromium.Screenshot(ctx, ctx.Log(), url, outputPath, options)
err = handleChromiumError(err, options.Options)
if errors.Is(err, ErrScreenshotSelectorNotFound) {
err = api.WrapError(
err,
api.NewSentinelHttpError(
http.StatusBadRequest,
fmt.Sprintf("The selector '%s' (selector) matched no element with a visible box", options.Selector),
),
)
} else {
err = handleChromiumError(err, options.Options)
}
if err != nil {
return fmt.Errorf("screenshot: %w", err)
}

View File

@@ -7,6 +7,7 @@ import (
"fmt"
"log/slog"
"os"
"strconv"
"time"
"github.com/chromedp/cdproto/cdp"
@@ -188,7 +189,16 @@ func captureScreenshotActionFunc(logger *slog.Logger, outputPath string, options
WithOptimizeForSpeed(options.OptimizeForSpeed).
WithFormat(page.CaptureScreenshotFormat(options.Format))
if options.Clip {
switch {
case options.Selector != "":
clip, err := elementClip(ctx, options.Selector)
if err != nil {
return err
}
logger.DebugContext(ctx, fmt.Sprintf("clip screenshot to selector '%s'", options.Selector))
captureScreenshot = captureScreenshot.WithClip(clip)
case options.Clip:
captureScreenshot = captureScreenshot.WithClip(&page.Viewport{
Width: float64(options.Width),
Height: float64(options.Height),
@@ -229,6 +239,49 @@ func captureScreenshotActionFunc(logger *slog.Logger, outputPath string, options
}
}
// elementClip resolves the first element matching selector to a page-space clip
// rectangle for Page.captureScreenshot.
//
// getBoundingClientRect reports viewport-relative CSS pixels; adding the scroll
// offset puts the rectangle in the document coordinate space that
// WithCaptureBeyondViewport expects. It fails with
// [ErrScreenshotSelectorNotFound] when nothing matches or the match has no
// rendered box (display:none or a zero area), so the caller can answer 400.
func elementClip(ctx context.Context, selector string) (*page.Viewport, error) {
var rect struct {
Found bool `json:"found"`
X float64 `json:"x"`
Y float64 `json:"y"`
Width float64 `json:"width"`
Height float64 `json:"height"`
}
expr := fmt.Sprintf(`(() => {
const el = document.querySelector(%s);
if (!el) {
return { found: false };
}
const r = el.getBoundingClientRect();
return { found: true, x: r.left + window.scrollX, y: r.top + window.scrollY, width: r.width, height: r.height };
})()`, strconv.Quote(selector))
err := chromedp.Evaluate(expr, &rect).Do(ctx)
if err != nil {
return nil, fmt.Errorf("evaluate selector box: %v: %w", err, ErrScreenshotSelectorNotFound)
}
if !rect.Found || rect.Width <= 0 || rect.Height <= 0 {
return nil, fmt.Errorf("selector %q matched no element with a visible box: %w", selector, ErrScreenshotSelectorNotFound)
}
return &page.Viewport{
X: rect.X,
Y: rect.Y,
Width: rect.Width,
Height: rect.Height,
Scale: 1,
}, nil
}
func setDeviceMetricsOverride(logger *slog.Logger, width, height int, deviceScaleFactor float64) chromedp.ActionFunc {
return func(ctx context.Context) error {
logger.DebugContext(ctx, "set device metrics override")

View File

@@ -69,6 +69,32 @@ Feature: /forms/chromium/screenshot/html
Then the response status code should be 200
Then the response header "Content-Type" should be "image/png"
# The target element is 300x200 and sits below a spacer, so a correct clip
# proves both the element size and its page offset. See issue #947.
Scenario: POST /forms/chromium/screenshot/html (Selector)
Given I have a default Gotenberg container
When I make a "POST" request to Gotenberg at the "/forms/chromium/screenshot/html" endpoint with the following form data and header(s):
| files | testdata/screenshot-selector-html/index.html | file |
| selector | #target | field |
| Gotenberg-Output-Filename | foo | header |
Then the response status code should be 200
Then the response header "Content-Type" should be "image/png"
Then the "foo.png" image should be 300x200 pixels
# A centered red pixel proves the clip landed on the element, not on the
# white spacer above it, i.e. the page offset was applied.
Then the "foo.png" image pixel at 150,100 should be "#ff0000"
Scenario: POST /forms/chromium/screenshot/html (Selector Not Found)
Given I have a default Gotenberg container
When I make a "POST" request to Gotenberg at the "/forms/chromium/screenshot/html" endpoint with the following form data and header(s):
| files | testdata/screenshot-selector-html/index.html | file |
| selector | #does-not-exist | field |
Then the response status code should be 400
Then the response body should contain string:
"""
The selector '#does-not-exist' (selector) matched no element with a visible box
"""
Scenario: POST /forms/chromium/screenshot/html (Quality)
Given I have a default Gotenberg container
When I make a "POST" request to Gotenberg at the "/forms/chromium/screenshot/html" endpoint with the following form data and header(s):

View File

@@ -5,6 +5,8 @@ import (
"encoding/json"
"errors"
"fmt"
"image"
_ "image/png" // Register the PNG decoder for image.DecodeConfig.
"io"
"mime"
"net/http"
@@ -1010,6 +1012,51 @@ func (s *scenario) thePdfShouldHaveImages(ctx context.Context, name string, imag
return nil
}
func (s *scenario) theImageShouldBePixels(_ context.Context, name string, width, height int) error {
path := fmt.Sprintf("%s/%s/%s", s.workdir, s.resp.Header().Get("Gotenberg-Trace"), name)
file, err := os.Open(path) //nolint:gosec // path is built from test-controlled values.
if err != nil {
return fmt.Errorf("open image %q: %w", path, err)
}
defer file.Close()
config, format, err := image.DecodeConfig(file)
if err != nil {
return fmt.Errorf("decode image %q: %w", path, err)
}
if config.Width != width || config.Height != height {
return fmt.Errorf("expected %s image %dx%d, but actual is %dx%d", format, width, height, config.Width, config.Height)
}
return nil
}
func (s *scenario) theImagePixelShouldBe(_ context.Context, name string, x, y int, want string) error {
path := fmt.Sprintf("%s/%s/%s", s.workdir, s.resp.Header().Get("Gotenberg-Trace"), name)
file, err := os.Open(path) //nolint:gosec // path is built from test-controlled values.
if err != nil {
return fmt.Errorf("open image %q: %w", path, err)
}
defer file.Close()
img, format, err := image.Decode(file)
if err != nil {
return fmt.Errorf("decode image %q: %w", path, err)
}
r, g, b, _ := img.At(x, y).RGBA()
// RGBA returns 16-bit channels; shift down to the 8-bit hex form.
got := fmt.Sprintf("#%02x%02x%02x", r>>8, g>>8, b>>8)
if !strings.EqualFold(got, want) {
return fmt.Errorf("expected %s pixel at %d,%d to be %s, but actual is %s", format, x, y, want, got)
}
return nil
}
func (s *scenario) thePdfShouldBeSetToLandscapeOrientation(ctx context.Context, name string, kind string) error {
var path string
if !strings.HasPrefix(name, "*_") {
@@ -1599,6 +1646,8 @@ func InitializeScenario(ctx *godog.ScenarioContext) {
ctx.Then(`^the "([^"]*)" PDF (should|should NOT) have the following content at page (\d+):$`, s.thePdfShouldHaveTheFollowingContentAtPage)
ctx.Then(`^the "([^"]*)" PDF (should|should NOT) have content matching "([^"]*)" at page (\d+)$`, s.thePdfShouldHaveContentMatchingAtPage)
ctx.Then(`^the "([^"]*)" PDF should have (\d+) image\(s\)$`, s.thePdfShouldHaveImages)
ctx.Then(`^the "([^"]*)" image should be (\d+)x(\d+) pixels$`, s.theImageShouldBePixels)
ctx.Then(`^the "([^"]*)" image pixel at (\d+),(\d+) should be "([^"]*)"$`, s.theImagePixelShouldBe)
ctx.After(func(ctx context.Context, sc *godog.Scenario, err error) (context.Context, error) {
if s.gotenbergContainer != nil {
errTerminate := s.gotenbergContainer.Terminate(ctx, testcontainers.StopTimeout(0))

View File

@@ -0,0 +1,28 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Element screenshot</title>
<style>
body {
margin: 0;
padding: 40px;
background: #ffffff;
}
/* A spacer pushes the target away from the origin so the clip has to
account for the element offset, not just its size. */
.spacer {
height: 120px;
}
#target {
width: 300px;
height: 200px;
background: #ff0000;
}
</style>
</head>
<body>
<div class="spacer"></div>
<div id="target"></div>
</body>
</html>