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.

Use wkhtmltopdf for PDF output and wkhtmltoimage for images. Neither tool is a Java library: each is a headless Qt WebKit command-line executable. In Java, you either start the installed executable yourself (for maximum control) or use a third-party wrapper that starts it for you. The executable must be installed, executable by the service account, and tested in the same environment as your application.

This guide shows a direct Java implementation for an HTML string, explains wrapper trade-offs, covers deployment and security, and then shows a browser-free alternative with ScreenshotNeo.

Choose the correct executable

Goal Executable Typical output
Paginated document wkhtmltopdf PDF
Rendered snapshot wkhtmltoimage PNG, JPEG and other image formats

Do not pass an image-output command when you need a PDF: wkhtmltoimage does not create PDFs. Both programs render with Qt WebKit and run headlessly.

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.

The upstream project identifies 0.12.6 as its stable series, released June 11, 2020. Its GitHub repository was archived and made read-only on January 2, 2023. That makes this legacy software: verify binary availability, operating-system compatibility and vulnerability exposure before standardizing on it.

#1 Best Overall
PDF Converter Ultimate - Convert PDF files into Word, Excel, PowerPoint and others - PDF converter software with OCR recognition compatible with Windows 11 / 10 / 8.1 / 8 / 7
  • Convert your PDF files into Word, Excel & Co. the easy way
  • Convert scanned documents thanks to our new 2022 OCR technology
  • Adjustable conversion settings
  • No subscription! Lifetime license!
  • Compatible with Windows 11, 10, 8.1, 7 - Internet connection required

Prepare a complete HTML string

Include a doctype, character encoding and all CSS needed for deterministic rendering. Relative URLs resolve against a base location; for a self-contained conversion, use absolute URLs or inline assets.

String html = """
    <!doctype html>
    <html>
      <head>
        <meta charset="UTF-8">
        <style>
          @page { size: A4; margin: 18mm; }
          body { font-family: sans-serif; color: #222; }
          h1 { page-break-after: avoid; }
        </style>
      </head>
      <body>
        <h1>Invoice 1042</h1>
        <p>Generated from a Java string.</p>
      </body>
    </html>
    """;

Java text blocks require Java 15 or newer. On older Java versions, build the same value with ordinary string concatenation and escaped quotes.

Direct Java conversion with ProcessBuilder

The most transparent integration is to write the string to a temporary UTF-8 file, invoke wkhtmltopdf, and read the resulting PDF. This avoids guessing a wrapper’s artifact version and lets you capture exit status and stderr.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Install a compatible wkhtmltopdf package in the image or host. Confirm wkhtmltopdf --version works for the account running Java.
  2. Use an absolute executable path in production, such as an application configuration value, rather than relying on PATH.
  3. Write the HTML with UTF-8 and create an output file in a directory writable by the service account.
  4. Start the process, drain stdout and stderr, enforce a timeout, and check the exit code and output size.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.List;
import java.util.concurrent.TimeUnit;

public final class WkhtmlPdf {
  public static Path convert(String html, Path output, String executable)
      throws IOException, InterruptedException {
    Path input = Files.createTempFile("wkhtml-", ".html");
    try {
      Files.writeString(input, html, StandardCharsets.UTF_8,
          StandardOpenOption.TRUNCATE_EXISTING);
      Files.createDirectories(output.toAbsolutePath().getParent());

      List<String> command = List.of(
          executable,
          "--encoding", "utf-8",
          input.toAbsolutePath().toString(),
          output.toAbsolutePath().toString());
      Process process = new ProcessBuilder(command)
          .redirectErrorStream(true)
          .start();
      String log = new String(process.getInputStream().readAllBytes(),
          StandardCharsets.UTF_8);
      if (!process.waitFor(90, TimeUnit.SECONDS)) {
        process.destroyForcibly();
        throw new IOException("wkhtmltopdf timed out");
      }
      if (process.exitValue() != 0 || !Files.isRegularFile(output)
          || Files.size(output) == 0) {
        throw new IOException("wkhtmltopdf failed (exit "
            + process.exitValue() + "): " + log);
      }
      return output;
    } finally {
      Files.deleteIfExists(input);
    }
  }

