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.

A Java servlet does not render a web page or take a screenshot by itself. To capture a page on the server, run a browser automation engine such as Selenium or Playwright from your Java application, capture the viewport, full page, or a particular element, then save the resulting image or send it through the servlet response. This guide shows both approaches and explains the server-side details that matter for persistence and concurrent requests.

What a servlet does—and what takes the screenshot

A servlet is an HTTP request-and-response component: it receives a request and produces a response. The Servlet API does not provide a browser that lays out HTML, executes JavaScript, or paints a page into pixels. For a screenshot of a rendered web page, your application needs a browser automation/rendering engine in addition to the servlet. The Jakarta Servlet specification describes the servlet model; the API documentation likewise treats request handling separately from page rendering (Jakarta Servlet Specification 6.0; Servlet API documentation).

The basic flow is: validate the requested target, ask Selenium or Playwright to load it in a real browser, capture the requested pixels, and either persist the image or write it to the HTTP response. Decide what “screenshot” means for your endpoint before coding:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Viewport: the visible browser area at the chosen viewport dimensions.
  • Full page: the page’s scrollable content captured as a single image, where the automation engine supports it.
  • Element: the rendered area corresponding to a selected page element.

These are different outputs. A viewport capture can omit content below the fold; a full-page capture may be very tall; an element capture depends on locating the intended element after the page has loaded.

#1 Best Overall
Hewlett Packard Enterprise ProLiant MicroServer Gen11 Tower Server, Intel Xeon 6315P Processor, 16GB Memory, External 180W US Power Supply (HPE Smart Choice P86811-005)
  • MODEL P86811-005: HPE ProLiant MicroServer Gen11 preconfigured with Intel Xeon 6315P 2.80GHz 4-core processor, ideal for small business IT, edge workloads, and on-premise compute
  • WHISPER-QUIET & SPACE-SAVING: Ultra-compact mini tower design fits easily in small office spaces; supports wall, flat, or vertical placement for deployment flexibility
  • READY OUT OF THE BOX: Includes 16GB DDR5 UDIMM memory (expandable to 128GB), dedicated iLO-M.2 port kit, embedded Intel VROC SATA controller for Gen11 servers, 180w external power adapter and 1/1/1 year warranty for dependable plug-and-play server operation
  • EXPANDABLE DESIGN: Two PCIe slots (including PCIe 5.0) and four LFF-NHP drive bays provide robust options for storage and component scalability. Features new MR408i-p controller support for enhanced storage performance
  • INTEGRATED REMOTE MANAGEMENT: Comes with HPE iLO 6 and embedded TPM 2.0, enabling secure, remote administration through browser, command line, or API with shared port access

Choose a browser automation option

Option Documented capture targets Output forms Useful when
Selenium Java TakesScreenshot WebDriver and web elements File and Base64 are shown in the API documentation; output is selected through an OutputType Your application already uses Selenium/WebDriver or you need a driver/element screenshot workflow.
Playwright Java screenshots Page viewport, full page, and locator/element Save to a path or capture as a byte array You want a direct byte-array or full-page capture path in Playwright Java.

Neither choice is universally better. Compare the capture target you need, whether bytes or files fit your storage/response path, and which browser runtime your application can deploy and operate. The documentation establishes these capture APIs, not a universal server installation recipe or a current compatible-version matrix. Match your chosen library, browser, Java runtime, servlet container, and deployment permissions to your own environment.

Capture and save a screenshot with Playwright Java

This example uses Playwright’s byte-array capture and writes the bytes to an application-managed file. It is a standalone Java method that can be called by a servlet service layer. Add Playwright Java and its required browser runtime using the installation method and versions appropriate for your project; the official screenshot API is documented in the Playwright Java screenshots guide.

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import com.microsoft.playwright.options.ScreenshotType;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public final class PageScreenshot {
    private PageScreenshot() {}

    public static byte[] capturePng(String url, Path destination)
            throws IOException {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(
                    new BrowserType.LaunchOptions().setHeadless(true));
            try {
                Page page = browser.newPage();
                page.navigate(url);
                byte[] png = page.screenshot(
                        new Page.ScreenshotOptions()
                                .setType(ScreenshotType.PNG)
                                .setFullPage(true));
                Files.createDirectories(destination.toAbsolutePath().getParent());
                Files.write(destination, png);
                return png;
            } finally {
                browser.close();
            }
        }
    }
}

