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

Java HttpClient does not convert HTML into PDF by itself. It sends and receives HTTP messages. A PDF renderer—running in your JVM or behind a conversion service—must perform HTML layout, pagination and PDF generation. HttpClient can fetch the HTML before local rendering, or submit HTML/URL data to a remote converter and save the returned PDF bytes.

This guide shows both architectures, explains response handling and asset resolution, and identifies the limits you must test for CSS, fonts, images, authentication and JavaScript.

Choose the conversion architecture first

Route What HttpClient does What creates the PDF Best fit
Local JVM rendering Optionally downloads HTML and assets An in-process library such as OpenHTMLtoPDF, PDFreactor or Aspose.PDF for Java Self-contained deployments, predictable network boundaries and no conversion request hop
Remote conversion service Sends a URL, HTML, or service-specific request and receives PDF bytes The separately operated converter Centralized rendering, independent scaling or a vendor-managed engine

Compare candidates by HTML/CSS and JavaScript support, resource loading, cookies and authentication, pagination, font embedding, deployment, licensing, synchronous versus asynchronous operation, and memory behavior. A browser-grade renderer and an XHTML/CSS renderer are not interchangeable.

Route 1: Fetch HTML with HttpClient and render locally

OpenHTMLtoPDF is an in-process JVM option. Its project describes support for well-formed XML/XHTML and a bounded subset of HTML5 with CSS 2.1 and later standards, producing PDF or images. That is not full modern-browser rendering, so test representative templates rather than assuming every web page will match Chrome. The project identifies an LGPL 2.1-or-later license; review the license and your distribution obligations.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Amazon Basics Multipurpose Copy Printer Paper, 8.5 x 11 Inches, 20 lb, 92 Bright, White, 1 Ream (500 Sheets), Jam-Free
  • 1 ream (500 sheets) of 8.5 x 11 white copier and printer paper for home or office use
  • Multipurpose letter size copy paper works with laser/inkjet printers, copiers and fax machines
  • Smooth 20lb weight paper for consistent ink and toner distribution; dries quickly and resists paper jams
  • Bright white paper (92 GE; 104 Euro) offers great contrast for crisp printing and vivid color
  • Virgin copy paper providing professional quality results; acid-free to prevent yellowing

Complete Java example (JDK 17 or later)

The following program downloads a page with java.net.http.HttpClient, then passes the resulting markup to a renderer. Add the OpenHTMLtoPDF artifacts and their transitive dependencies according to the version you select from the project’s documentation.

import java.io.OutputStream;
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;
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;

public class HtmlToPdf {
    public static void main(String[] args) throws Exception {
        URI page = URI.create("https://example.com/invoice/42");
        HttpClient client = HttpClient.newBuilder()
                .followRedirects(HttpClient.Redirect.NORMAL)
                .build();

        HttpRequest request = HttpRequest.newBuilder(page)
                .header("Accept", "text/html")
                .header("User-Agent", "InvoicePdf/1.0")
                .GET()
                .build();

        HttpResponse<String> response = client.send(
                request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() < 200 || response.statusCode() >= 300) {
            throw new IllegalStateException("HTML request failed: HTTP "
                    + response.statusCode());
        }

        Path output = Path.of("invoice-42.pdf");
        try (OutputStream out = Files.newOutputStream(output)) {
            new PdfRendererBuilder()
                    .withHtmlContent(response.body(), page.toString())
                    .toStream(out)
                    .run();
        }
        System.out.println("Wrote " + output.toAbsolutePath());
    }
}

page.toString() is the base URI. It lets the renderer resolve relative images, stylesheets and other URLs against the page address. If you instead load a local document, use a file:// URI as the base. Do not pass an arbitrary filesystem path where a renderer expects a URL.