  public static void main(String[] args) throws Exception {
    String html = """
        <!doctype html><meta charset="UTF-8">
        <h1>Hello PDF</h1><p>Café</p>
        """;
    convert(html, Path.of("build/report.pdf"),
        System.getenv().getOrDefault("WKHTMLTOPDF", "wkhtmltopdf"));
  }
}

For image output, keep the same structure but invoke wkhtmltoimage and use an image filename:

List<String> command = List.of(
    wkhtmltoimage, "--format", "png", input.toString(), "report.png");

Option names vary by version and platform. Consult the executable’s own --help output and validate every option in your target image.

Rank #2
Doxillion Free Document Converter – Converts DOCX, DOC, PDF, WPS and Many More Files Quickly [Download]
  • Convert over 50 document file formats.
  • Preview your files from Doxillion before converting them.
  • Use batch conversion to convert thousands of files at once.
  • Enjoy an easy-to-use, intuitive interface with a Drag and Drop file option.
  • Burn your converted or original files directly to disc.

Using a Java wrapper

A third-party Java wrapper can expose a page/input API, conversion options and a success response instead of requiring you to assemble ProcessBuilder calls. The wrapper documentation demonstrates supplying page content from a string, configuring options, and converting to a destination. It explicitly requires a separately installed, working wkhtmltopdf executable; adding the Java dependency does not install the renderer.

Because wrapper coordinates and behavior change, select the current published Maven or Gradle artifact from that project’s documentation, pin the version, and inspect its release notes. Confirm how it discovers the binary, how it reports stderr, and whether it supports your operating system. One documented wrapper caveat is that concurrent PDF generations are not supported; it also reports timeout issues with some options. Serialize calls or isolate workers unless your exact version documents safe concurrency.

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

Wrapper integration checklist

  • Set the executable path explicitly when the wrapper permits it.
  • Pass the HTML string through the wrapper’s page/input method, not as an unescaped shell command.
  • Set encoding, paper size, margins, headers and footers through typed options where available.
  • Check the conversion result and preserve diagnostic output.
  • Run a version-pinned integration test inside the production container.

Rendering options that affect real documents

Page geometry and pagination

Use CSS @page rules and, where needed, command options for paper size, orientation and margins. Test tables, long code blocks, widows/orphans and page breaks with representative data. A successful process does not guarantee attractive pagination.

Fonts and assets

Install every required font in the runtime image. Remote fonts and images require network access and valid certificates; local files may require the executable’s local-file policy. Prefer absolute, allow-listed asset URLs or inline data for reproducibility.

JavaScript and dynamic pages

Qt WebKit is not a modern browser. Pages that depend on current JavaScript frameworks, complex CSS or delayed API calls may render incompletely. Use a documented delay or wait condition only after measuring the page’s actual readiness; a fixed delay increases latency without proving that data loaded.

Rank #3
PDF Extra Ultimate | Complete PDF Reader and Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | Yearly License | 1 Windows PC & 2 Mobile Devices | 1 User
  • EDIT text, images & designs in PDF documents. ORGANIZE PDFs. Convert PDFs to Word, Excel & ePub.
  • READ and Comment PDFs – Intuitive reading modes & document commenting and mark up.
  • CREATE, COMBINE, SCAN and COMPRESS PDFs
  • FILL forms & Digitally Sign PDFs. PROTECT and Encrypt PDFs
  • 1 Year License for 1 Windows & 2 Mobile (Android and/or iOS) devices.

Headers, cookies and authentication

Do not put secrets in query strings or HTML. Supply controlled headers or cookies through supported options, redact command logs, and ensure temporary files have restrictive permissions.

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

Security and isolation