The returned byte array and saved file contain the same PNG data. If you only need the file, you can avoid retaining the returned bytes after writing; if you need an HTTP response, return the bytes to the servlet layer instead of saving them first. The example requests a full-page image. For a viewport screenshot, omit setFullPage(true). Playwright also supports capturing a specific locator and taking screenshot data as a byte array; consult the API documentation for the exact overloads and options that match your installed version.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Dell Optiplex 7050 SFF Desktop PC Intel i7-7700 4-Cores 3.60GHz 32GB DDR4 1TB SSD WiFi BT HDMI Duel Monitor Support Windows 11 Pro Excellent Condition(Renewed)
  • Model: Dell OptiPlex 7050 Small Form Factor (SFF)
  • Processor: Intel Core i7-7700 3.60 GHz
  • Memory: 32GB DDR4 Ram
  • Storage: 1TB Solid State Drive (SSD) Fast Boot + Storage
  • Operating System: Windows 11 Pro (64-bit)

Call it from a servlet and return the image

Keep browser work and validation in a service class rather than putting all capture logic into the servlet. The following sketch shows the response boundary; connect it to the service method above and use your application’s error handling and URL policy.

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.nio.file.Path;

@WebServlet("/screenshots")
public class ScreenshotServlet extends HttpServlet {
    private final ScreenshotService service = new ScreenshotService();

    @Override
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
            throws ServletException, IOException {
        String url = request.getParameter("url");
        if (url == null || url.isBlank()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Missing url parameter");
            return;
        }

        try {
            byte[] png = service.capturePng(url);
            response.setContentType("image/png");
            response.setContentLength(png.length);
            response.getOutputStream().write(png);
        } catch (IllegalArgumentException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Invalid target URL");
        } catch (Exception e) {
            response.sendError(HttpServletResponse.SC_BAD_GATEWAY,
                    "Screenshot capture failed");
        }
    }
}

interface ScreenshotService {
    byte[] capturePng(String url) throws Exception;
}

The service interface is illustrative; wire in your actual implementation and dependency management. This servlet uses the Jakarta namespace (jakarta.servlet). Older applications may use javax.servlet instead. Use the imports and API level supported by your actual servlet container rather than mixing namespaces. Set the content type before writing the body; servlet response guidance describes setting response metadata before obtaining/writing the body (Jakarta HttpServlet API documentation).

Save through the service instead of the response

For durable storage, write to an application-controlled directory or object store and return a stable identifier or authorized download URL. Do not accept an arbitrary destination path from the caller: resolve output paths under a configured storage root and reject traversal outside it. Use a random or otherwise collision-resistant filename, and avoid exposing sensitive filesystem paths. If the endpoint is meant to both save and preview, capture once, persist the bytes, then stream those same bytes or retrieve them through a separate authorized endpoint.

Rank #3
Dell PowerEdge R730xd Server 24B SFF 2U, 2X Intel Xeon E5-2690 v4 2.6Ghz (28-cores Total), 128GB DDR4 RAM, 4X 1.2TB 10K SAS 2.5” 12Gb/s HDD, H730P 2GB RAID, NIC 10Gb + I350 1Gb (Renewed)
  • Dell PowerEdge R730xd 24B SFF 2U Server
  • 2x Intel Xeon E5-2690 v4 2.6Ghz 14-Core (28-cores Total)
  • 128GB DDR4 RAM – 4x 1.2TB 10K SAS 2.5” 12Gb/s
  • Dell H730P mini 2GB 12Gb/s RAID
  • 2x 750W PSU - 2x 10Gb SFP+ 2x 1Gb (RJ45) NIC

Capture with Selenium Java

Selenium’s TakesScreenshot API works with a WebDriver or an element and lets the caller choose an output form. The Java API documents getScreenshotAs(OutputType.FILE) and Base64 output (TakesScreenshot API). The example below assumes you have already created and navigated a configured WebDriver.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.io.FileHandler;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public final class SeleniumCapture {
    private SeleniumCapture() {}

    public static Path capturePage(WebDriver driver, Path destination)
            throws IOException {
        File temporary = ((TakesScreenshot) driver)
                .getScreenshotAs(OutputType.FILE);
        Files.createDirectories(destination.toAbsolutePath().getParent());
        FileHandler.copy(temporary, destination.toFile());
        return destination;
    }

    public static Path captureElement(WebDriver driver, String cssSelector,
                                      Path destination) throws IOException {
        WebElement element = driver.findElement(By.cssSelector(cssSelector));
        File temporary = ((TakesScreenshot) element)
                .getScreenshotAs(OutputType.FILE);
        Files.createDirectories(destination.toAbsolutePath().getParent());
        FileHandler.copy(temporary, destination.toFile());
        return destination;
    }
}