Make local conversion reliable

  • Images and CSS: verify that the renderer can reach every absolute URL and that relative URLs have the correct base URI. Package assets or serve them from a controlled host when production networking is restricted.
  • Fonts: install or register the required fonts and confirm embedding. A missing font can change line wrapping and page count.
  • Authentication: HttpClient headers and cookies used to fetch the HTML are not automatically available to a renderer when it later fetches CSS or images. Supply authenticated resources through the library’s documented hooks or make them reachable with signed URLs.
  • JavaScript: a bounded HTML/CSS renderer may not execute application JavaScript. Render server-side HTML or choose a service/library whose documented engine supports the scripts your page needs.
  • Print layout: test @page rules, page breaks, margins, tables, RTL text and long unbreakable strings with real templates.

Route 2: Send a request to a conversion service

With this architecture, HttpClient is the transport and the service is the renderer. PDFreactor documents both a Java library and a web service. Its service documentation describes synchronous POST /convert and, when enabled by the deployment, API-key query authentication; its Java integration also exposes synchronous and asynchronous conversion methods. The exact request JSON, content type, host and authentication policy belong to the installed service version, so copy them from that deployment’s REST documentation rather than treating the following shape as universal.

HttpClient response-handling pattern

Once you have the service’s documented endpoint and request body, this pattern checks status before writing a PDF and preserves the response content type for diagnostics. Replace the endpoint and request construction with the converter’s actual contract.

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.
Rank #2
HP Printer Paper | 8.5 x 11 Paper | Copy &Print 20 lb | 1 Ream Case - 500 Sheets| 92 Bright | FSC Certified | 200060
  • HP Papers is sourced from renewable forest resources and has achieved production with 0% deforestation in North America. Each ream is wrapped in a polyurethane coated paper wrapper to protect the cut sheets from moisture damage
  • Sheet size – 8.5 x 11; Thickness – 20 pounds; Brightness – 92 bright white
  • HP Copy&Print20 20 pounds printer paper is Forest Stewardship Council (FSC) certified and contributes toward satisfying credit MR1 under LEED (Leadership in Energy and Environmental Design)
  • All HP Papers provide premium performance on HP equipment, as well as on all other printer and copier equipment; 100% satisfaction guaranteed; ColorLok technology provides more vivid colors, bolder blacks and faster drying
  • Superior quality, reliability, and dependability for high-volume printing at home, at school and in the office; HP Copy&Print20 print and copy paper prevents yellowing over time to ensure a long-lasting appearance for added archival quality
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 ConversionClient {
    public static void main(String[] args) throws Exception {
        URI endpoint = URI.create("https://converter.example/convert");
        String requestBody = "<!-- construct the JSON or HTML body required by your service -->";

        HttpClient client = HttpClient.newBuilder()
                .followRedirects(HttpClient.Redirect.NORMAL)
                .build();
        HttpRequest request = HttpRequest.newBuilder(endpoint)
                .header("Content-Type", "application/json")
                .header("Accept", "application/pdf")
                // Add the service's documented Authorization header here.
                .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                .build();

        HttpResponse<byte[]> response = client.send(
                request, HttpResponse.BodyHandlers.ofByteArray());
        int status = response.statusCode();
        if (status < 200 || status >= 300) {
            String detail = new String(response.body());
            throw new IllegalStateException("Conversion failed (HTTP "
                    + status + "): " + detail);
        }
        String type = response.headers().firstValue("Content-Type").orElse("");
        if (!type.toLowerCase().contains("pdf")) {
            throw new IllegalStateException("Unexpected Content-Type: " + type);
        }
        Files.write(Path.of("result.pdf"), response.body());
    }
}

This example buffers the entire document. That is convenient for small PDFs but can consume substantial heap for reports containing many images.

Streaming large responses

For a large result, use a streaming body handler and a try-with-resources block:

HttpResponse<java.io.InputStream> response = client.send(
    request, HttpResponse.BodyHandlers.ofInputStream());
if (response.statusCode() < 200 || response.statusCode() >= 300) {
    try (var error = response.body()) {
        throw new IllegalStateException("HTTP " + response.statusCode());
    }
}
try (var in = response.body(); var out = Files.newOutputStream(Path.of("result.pdf"))) {
    in.transferTo(out);
}

Oracle’s Java SE HttpClient documentation requires the streaming response body to be obtained and then closed, cancelled or read to exhaustion so resources can be reclaimed and the request can complete. Always close the stream, including error paths. For very large jobs, prefer an asynchronous conversion API or webhook if your service provides one, rather than holding a client connection open indefinitely.