The project documentation gives this warning: “Do not use wkhtmltopdf with any untrusted HTML – be sure to sanitize any user-supplied HTML/JS, otherwise it can lead to complete takeover of the server it is running on!” Treat sanitization as necessary, not sufficient. Run conversion in a locked-down container or sandbox with a non-privileged user, restricted filesystem access, limited outbound network access and CPU/memory/time quotas. Never expose the converter as an unrestricted network service.

Review the licenses for the 0.12.6 binary, native libraries, wrapper and any fonts before distribution. The upstream project identifies its software as LGPLv3; obligations can differ across bundled components.

Deployment, reliability and cost considerations

  • Binary management: bake a known binary into the image or install it during deployment, then verify its checksum and run a smoke conversion.
  • Process limits: use a bounded queue, timeout and maximum HTML size. Clean temporary files on success, failure and cancellation.
  • Observability: record version, elapsed time, exit code and sanitized stderr. Keep the input identifier, not sensitive HTML, in application logs.
  • Concurrency: the cited wrapper does not support concurrent PDF generations. Even with direct invocation, benchmark your CPU and memory limits before increasing worker count.
  • Licensing and maintenance: the archived upstream project receives no ordinary repository development. Revalidate security and platform support whenever your base image or Java runtime changes.

When another renderer is a better fit

The project’s status guidance points to Puppeteer for pages dependent on dynamic JavaScript and suggests considering WeasyPrint or commercial Prince for controlled report generation. These are scenario recommendations, not a current benchmark. Compare Java integration, HTML/CSS and JavaScript fidelity, print pagination, runtime size, isolation, maintenance and license terms.

For a Java-focused alternative, iText’s pdfHTML material shows a Java API that converts HTML input to PDF. That example alone does not establish current license terms, supported CSS, or suitability for your document, so verify those points before adoption.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
PDF Extra Lifetime - Professional PDF Editor - Best Adobe Acrobat Pro Alternative - Lifetime License for Windows PC
  • Perfect Adobe Acrobat Pro alternative – lifetime license for Windows 10 and 11.
  • EDIT text, images, pages, hyperlinks, designs in PDF documents. ORGANIZE PDFs.
  • READ and Comment on PDFs – Intuitive reading modes & document commenting and mark up tools!
  • CREATE, COMBINE, SCAN and COMPRESS PDFs.
  • FILL forms & Digitally Sign PDFs. Work with Digital certificates
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns PNG, JPEG, WebP or PDF. It accepts cookie/consent banners before capture and removes more than 60 known consent platforms, newsletter popups and chat widgets; each step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and response headers identify the page verdict and billing result.

For a URL-based capture, use the documented endpoint and options at https://screenshotneo.com/docs/:

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

The same request from Java is:

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;

var uri = URI.create("https://api.screenshotneo.com/v1/shot"
    + "?access_key=YOUR_API_KEY&url=https%3A%2F%2Fstripe.com");
var response = HttpClient.newHttpClient().send(
    HttpRequest.newBuilder(uri).GET().build(),
    HttpResponse.BodyHandlers.ofByteArray());
if (response.statusCode() / 100 != 2) throw new RuntimeException("HTTP " + response.statusCode());
Files.write(Path.of("shot.webp"), response.body());

ScreenshotNeo also supports full-page captures with lazy images, CSS-selector element capture, dark mode, device presets, arbitrary viewports, retina scale, PDF paper settings and ranges, HTML/CSS-to-image, custom CSS and JavaScript, clicks, selector waits, delays, network-idle waits, request blocking, headers, cookies, user agents, Authorization, timezone, geolocation, transparent backgrounds, resizing, configurable caching, signed links, asynchronous jobs with signed webhooks, bulk capture for 100 URLs per call, a usage API and an OpenAPI specification. An MCP server exposes take_screenshot, get_page_info and capture_pdf to Claude, Cursor and other MCP clients.

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

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

Troubleshooting

“Cannot run program” or exit 127

The executable is missing or not on the service account’s PATH. Install it, use an absolute path, and verify permissions as the same user.

Empty or partial PDF

