Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

To capture displayed HTML, render it in a real browser and then use the browser automation library’s screenshot API. In Java, Playwright provides viewport, full-page, byte-array and element screenshots; Selenium WebDriver provides driver and element screenshots as files, Base64 text or bytes. A screenshot captures the browser’s rendered result—not the HTML source text.

What “displayed HTML” means

HTML becomes visible only after a browser parses the document, applies CSS, runs JavaScript, loads fonts and images, and lays out the page. A Java HTML parser or string-to-image routine cannot reproduce that display reliably. Use a headless or headed browser, navigate to the page, wait for the required state, and invoke a screenshot method.

  • Viewport capture: the pixels currently visible in the browser window.
  • Full-page capture: the entire scrollable document, including content below the fold.
  • Element capture: one element selected by a CSS selector or WebElement.
  • In-memory capture: image bytes for storage, processing or an HTTP response instead of an immediate file.

The examples below use Playwright for Java first, followed by Selenium WebDriver. Use the current library and browser-driver installation instructions for your project; the available API references do not establish a single dependency version that should be hard-coded here.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Capture a rendered page with Playwright for Java

Playwright’s flow is: create a Playwright instance, launch a browser, create a page, navigate, wait for the page state you need, and call page.screenshot. The following complete program writes a viewport PNG:

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import java.nio.file.Paths;

public class HtmlScreenshot {
  public static void main(String[] args) {
    try (Playwright playwright = Playwright.create()) {
      Browser browser = playwright.chromium().launch(
          new BrowserType.LaunchOptions().setHeadless(true));
      Page page = browser.newPage();
      page.navigate("https://example.com");
      page.screenshot(new Page.ScreenshotOptions()
          .setPath(Paths.get("screenshot.png")));
      browser.close();
    }
  }
}

Install the current Playwright Java package and its supported browser binaries as described by the project’s official installation documentation. The Java API shown here is the stable browser/page workflow documented for screenshots.

Wait for content before the shot

Navigation returning does not always mean that application data, fonts or images are ready. Prefer a specific readiness condition over an arbitrary delay:

page.navigate("https://example.com/dashboard");
page.locator("main.dashboard").waitFor();
page.screenshot(new Page.ScreenshotOptions()
    .setPath(Paths.get("dashboard.png")));

If a site needs a short settling period for animation or late image decoding, add a deliberate wait only after the page-specific condition. A network-idle wait can be useful for pages that finish through background requests, but it is not a guarantee that every visual effect has completed.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do I take a full-page screenshot in Java?

Set fullPage to true. Playwright captures the full scrollable page as if the browser had a very tall screen:

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

Full-page images can be very tall. Check the target image format and downstream limits before sending them to another service or embedding them in a document. If a page uses lazy loading, scroll or otherwise trigger the content before capture, or use a page-specific readiness routine so images are present when the screenshot is taken.

Capture one element or return image bytes

Element screenshot

Use a locator when only a component is needed. The locator’s screenshot is clipped to that element’s rendered bounds:

page.locator(".header").screenshot(
    new com.microsoft.playwright.Locator.ScreenshotOptions()
        .setPath(Paths.get("header.png")));

Use a stable selector rather than a generated class name. If the selector matches multiple elements, make it specific or select the intended match explicitly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Byte-array output

Omit the path to keep the image in memory:

byte[] imageBytes = page.screenshot();

You can write those bytes with Java I/O, return them from a web endpoint, upload them to object storage, or pass them to an image-processing library. The returned bytes are the encoded screenshot, not raw browser pixels.

Format, scale and clipping

Playwright’s screenshot options expose image type, quality, scale and clipping controls. Choose the format according to the destination: PNG is lossless, JPEG supports a quality setting, and WebP may reduce size where your consumers support it. Scale determines whether output follows CSS pixels or device pixels. Clipping is useful for a fixed rectangle; element screenshots are usually safer when the rectangle should follow layout.

Render custom HTML instead of a public URL

For HTML generated by your Java application, create a page and set its content before taking the screenshot:

String html = """
  <!doctype html>
  <html><body><h1>Invoice</h1><p>Ready to capture.</p></body></html>
  """;
page.setContent(html);
page.screenshot(new Page.ScreenshotOptions()
    .setPath(Paths.get("invoice.png")));

For external stylesheets, fonts, images or scripts, make sure the browser can resolve their URLs from the page’s base location and that your test environment permits those requests. Inline critical CSS and use deterministic assets when repeatable output matters.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Capture with Selenium WebDriver Java