Input forms and resource resolution

PDFreactor’s 12.7.1 library manual documents three common document inputs: a local file:// URL, a remote HTTP(S) URL, or dynamic string/binary content (Java uses byte[] for binary input). The document setting is required, and a raw filesystem path is not the source form. A service that accepts a URL fetches it from the service’s network, not from the HttpClient process; private DNS, VPN access, cookies and firewall rules therefore matter. If you upload markup, confirm how that service determines the base URL for relative resources.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Amazon Basics Multipurpose Copy Printer Paper, 20 lb, 8.5 x 11 Inches, 3 Reams (1,500 Sheets), 92 Bright White for Home Use
  • 3 ream case (1,500 sheets) of 8.5 x 11 white copier and printer paper for home or office use
  • Multipurpose letter size copy paper works with laser/inkjet printers, copiers and fax machines
  • Smooth 20lb weight paper for consistent ink and toner distribution; dries quickly and resists paper jams
  • Bright white paper (92 GE; 104 Euro) offers great contrast for crisp printing and vivid color
  • Virgin copy paper providing professional quality results; acid-free to prevent yellowing

Security and operational safeguards

  • Allow-list destination hosts when converting user-supplied URLs to reduce SSRF risk.
  • Set connect, request and overall job timeouts; do not let a stalled asset hold a worker forever.
  • Limit HTML size, image dimensions and PDF output size before writing to disk.
  • Never log API keys, cookies or authorization headers. Store secrets outside source code.
  • Use HTTPS and validate certificates. Treat converter responses as untrusted until status, content type and (where required) the PDF signature are checked.
  • Use separate temporary files and atomic moves so a failed conversion cannot replace a valid PDF.

Choosing a renderer

OpenHTMLtoPDF

Choose it when an in-process JVM renderer with its documented XHTML/HTML5 and CSS scope fits your templates. Its output is local, but browser-only behavior and complex JavaScript may require redesign or another engine.

PDFreactor

PDFreactor documents both a Java library and a web service, with vendor-documented features including authentication, headers and cookies, font fallback and pagination. Decide whether you want an embedded library or a separately operated service, then follow the API version’s request and licensing terms.

Aspose.PDF for Java

Aspose’s HTML guide documents loading options affecting layout scaling, CSS media, page-rule priority, font embedding, resource resolution and single-page behavior. Treat those as documented capabilities and validate them against your own page designs.

Common failures and fixes

HTTP 401 or 403

The service or source page requires credentials. Add the documented authorization mechanism, cookies or headers, and confirm that the renderer—not only your initial HttpClient request—can access linked resources.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Amazon Basics Multipurpose Copy Printer Paper, 20 lb, 8.5 x 11 Inches, 5 Reams (2,500 Sheets), 92 Bright White
  • 5 ream case (2,500 sheets) of 8.5 x 11 white copier and printer paper for home or office use
  • Multipurpose letter size copy paper works with laser/inkjet printers, copiers and fax machines
  • Smooth 20lb weight paper for consistent ink and toner distribution; dries quickly and resists paper jams
  • Bright white paper (92 GE; 104 Euro) offers great contrast for crisp printing and vivid color
  • Virgin copy paper providing professional quality results; acid-free to prevent yellowing

HTML appears instead of a PDF

You may have received an error page with a successful-looking transport path. Check the status, Content-Type and error body before saving. Do not infer PDF output from the requested URL.

Missing images or styles

Check absolute versus relative URLs, the base URI, TLS trust, redirects and resource authentication. A converter fetching a URL from its own network may not reach localhost or private hosts.

Blank pages or wrong pagination

Inspect CSS @page rules, print media, fixed heights, oversized tables and unavailable fonts. Compare a minimal template with the production one, then add assets incrementally.

Out-of-memory errors

