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

Use Java’s ProcessBuilder to launch the separately installed wkhtmltoimage executable. Pass the executable, each option, the input URL or HTML file, and the output filename as separate list items; wait for completion, capture diagnostics, enforce a timeout, and reject non-zero exit codes. This is the practical Java integration because the Java wrapper libraries commonly found for this project target wkhtmltopdf (PDF), not wkhtmltoimage (images).

What wkhtmltoimage does—and what Java must provide

wkhtmltoimage is a command-line HTML-to-image converter built on Qt WebKit. Its documented command shape is:

wkhtmltoimage [OPTIONS]... <input file> <output file>

The program is not a Java library. Install a compatible binary on the machine running your application, or package and provision one as part of your deployment. Java then starts that operating-system process. The project repository has been archived read-only since January 2, 2023, so check binary availability, platform support, security requirements, and rendering compatibility before choosing it for a new system.

The input operand can be an HTTP(S) URL or a local HTML file. The output should be an explicit image filename such as page.png, page.jpg, or page.webp, depending on the format supported by the installed build.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

A safe Java ProcessBuilder implementation

The following class demonstrates a production-oriented starting point. It avoids shell quoting, redirects the converter’s diagnostics, creates a temporary output file, and applies a deadline. Adapt the executable path and policy to your operating system.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public final class Wkhtmltoimage {
    public static Path capture(
            Path executable,
            String input,
            Path output,
            int width,
            Duration timeout) throws IOException, InterruptedException {

        List<String> command = new ArrayList<>();
        command.add(executable.toString());
        command.add("--format");
        command.add("png");
        command.add("--width");
        command.add(Integer.toString(width));
        command.add(input);
        command.add(output.toString());

        Process process = new ProcessBuilder(command)
                .redirectError(ProcessBuilder.Redirect.INHERIT)
                .start();

        boolean finished = process.waitFor(timeout.toMillis(), TimeUnit.MILLISECONDS);
        if (!finished) {
            process.destroy();
            if (!process.waitFor(2, TimeUnit.SECONDS)) {
                process.destroyForcibly();
            }
            throw new IOException("wkhtmltoimage timed out after " + timeout);
        }

        int exitCode = process.exitValue();
        if (exitCode != 0) {
            throw new IOException("wkhtmltoimage exited with code " + exitCode);
        }
        if (!Files.isRegularFile(output) || Files.size(output) == 0) {
            throw new IOException("Converter reported success but produced no image: " + output);
        }
        return output;
    }

    public static void main(String[] args) throws Exception {
        Path output = Path.of("output.png");
        capture(
                Path.of("/opt/wkhtmltopdf/bin/wkhtmltoimage"),
                "https://example.com",
                output,
                1200,
                Duration.ofSeconds(90));
        System.out.println("Wrote " + output.toAbsolutePath());
    }
}

Every flag and value is a separate list element. Do not build one quoted command string and hand it to a shell: quoting rules differ between Windows and Unix-like systems, and a URL or filename can contain characters that a shell interprets. ProcessBuilder starts the executable directly.

Reading error output instead of inheriting it

Redirect.INHERIT is useful for a command-line service because converter warnings appear in the application’s logs. If you need structured logging, leave the error stream as a pipe and consume it on a separate thread (or use redirectErrorStream(true) and read the merged stream). Always drain output when it is piped; otherwise a verbose process can block on a full operating-system buffer.

Choosing an executable path

Use an absolute, configured path in production. A bare wkhtmltoimage relies on the service account’s PATH, which may differ from an interactive shell. On Windows, configure the full .exe path. Verify the binary at startup with a harmless version command or a health check, and fail clearly if it is missing or not executable.

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

Basic commands and image settings

URL input

wkhtmltoimage --format png --width 1200 https://example.com output.png

Local HTML input

wkhtmltoimage --format png --width 1200 /srv/pages/report.html /srv/output/report.png

When local HTML references nearby CSS, images, fonts, or JavaScript, local-file access rules determine whether those resources can be read. The manual provides --disable-local-file-access and --allow <path>. Prefer disabling broad access and allowing only the directories the page needs.

