ScreenshotNeo

BlogHow-to

How to Screenshot a Webpage with a Custom Viewport in Java Playwright

Set a custom viewport in Playwright for Java, choose viewport or full-page capture, configure image output, and troubleshoot common screenshot issues.

By the ScreenshotNeo team4 October 20266 min read

Set the viewport before navigating, then call page.screenshot(). The example below saves the visible viewport as a PNG; change the dimensions and URL for your case.

import com.microsoft.playwright.*;
import java.nio.file.Paths;

public class ScreenshotExample {
  public static void main(String[] args) {
    try (Playwright playwright = Playwright.create()) {
      Browser browser = playwright.chromium().launch();
      try {
        Page page = browser.newPage();
        page.setViewportSize(1440, 900);
        page.navigate("https://example.com");
        page.screenshot(new Page.ScreenshotOptions()
            .setPath(Paths.get("screenshot.png")));
      } finally {
        browser.close();
      }
    }
  }
}

The Java Page API accepts viewport width and height in CSS pixels. Setting them before navigation lets responsive pages render for the intended size. A screenshot captures the current viewport by default. See the Playwright Java Page API and screenshots guide.

1. Set the viewport for one page or a whole context

Use page.setViewportSize(width, height) when a single page needs its own dimensions. For a consistent viewport across pages, configure the browser context before creating pages:

import com.microsoft.playwright.*;
import java.nio.file.Paths;

public class ContextViewportExample {
  public static void main(String[] args) {
    try (Playwright playwright = Playwright.create()) {
      Browser browser = playwright.chromium().launch();
      try {
        BrowserContext context = browser.newContext(
            new Browser.NewContextOptions().setViewportSize(1440, 900));
        Page page = context.newPage();
        page.navigate("https://example.com");
        page.screenshot(new Page.ScreenshotOptions()
            .setPath(Paths.get("screenshot.png")));
        context.close();
      } finally {
        browser.close();
      }
    }
  }
}

The documented default viewport is 1280 × 720. Disabling the context’s consistent viewport with null makes rendering depend on the host window, which can make runs non-deterministic. Prefer an explicit size for repeatable captures. See the Browser API.

page.setViewportSize also resets the screen size. If you need to control screen size and viewport separately, configure screen and viewport on the context. Viewport-only resizing is not complete mobile-device emulation: device scale factor, mobile behavior, user agent, touch, and screen size are separate context settings. Consult the emulation guide for the options supported by your Playwright version.

2. Choose viewport, full-page, element, or clipped capture

Capture goal Java API What it captures
Visible viewport page.screenshot(options) The current viewport; this is the default.
Entire scrollable page setFullPage(true) The full page as if it fit in a very tall screen.
One element page.locator(selector).screenshot(options) The matched element, scrolling it into view as needed.
Specific rectangular area setClip(clip) The requested clip rectangle.

Full-page example:

page.screenshot(new Page.ScreenshotOptions()
    .setPath(Paths.get("full-page.png"))
    .setFullPage(true));

Element example:

page.locator("main article").screenshot(
    new Locator.ScreenshotOptions()
        .setPath(Paths.get("article.png")));

Element screenshots are useful when the output should contain a component rather than the full layout. The locator API waits for actionability and scrolls the element into view. A selector that matches no element, or matches an unexpected element, needs to be fixed before capture. See the Locator API.

3. Configure format, scale, clipping, and output

Screenshot options let you choose PNG, JPEG, or WebP output, CSS-pixel or device-pixel scaling, clipping, animation handling, and a stylesheet. JPEG quality is configurable; the quality setting does not apply to PNG. Device-pixel scale can produce larger high-DPI images.

page.screenshot(new Page.ScreenshotOptions()
    .setPath(Paths.get("capture.webp"))
    .setType(ScreenshotType.WEBP)
    .setScale(Page.ScreenshotScale.CSS)
    .setAnimations(ScreenshotAnimations.DISABLED));

To capture an explicit region, provide a clip rectangle in the screenshot options. Check the Java API for the exact clip type and setters available in your installed version. A path saves the image to disk; omitting the path returns the screenshot as a byte[], which you can pass to another library or upload.