The first method captures through the driver; the second captures the selected element. Selenium’s documentation describes the temporary-file output as temporary rather than durable application storage, so copy it to a managed destination if you need to keep it. For a servlet response, select an output form that yields bytes or read the copied file and stream it, setting the response MIME type before writing the output stream. Do not return a temporary path to a caller and assume the file will remain available.

Server-side details that determine whether this works reliably

Browser runtime and permissions

The server must be able to launch or connect to the browser runtime your automation library uses. Confirm that the browser binaries and required system dependencies exist in the deployment environment, the process has permission to execute them, and temporary storage is writable. Containers and restricted hosting environments may require additional configuration; the cited API pages do not establish one setup that applies everywhere.

Rank #4
Hewlett Packard Enterprise ProLiant MicroServer Gen11 Tower Server, Intel Pentium Gold G7400 Processor, 16GB Memory, 1TB HDD Storage, External 180W US Power Supply (HPE Smart Choice P74439-005)
  • MODEL P74439-005: Compact and affordable HPE ProLiant MicroServer Gen11 powered by Intel Pentium Gold G7400 3.7GHz processor, ideal for file sharing, NAS, and basic business workloads
  • READY OUT OF THE BOX: Includes 16GB DDR5 UDIMM memory (expandable to 128GB), one 1TB SATA 6G Business Critical HDD, embedded Intel VROC SATA, dedicated iLO-M.2 port kit, 180w external power adapter and 1/1/1 warranty for dependable plug-and-play server operation
  • WHISPER-QUIET & SPACE-SAVING: Ultra-compact mini tower design fits easily in small office spaces; supports wall, flat, or vertical placement for deployment flexibility
  • INTEGRATED REMOTE MANAGEMENT: Comes with HPE iLO 6 and embedded TPM 2.0 for secure, license-free remote server administration through shared port access
  • EXPANDABLE DESIGN: Two PCIe slots (including PCIe 5.0) and four LFF-NHP drive bays provide robust options for storage and component scalability. Features new MR408i-p controller support for enhanced storage performance

Concurrency and resource lifecycle

Servlet containers may handle multiple requests concurrently. Do not store per-request URLs, output paths, driver state, or screenshot bytes in mutable servlet instance fields. Use request-local state and distinct output names. Close browser and page resources reliably, including on exceptions. The sample uses structured cleanup for the browser; production code should also define how browser processes, timeouts, and any reuse or pooling are managed. The available API guidance does not prescribe a production pooling design.

URL validation and access control

A screenshot endpoint that accepts a URL can become a way to make server-side requests to destinations the caller should not reach. Apply an explicit policy: allow only intended schemes and hosts, reject local/private network targets where appropriate, limit redirects, and enforce timeouts and request-size controls. Do not let a client supply a filesystem path. These are application security controls, not features automatically provided by the servlet or screenshot API.

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

Response versus persistent file

  • Image response: set image/png, image/jpeg, or the actual output type before writing bytes. Use the output stream for binary data.
  • Download: add a deliberate content-disposition header if the client should download rather than display the image.
  • Persistent artifact: store under an application-controlled location or object store, with authorization and retention rules appropriate to the content.
  • Large full-page images: account for memory and response size; a tall page can produce substantially more image data than a viewport capture.

Troubleshooting common failures

  • Class or package not found: check that the automation dependency is on the application classpath and that servlet imports match the container’s namespace: javax.servlet or jakarta.servlet.
  • Browser fails to launch: verify browser/runtime installation, executable permissions, required system libraries, and the container’s restrictions. The Java API alone does not install every deployment prerequisite.
  • Blank or incomplete image: the page may not have finished rendering or may load content asynchronously. Wait for an appropriate page condition or target element before capturing; validate that the URL is reachable from the server, not just from a developer’s browser.
  • Element not found: check that the selector is correct for the rendered page and that the element exists after navigation and any client-side rendering.
  • Saved file disappears: a Selenium temporary screenshot file is not durable storage. Copy it promptly to an application-managed path.
  • Wrong or overwritten image under load: generate a unique destination per request and avoid shared mutable state for filenames or capture results.
  • Image appears corrupted in the response: set the response content type and write raw bytes to getOutputStream(); do not mix binary output with a character writer or write an error page after part of the image body has been committed.
  • Request hangs or consumes resources: configure suitable navigation and application-level time limits, and ensure browser cleanup occurs on failures. Choose limits based on the pages and environment you support; no universal value is established by the cited documentation.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If you need a screenshot endpoint without deploying and maintaining browser automation in your Java service, ScreenshotNeo is a website screenshot API and MCP server. Send one GET request with a URL; the response can be a PNG, JPEG, WebP, or PDF. It can accept cookie/consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets before capture, with each step configurable. Bot checks/CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing; response headers report the page verdict and whether it was billed. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to AI agents using Claude, Cursor, or another MCP client.