Inspect stderr and HTML separately. Check encoding, blocked local files, missing fonts, certificate errors, remote asset access and JavaScript timing. Capture a minimal self-contained document to isolate the cause.

Best Value
Doxillion Free Document Converter for Mac – Converts DOCX, DOC, PDF, WPS and Many More Files Quickly [Download]
  • Convert over 50 document file formats.
  • Preview your files from Doxillion before converting them.
  • Use batch conversion to convert thousands of files at once.
  • Enjoy an easy-to-use, intuitive interface with a Drag and Drop file option.
  • Burn your converted or original files directly to disc.

Timeouts

Look for unreachable assets, never-ending scripts and waits that cannot be satisfied. Set a finite process timeout, abort the child, and cap page size and network scope.

Works locally but fails in a container

Compare installed fonts, shared libraries, executable permissions, sandbox restrictions, DNS, certificates and writable temporary directories. Reproduce with a smoke test during image build.

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

Concurrent jobs fail intermittently

Use a bounded worker pool and serialized conversion when using the cited wrapper, or switch to isolated worker processes after validating direct invocation under load.

Frequently Asked Questions

Can a Java dependency install wkhtmltopdf automatically?

No. The Java wrapper and the renderer are separate; install and verify the wkhtmltopdf executable yourself.

Can wkhtmltoimage produce a PDF?

No. Use wkhtmltopdf for PDF output; wkhtmltoimage produces image formats.

Is wkhtmltopdf suitable for untrusted user HTML?

Not without strong sanitization and isolation. The project warns that unsafe HTML or JavaScript can enable complete server takeover.

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

What should replace wkhtmltopdf for a JavaScript-heavy page?

Evaluate a browser-based renderer such as Puppeteer, or a controlled-report engine such as WeasyPrint or Prince, against your fidelity, deployment and licensing requirements.

Quick Recap

Bestseller No. 1
PDF Converter Ultimate - Convert PDF files into Word, Excel, PowerPoint and others - PDF converter software with OCR recognition compatible with Windows 11 / 10 / 8.1 / 8 / 7
PDF Converter Ultimate - Convert PDF files into Word, Excel, PowerPoint and others - PDF converter software with OCR recognition compatible with Windows 11 / 10 / 8.1 / 8 / 7
Convert your PDF files into Word, Excel & Co. the easy way; Convert scanned documents thanks to our new 2022 OCR technology
$29.99
Bestseller No. 2
Doxillion Free Document Converter – Converts DOCX, DOC, PDF, WPS and Many More Files Quickly [Download]
Doxillion Free Document Converter – Converts DOCX, DOC, PDF, WPS and Many More Files Quickly [Download]
Convert over 50 document file formats.; Preview your files from Doxillion before converting them.
Bestseller No. 3
PDF Extra Ultimate | Complete PDF Reader and Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | Yearly License | 1 Windows PC & 2 Mobile Devices | 1 User
PDF Extra Ultimate | Complete PDF Reader and Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | Yearly License | 1 Windows PC & 2 Mobile Devices | 1 User
READ and Comment PDFs – Intuitive reading modes & document commenting and mark up.; CREATE, COMBINE, SCAN and COMPRESS PDFs
$83.88
Bestseller No. 4
PDF Extra Lifetime - Professional PDF Editor - Best Adobe Acrobat Pro Alternative - Lifetime License for Windows PC
PDF Extra Lifetime - Professional PDF Editor - Best Adobe Acrobat Pro Alternative - Lifetime License for Windows PC
Perfect Adobe Acrobat Pro alternative – lifetime license for Windows 10 and 11.; EDIT text, images, pages, hyperlinks, designs in PDF documents. ORGANIZE PDFs.
$99.99
Bestseller No. 5
Doxillion Free Document Converter for Mac – Converts DOCX, DOC, PDF, WPS and Many More Files Quickly [Download]
Doxillion Free Document Converter for Mac – Converts DOCX, DOC, PDF, WPS and Many More Files Quickly [Download]
Convert over 50 document file formats.; Preview your files from Doxillion before converting them.

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.