Replace ofByteArray() with ofInputStream() or a file-oriented body handler, cap input and output sizes, and move lengthy jobs to an asynchronous workflow.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
HP Printer Paper | 8.5 x 11 Paper | Office 20 lb | 3 Ream Case - 1500 Sheets | 92 Bright | Made in USA - FSC Certified | 112090C, White
  • Made in USA: HP Papers is sourced from renewable forest resources and has achieved production with 0% deforestation in North America.
  • Optimized for HP technology: All HP Papers provide premium performance on HP equipment, as well as on all other printer and copier equipment.
  • Perfect everyday office paper: Superior quality, reliability, and dependability for high-volume printing at home, at school and in the office. Perfect for everyday black and white printing.
  • Certified sustainable: HP Office20 20lb printer paper is Forest Stewardship Council (FSC) certified and contributes toward satisfying credit MR1 under LEED (Leadership in Energy and Environmental Design).
  • ColorLok technology printing paper: ColorLok technology provides more vivid colors, bolder blacks and faster drying.

Request never completes

Set explicit timeouts and investigate slow or cyclic assets. For streaming responses, consume or close the body on every branch.

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 your goal is a clean screenshot or PDF of a public page rather than server-side document templating, ScreenshotNeo provides an HTTP API and MCP server. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups and chat widgets; bot checks, blank pages, timeouts, failed loads and cache hits are not billed, and response headers identify the page verdict and billing status.

For a PDF or screenshot workflow, call the API directly (set the output options documented at ScreenshotNeo docs):

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

ScreenshotNeo also offers take_screenshot, get_page_info and capture_pdf tools through its MCP server for Claude, Cursor and other MCP clients. The Free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

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

Equivalent calls from Python and Node.js

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 bytes = Buffer.from(await res.arrayBuffer());

Frequently Asked Questions

Can Java HttpClient convert HTML to PDF without another library?

No. HttpClient transports requests and responses; a PDF renderer or conversion service must perform layout and PDF generation.

Should I use a URL or upload HTML?

Use the input form required by your selected converter. URL conversion is simplest when the renderer can reach every asset; uploaded HTML gives more control but may require an explicit base URL.

Why does my PDF differ from the browser page?

Your renderer may support a narrower HTML/CSS set, may not execute JavaScript, or may lack the page’s fonts and authenticated assets. Test a representative template against the exact renderer version.

Quick Recap

Bestseller No. 1
Amazon Basics Multipurpose Copy Printer Paper, 8.5 x 11 Inches, 20 lb, 92 Bright, White, 1 Ream (500 Sheets), Jam-Free
Amazon Basics Multipurpose Copy Printer Paper, 8.5 x 11 Inches, 20 lb, 92 Bright, White, 1 Ream (500 Sheets), Jam-Free
1 ream (500 sheets) of 8.5 x 11 white copier and printer paper for home or office use; Virgin copy paper providing professional quality results; acid-free to prevent yellowing
$6.97
Bestseller No. 2
HP Printer Paper | 8.5 x 11 Paper | Copy &Print 20 lb | 1 Ream Case - 500 Sheets| 92 Bright | FSC Certified | 200060
HP Printer Paper | 8.5 x 11 Paper | Copy &Print 20 lb | 1 Ream Case - 500 Sheets| 92 Bright | FSC Certified | 200060
Sheet size – 8.5 x 11; Thickness – 20 pounds; Brightness – 92 bright white
$6.97
Bestseller No. 3
Amazon Basics Multipurpose Copy Printer Paper, 20 lb, 8.5 x 11 Inches, 3 Reams (1,500 Sheets), 92 Bright White for Home Use
Amazon Basics Multipurpose Copy Printer Paper, 20 lb, 8.5 x 11 Inches, 3 Reams (1,500 Sheets), 92 Bright White for Home Use
Virgin copy paper providing professional quality results; acid-free to prevent yellowing
$23.99
Bestseller No. 4
Amazon Basics Multipurpose Copy Printer Paper, 20 lb, 8.5 x 11 Inches, 5 Reams (2,500 Sheets), 92 Bright White
Amazon Basics Multipurpose Copy Printer Paper, 20 lb, 8.5 x 11 Inches, 5 Reams (2,500 Sheets), 92 Bright White
Virgin copy paper providing professional quality results; acid-free to prevent yellowing
$34.85

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.