For the available parameters and response details, see the ScreenshotNeo API documentation. Example request (replace the URL and key):

Best Value
Sale
KAMRUI Pinova P2 Mini PC, AMD Ryzen 7330U(4 Cores, 8 Threads, Up to 4.3GHz), 16GB RAM 256GB SSD, Zen3 Architecture 7nm Processor, 8MB L3 Smart Cache Mini Computers,Triple 4K Display Home/Business
  • 【AMD Ryzen 7330U】 – The Efficiency-Tuned Powerhouse,AMD Ryzen 7330U (Zen 3, SMT, 4C/8T) in KAMRUI P2 mini PC crushes rivals: Intel i3-10110U (2C/4T, 2019) and N95 (4 efficiency cores, no HT, single-channel memory). Vs predecessor Ryzen 3 4300U (4C/4T): ~50% faster single-core, ~46% multi-core, 8MB L3 cache (vs 4MB). Beats both Intel chips hugely in multi-core, making heavy multitasking, coding, data work smooth at just 15W TDP. High-end power in a cool, efficient box.
  • 【AMD Radeon Graphics】– Triple 4K Vision & Fluidity,The integrated Radeon Graphics (based on the modern Vega architecture with 6 CUs) is a visual beast, outclassing the iGPU offerings from both AMD's prior generation and Intel. The Intel UHD Graphics (i3-10110U/N95) struggles with single-channel memory and low execution units, crippling its gaming performance and barely handling basic 4K video without stuttering. While the older Radeon Vega 5 (4300U) was decent, our 7330U's Radeon Graphics (6 CUs) pushes the boundaries, delivering higher graphics clock speeds (up to 1.8GHz) and significantly better rendering capabilities. It can drive triple 4K@60Hz displays with zero lag, edit photos/videos.
  • 【Generous Storage & Easy Expansion】The KAMRUI Pinova P2 mini desktop computers comes with 16GB LPDDR4X RAM (higher frequency, lower power) for buttery‑smooth multitasking, and a 256GB M.2 SSD for blazing fast boot‑up, quick file transfers, and no more long loading screens. It also features two storage expansion slots (1x M.2 2280 SATA/NVMe PCIe 3.0 slot + 1x M.2 2280 SATA slot), supporting up to 4TB total (not included). You’ll have all the space you need for projects, media, and important data.
  • 【Triple 4K Display Output】The KAMRUI Pinova P2 mini desktop pc is equipped with HDMI 2.0 ×1 + DP 1.4 ×1 + USB 3.2 Gen2 Type‑C ×1 (with DP Alt Mode), enabling simultaneous triple 4K@60Hz output. Whether for home entertainment, remote work, or conference room presentations, it delivers an immersive visual experience. Two USB 3.2 Gen2 Type‑A ports (up to 10Gbps – 21x faster than USB 2.0) make data transfers and device expansion a breeze.
  • 【USB 3.2 Gen2 Type‑C: 10Gbps & Versatile Connectivity】The USB 3.2 Gen2 Type‑C port on the KAMRUI P2 small pc supports 10Gbps data transfer speeds and can also output DisplayPort 1.4 video. Together with Gigabit LAN, Wi‑Fi, and Bluetooth, you get a fast, flexible, and productive connected environment – wired or wireless.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

ScreenshotNeo’s Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots. Sign up for the free plan to try it.

Frequently Asked Questions

Can a servlet take a screenshot using only the Servlet API?

No. The Servlet API handles HTTP requests and responses; a browser automation/rendering engine must render the page and capture its pixels.

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

How do I capture only one element?

Use Selenium’s element screenshot support or Playwright’s locator screenshot support, after ensuring the element exists in the rendered page.

Should I save a screenshot to a file or return bytes?

Use bytes for an immediate image response or in-memory processing; use controlled durable storage when the image must persist beyond the request.

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.