byte[] imageBytes = page.screenshot(new Page.ScreenshotOptions()
    .setType(ScreenshotType.PNG));

Disabling animations and applying a stylesheet can reduce visual variation, but you still need to account for site-specific content such as rotating banners, live data, and delayed images. Full-page captures can be much taller and larger than viewport captures.

4. Make captures reliable

  1. Set the viewport before navigation when responsive layout matters.
  2. Navigate to the target URL and wait for the condition that signals the content you need is ready; do not assume that navigation alone means every delayed image or application update has completed.
  3. Use a stable selector or page-specific readiness condition where possible, especially for dynamic applications.
  4. Choose viewport, full-page, element, or clip capture based on the intended output.
  5. Save to a known path or retain returned bytes, and close contexts and browsers in a finally block or try-with-resources scope.

For repeatable visual comparisons, keep the viewport, device scale, browser version, fonts, content state, and animation handling consistent. A fixed viewport controls layout dimensions; it does not freeze changing website content.

5. Troubleshoot common problems

Symptom Likely cause Fix
Layout looks like desktop when you expected mobile Viewport was set after navigation, or the page uses additional device signals. Set the viewport before navigating. Configure device emulation options too if the test requires mobile behavior, touch, or a mobile user agent.
Screenshot has the wrong dimensions The capture mode or scale differs from the intended output. Confirm the viewport dimensions and whether the screenshot should use CSS or device-pixel scale. Remember that full-page output has page height, not viewport height.
Only the visible portion appears Full-page capture is not enabled. Set setFullPage(true).
Element screenshot times out or fails The selector does not resolve to an actionable element, or the element never becomes available. Check the selector and wait for the page’s real readiness condition before capturing.
Image is blank or missing content The page may still be loading content, require interaction, or be showing a failed or blocked state. Wait for the needed content, inspect the page state, and handle site-specific consent or interaction requirements explicitly.
Output file is missing The path is invalid or points somewhere unexpected relative to the process working directory. Use an absolute path or verify the process working directory and write permissions.
Capture changes between runs Dynamic content, animation, host-dependent viewport, fonts, or device scale differ. Use an explicit viewport and context configuration; disable animations or inject a stylesheet if appropriate; stabilize the page data.
Large image consumes too much memory or storage Full-page or device-pixel capture creates many pixels. Capture only the needed element or region, use CSS scale, or choose a compressed format such as JPEG or WebP when suitable.

6. Performance, reliability, and cost

Playwright runs a browser, so capture time and resource use depend on browser startup, page loading, page complexity, and image dimensions. Reuse a browser process and context for batches where isolation requirements allow it; create separate contexts when pages need separate cookies or emulation. Close pages, contexts, and browsers when finished.

Viewport captures generally produce less output than full-page captures. Device-pixel scale increases output resolution and can increase file size and processing cost. Choose the smallest capture extent and resolution that meets the purpose. Playwright itself has no per-screenshot service fee in this workflow, but running browser processes consumes your compute, memory, storage, and engineering time.

Or skip the browser setup

If you need a screenshot without managing a browser, ScreenshotNeo is a website screenshot API and MCP server. One GET request returns a PNG, JPEG, WebP, or PDF. Its API documentation describes the available parameters, including viewport sizing.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://example.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://example.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Cookie banners, newsletter popups, and chat widgets are removed before capture, and each step can be turned off. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed; response headers identify the page verdict and billing status. An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 screenshots. View the ScreenshotNeo docs and sign up for 1,000 free screenshots a month with no card.

FAQ

Does changing the viewport resize the browser window?

page.setViewportSize changes the page viewport and resets screen size. For separate control of screen size and viewport, use context options.

Can I take a screenshot without writing a file?

Yes. Omit the path and the screenshot call returns image bytes as a byte[].

Should I use full-page capture for a long page?

Use it when the deliverable must show the entire scrollable document. For a single component or a smaller report, element or clipped capture can keep output dimensions manageable.

Does a custom viewport emulate a phone?

It sets viewport dimensions. Device-like rendering can also require device scale factor, mobile behavior, user agent, touch, and screen configuration.

Official references