Format, quality, dimensions, and cropping

  • --format selects the image format.
  • --quality controls quality where the selected format supports it.
  • --width supplies a screen-width guide; it is not automatically a strict crop. Smart-width behavior affects how the final width is resolved.
  • --height, crop controls, zoom, and related sizing options tune the output. The default height is calculated from page content.

Test dimensions with the actual pages you will render. A responsive layout can change when the viewport width changes, and a page that visually fits a browser window may still produce a very tall image.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

JavaScript, dynamic pages, and completion timing

JavaScript is enabled by default in common configurations, but the command exposes explicit controls:

  • --enable-javascript or --disable-javascript;
  • --javascript-delay <msec> to wait after loading;
  • --run-script to execute supplied JavaScript;
  • --window-status to wait for a page-reported status.

Use the smallest delay that reliably allows your page to render. Increasing it raises latency for every capture. A status-based wait can be more deterministic for an application that controls the page: have the page set the expected window status after data and images are ready, then pass that value to the converter. If a page never sets it, the process can wait until your external timeout kills it.

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.

JavaScript-heavy sites may depend on browser features unavailable in the Qt WebKit rendering engine. A successful exit code means the process completed, not that every modern framework, font, animation, or cross-origin request rendered exactly as it would in a current browser.

Authentication, network access, and request behavior

The command-line options include custom headers, cookies, proxy configuration, and load-error handling. Use them only when needed:

  • Pass authentication headers or cookies for pages that require a session.
  • Configure an outbound proxy when the runtime network requires one.
  • Decide whether a failed subresource should make the whole capture fail; load-error options affect that policy.

Never put long-lived secrets in URLs, process arguments visible to other users, or captured images. Where your operating system permits, restrict process visibility and use short-lived credentials. For local pages, explicitly allow only the asset directories required by the document.

Handling files, concurrency, and reliability

Use unique temporary paths

Generate a per-request output path rather than writing every job to output.png. This prevents concurrent requests from overwriting one another and avoids serving a partially written file. Write into a private temporary directory, validate the result, then atomically move it into its final location.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Set resource limits

Apply a wall-clock timeout, cap concurrent conversions, and limit input size and destination paths. A page can be slow, intentionally recursive, or unexpectedly large. Process isolation is an advantage of the CLI, but it does not remove the need for operating-system quotas and cleanup of abandoned child processes.

Record useful diagnostics

Log the input identifier (without credentials), executable version, options, duration, exit code, output size, and stderr. These values distinguish a missing binary from a page-load failure and a successful conversion that produced an unusable file.

Common failures and fixes

“Cannot run program” or executable not found

Cause: the binary is not installed, the configured path is wrong, or the service account cannot execute it.
Fix: install/provision the binary for the target platform, use an absolute path, verify permissions, and test under the same account that runs Java.

Exit code is non-zero

Cause: invalid options, an inaccessible input, a failed load, or a converter-level error.
Fix: preserve stderr, run the exact argument list manually in a controlled environment, check URL reachability and local-file permissions, and confirm that the option names match the installed version.

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.

Blank or incomplete image

Cause: JavaScript has not finished, a required asset was blocked, or the page relies on unsupported browser behavior.
Fix: add a narrowly chosen JavaScript delay or window-status wait, allow the required local directory, verify fonts and network access, and simplify or server-render the page when the legacy engine cannot execute it.

Local images or styles are missing

Cause: local-file access restrictions or incorrect relative paths.
Fix: use correct file URLs/paths and --allow for the specific asset directory; do not enable unrestricted local access unless the isolation risk is acceptable.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

The process hangs

Cause: a page never reaches its wait condition, a network request does not complete, or Java code is not draining a piped stream.
Fix: enforce a timeout, consume diagnostics concurrently, avoid an unconditional status wait, and terminate the process tree according to your platform’s process-management policy.

Output dimensions are surprising