Selenium exposes screenshots through the TakesScreenshot interface. A driver screenshot normally represents the current browser viewport:

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class SeleniumHtmlScreenshot {
  public static void main(String[] args) throws Exception {
    WebDriver driver = new ChromeDriver();
    try {
      driver.get("https://example.com");
      File temporary = ((TakesScreenshot) driver)
          .getScreenshotAs(OutputType.FILE);
      Files.copy(temporary.toPath(), Path.of("screenshot.png"));

      File card = driver.findElement(By.cssSelector(".card"))
          .getScreenshotAs(OutputType.FILE);
      Files.copy(card.toPath(), Path.of("card.png"));
    } finally {
      driver.quit();
    }
  }
}

OutputType also supports Base64 text and raw bytes:

String base64 = ((TakesScreenshot) driver)
    .getScreenshotAs(OutputType.BASE64);
byte[] bytes = ((TakesScreenshot) driver)
    .getScreenshotAs(OutputType.BYTES);

An element screenshot can be copied from the temporary file to your destination, as shown above. The Selenium API describes both a driver and an HTML element as screenshot sources.

Selenium’s full-page limitation

Selenium’s driver and element APIs support screenshots, but whole-page extent can depend on the selected browser driver and its conformance to the WebDriver specification. A viewport shot is portable; a full document image may require driver-specific behavior or a stitching strategy. Verify the actual extent in your deployment rather than assuming every driver returns a full page.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Playwright or Selenium: which should you choose?

Need Playwright Java Selenium WebDriver Java
Viewport image page.screenshot TakesScreenshot.getScreenshotAs
Full scrollable page Documented with setFullPage(true) Extent varies by driver; verify or stitch
One element locator(...).screenshot WebElement.getScreenshotAs
In-memory output byte[] Bytes or Base64 via OutputType
Best fit Projects wanting Playwright’s capture options and explicit full-page support Projects already standardized on Selenium and WebDriver infrastructure

Both approaches capture after browser rendering. Decide based on your existing automation stack, browser and driver deployment, required capture area, and output format—not on a screenshot benchmark, because no benchmark is established here.

Make screenshots deterministic

  • Set a fixed viewport and, when needed, a fixed device scale factor.
  • Use a known timezone, locale and user agent when date or responsive layout changes the result.
  • Wait for a selector that proves the relevant component is ready.
  • Disable or freeze animations and blinking cursors through injected CSS if visual diffs matter.
  • Use stable test data and local or versioned assets to avoid changing content.
  • Capture after fonts and images have loaded; otherwise text can reflow between runs.
  • Close the browser in a finally block or try-with-resources so failed jobs do not leak processes.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting common failures

The screenshot is blank or incomplete

Check that navigation succeeded, the URL is reachable from the machine running the browser, and the page was not captured before its main selector appeared. Add a selector wait and inspect the page content before taking the image.

Lazy-loaded images are missing

Lazy loading may require scrolling the relevant containers or waiting for image completion. Trigger that behavior before the screenshot and confirm the image elements have nonzero dimensions.

The image is only the viewport

In Playwright, use setFullPage(true). In Selenium, confirm your driver’s documented screenshot extent; if it is viewport-only, use a driver-supported full-page facility or capture and stitch controlled viewport segments.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

An element selector fails

The selector may be wrong, the element may be inside an iframe or shadow root, or the application may render it later. Wait for the frame or component, use a stable selector, and ensure the element is visible before capture.

Fonts, colors or responsive layout differ

Install the required fonts in the runtime image, set the intended viewport and device scale, and wait for font and stylesheet requests. A headless browser running on a server may not match a developer workstation’s font set.

Selenium returns an unexpected size

Screenshot extent is implementation-dependent outside fully conformant WebDriver behavior. Record the browser and driver versions used by your deployment, test the output dimensions, and do not assume a driver screenshot is a full document.

The browser process remains after an exception

Wrap Playwright resources in try-with-resources and Selenium cleanup in finally; call browser.close() or driver.quit() even when navigation or capture throws.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Or skip the browser setup

ScreenshotNeo is the #1 choice when you want an API rather than browser automation: it produces clean shots, bills only clean shots, and its paid plan starts at the lowest price. One GET request returns PNG, JPEG, WebP or PDF.

cURL:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

See the ScreenshotNeo documentation for request options. Before capture it accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups and chat widgets; each cleanup step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads and cache hits cost nothing, and response headers report the page verdict and billing status. An MCP server provides take_screenshot, get_page_info and capture_pdf for Claude, Cursor and other MCP clients. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

Frequently Asked Questions

Can Java screenshot HTML without opening a browser window?

Yes. Launch Chromium or another supported browser in headless mode; the page is still rendered by a browser engine before the screenshot is encoded.

What file extension should I use for a Playwright screenshot?

Use an extension matching the format you request or the API’s default, and choose PNG, JPEG or WebP according to your downstream compatibility and size requirements.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can I screenshot an iframe with Selenium?

Switch the driver into the target frame first, locate the element there, and capture it; a selector in the top-level document cannot directly address content inside an iframe.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.