Cause: --width is a screen-width guide and page content determines height; responsive breakpoints or smart-width behavior may also apply.
Fix: set the intended viewport width, review crop and zoom options, and inspect the generated image dimensions rather than assuming the CSS viewport equals the bitmap size.

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

CLI invocation versus native integration

Approach Integration work Deployment characteristics When it fits
Java ProcessBuilder Low: construct arguments, supervise a child process, validate output Requires a separately installed compatible executable; process isolation is straightforward Most Java services that need a practical image conversion command
Native C image binding High: JNI/JNA or another native interop layer, native libraries, lifecycle and callbacks More platform packaging and native-runtime work; in-process integration Teams that specifically need the documented C interface and can own native deployment
Java wrappers found for wkhtmltopdf Varies They wrap the PDF executable and do not establish image support Use only for PDF requirements, not as a wkhtmltoimage solution

The project documents an image C binding lifecycle—initialize, create and set global settings, create a converter, add callbacks, convert, and destroy it. That is a native API, not a ready-made Java API. Do not copy a wkhtmltopdf wrapper class and assume it produces images.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

When wkhtmltoimage is a poor fit

Choose another renderer when you require current browser standards, modern JavaScript frameworks, strict security updates, or pixel parity with Chromium-based users. The Qt WebKit stack and archived project status warrant an explicit compatibility and risk review. This does not by itself establish a vulnerability; it means your team should evaluate the binary, page content, and operational exposure before production use.

Or skip the browser setup

ScreenshotNeo is a hosted screenshot API and MCP server. One GET request returns a PNG, JPEG, WebP, or PDF, so your Java service does not need to install or supervise a wkhtmltoimage binary. Cookie and consent banners, newsletter popups, and chat widgets are removed before capture. Bot checks/CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status.

Using the API from Java requires only an HTTP client:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;

public class ScreenshotNeoExample {
    public static void main(String[] args) throws Exception {
        String url = "https://stripe.com";
        String endpoint = "https://api.screenshotneo.com/v1/shot"
                + "?access_key=YOUR_API_KEY"
                + "&url=" + java.net.URLEncoder.encode(url, java.nio.charset.StandardCharsets.UTF_8);
        HttpRequest request = HttpRequest.newBuilder(URI.create(endpoint)).GET().build();
        HttpResponse<byte[]> response = HttpClient.newHttpClient()
                .send(request, HttpResponse.BodyHandlers.ofByteArray());
        if (response.statusCode() / 100 != 2) {
            throw new IllegalStateException("ScreenshotNeo HTTP " + response.statusCode());
        }
        Files.write(Path.of("shot.webp"), response.body());
    }
}

See the ScreenshotNeo documentation for request options. It also provides the MCP tools take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients; options include full-page lazy-image loading, CSS-selector element capture, device presets, retina scale, custom CSS/JavaScript, click and wait controls, request blocking, headers, cookies, user agent, timezone, geolocation, transparent backgrounds, resizing, TTL caching, signed links, asynchronous webhooks, bulk capture, usage data, and an OpenAPI specification.

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

The Free plan includes 1,000 screenshots each month with no card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan. Create a free ScreenshotNeo account to try it.

cURL, Python, and Node.js equivalents

These calls use the same API endpoint and can help you test behavior before wiring Java into a service.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const buffer = Buffer.from(await res.arrayBuffer());
require('fs').writeFileSync('shot.webp', buffer);

Frequently Asked Questions

Is wkhtmltoimage a Maven dependency?

No. The practical integration runs an installed executable. Java wrapper artifacts commonly documented for this project target wkhtmltopdf and PDF output, not the image converter.

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

Can I pass a web URL instead of an HTML file?

Yes. The URL is the input operand; provide it as its own ProcessBuilder argument and write an explicit image output path.

Why did Java report success but no image exists?

Validate the exit code, then check that the output path is writable, the file exists, and its size is greater than zero. A successful process does not replace those application-level checks.

Should I use the native C binding from Java?

Only when you need its in-process native interface and can support JNI/JNA-style packaging, callbacks, and platform-specific libraries. ProcessBuilder is simpler to deploy.

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.

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