Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minuteSome links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
Java’s java.net.http.HttpClient does not convert HTML into PDF. It is the HTTP transport: it sends a request and receives bytes. A PDF renderer—running in your JVM or behind an HTTP service—performs HTML layout, pagination, font handling and PDF generation. In practice, you either use HttpClient to call a conversion service, or use it to fetch HTML that a local Java renderer converts.
Choose the rendering architecture first
The right implementation depends on where rendering should happen. Keep these concerns separate:
| Approach | What HttpClient does | What creates the PDF | Typical trade-offs |
|---|---|---|---|
| Local JVM library | Optionally downloads HTML or assets | An in-process renderer such as OpenHTMLtoPDF or Aspose.PDF for Java | No conversion network hop; you own renderer memory, fonts, assets and licensing |
| Remote conversion service | Sends a URL, HTML, JSON or multipart request and receives PDF bytes | The service’s renderer | Separate operations and scaling; request schema, authentication and network access must match that service |
| PDFreactor library or service | Used only when your integration needs HTTP retrieval or a web-service call | PDFreactor | Vendor-documented Java and web-service routes; verify the deployed version and contract |
Oracle’s Java SE 23 HttpClient documentation describes request and response handling, not HTML layout. PDFreactor documents both Java-library and web-service integrations at its Java page. Use the JDK version your application actually runs; the examples below use the Java 17+ java.net.http API.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchRoute 1: fetch HTML with HttpClient, then render locally
This route keeps the conversion in your process. The following complete example downloads an HTML document and passes it to OpenHTMLtoPDF. Add the OpenHTMLtoPDF dependency using the version approved for your project; the project documents its current coordinates and releases on GitHub.
#1 Best Overall
- 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
Runnable Java example
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
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 java.time.Duration;
public class HtmlToPdf {
public static void main(String[] args) throws Exception {
URI page = URI.create("https://example.com/invoice/123");
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(20))
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
HttpRequest request = HttpRequest.newBuilder(page)
.timeout(Duration.ofSeconds(60))
.header("Accept", "text/html,application/xhtml+xml")
.GET()
.build();
HttpResponse<String> response = client.send(
request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() < 200 || response.statusCode() >= 300) {
throw new IOException("HTML request failed: HTTP " + response.statusCode());
}
String html = response.body();
try (ByteArrayOutputStream pdf = new ByteArrayOutputStream()) {
new PdfRendererBuilder()
.withHtmlContent(html, page.toString())
.toStream(pdf)
.run();
Files.write(Path.of("invoice.pdf"), pdf.toByteArray());
}
}
}
The second argument to withHtmlContent is the base URL. Supplying it lets the renderer resolve relative images, stylesheets and fonts against the source page. If your HTML is generated in memory, use a suitable HTTPS base URL or bundle resources so relative links remain resolvable.
Know the local renderer’s limits
OpenHTMLtoPDF says it renders a reasonable subset of well-formed XML/XHTML and some HTML5 with CSS 2.1 and later standards, and can produce PDF or images. That is not the same as a full browser: complex JavaScript applications, unsupported CSS, video and browser-only APIs may not render. Validate representative templates, including fonts, images, tables, page breaks and long content, against the exact library version you deploy.
A commercial alternative is Aspose.PDF for Java. Its HTML-loading documentation describes options for layout scaling, CSS media, page-rule priority, font embedding, resource resolution and single-page behavior. Treat those capabilities as vendor documentation and test your own layouts.
Route 2: call an HTML-to-PDF service with HttpClient
With a service, HttpClient sends the conversion request and receives a PDF response. Services differ: one may accept a document URL, another raw HTML, JSON or multipart data. Do not assume that a request body or authentication method from one product works with another.
Rank #2
- 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
Response-handling pattern
This pattern is intentionally contract-neutral. Replace the URI, headers and body with the selected service’s documented request. It shows the important parts: explicit timeout, status validation, content-type checking and binary output.
import java.io.IOException;
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 java.time.Duration;
public class PdfServiceClient {
public static void main(String[] args) throws Exception {
String htmlUrl = "https://example.com/report.html";
URI endpoint = URI.create("https://converter.example/v1/convert");
String json = "{"url":"" + htmlUrl + ""}";
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(20))
.build();
HttpRequest request = HttpRequest.newBuilder(endpoint)
.timeout(Duration.ofSeconds(120))
.header("Authorization", "Bearer YOUR_TOKEN")
.header("Content-Type", "application/json")
.header("Accept", "application/pdf")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
HttpResponse<byte[]> response = client.send(
request, HttpResponse.BodyHandlers.ofByteArray());
int status = response.statusCode();
if (status < 200 || status >= 300) {
String error = new String(response.body());
throw new IOException("Conversion failed: HTTP " + status + ": " + error);
}
String type = response.headers().firstValue("Content-Type").orElse("");
if (!type.toLowerCase().contains("application/pdf")) {
throw new IOException("Expected PDF, received Content-Type: " + type);
}
Files.write(Path.of("report.pdf"), response.body());
}
}
The JSON above is a shape, not a universal API. For example, PDFreactor’s REST documentation describes a synchronous POST /convert endpoint and API-key query authentication when enabled by the deployment. Consult the exact PDFreactor web-service documentation for its request fields, host and authentication configuration before adapting the example.
URL input, HTML input and asset access
- If the service receives a URL, the service—not your Java process—must be able to reach that URL and every linked asset. Private DNS, firewalls, login cookies and authorization headers therefore matter.
- If you upload HTML, confirm how the renderer resolves relative URLs. You may need a base URL, absolute asset URLs or an archive of the assets.
- PDFreactor 12.7.1 documents local
file://URLs, remote HTTP(S) URLs and dynamic string or byte-array content. It explicitly requires a document setting and does not accept a raw filesystem path as the source form; use a file URL.
Memory, streaming and reliability
Small and medium PDFs
BodyHandlers.ofByteArray() is simple but buffers the entire PDF. It is suitable when output sizes are bounded and your heap has adequate headroom. Always check the status before writing bytes to a file; a failed request may return an HTML or JSON error that would otherwise be saved as .pdf.
Free tools Windows power users keep installed
One-click scans. No signup required.
Large PDFs
Use a file or streaming body handler for large documents, and write with try-with-resources. Oracle notes that streaming response bodies must eventually be obtained and closed, cancelled or read to exhaustion so resources can be reclaimed and the HTTP exchange can complete. Keep conversion timeouts longer than connection timeouts, and cap accepted output sizes where your service permits it.
Rank #3
- 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
Retries and idempotency
Retry only failures that are safe to repeat, such as a transient connection failure or selected 5xx response. A conversion may be expensive, and a repeated POST can create duplicate work. Prefer an idempotency key or the provider’s asynchronous job mechanism when available. Do not retry authentication errors, malformed HTML responses or most 4xx statuses without fixing the request.
HTML, CSS and asset checklist
- Use print-oriented CSS such as
@page, explicit margins and deliberate page breaks. - Embed or make fonts available to the renderer; verify licensing and fallback behavior.
- Use absolute HTTPS asset URLs when the renderer runs outside your network.
- Test images, SVG, tables, nested lists and very long words at the target page size.
- Decide whether the output needs selectable text, tagged accessibility, PDF/A or JavaScript; support varies by engine.
- Sanitize untrusted HTML and restrict outbound fetching to prevent server-side request forgery. Do not let user-controlled markup access internal metadata endpoints.
Local library versus service: a practical decision
| Choose local rendering when… | Choose a service when… |
|---|---|
| You need predictable in-process deployment, can provision fonts and memory, and accept the renderer’s HTML/CSS scope and license. | You want conversion isolated from the application, provider-managed scaling, or a renderer exposed through an existing HTTP contract. |
| Documents and assets must remain inside your network and the library supports them. | Your organization already operates a conversion endpoint and can provide it the required network access. |
| You can test and maintain renderer upgrades yourself. | You prefer service-level operations, while accepting network latency, authentication and provider availability concerns. |
Common failures and fixes
“HttpClient converted nothing”
HttpClient only transported the request. Add a renderer such as OpenHTMLtoPDF, or call a documented conversion service.
HTTP 401 or 403
Check the service’s required credential location, scope and encoding. PDFreactor’s API-key query authentication applies only when that service is configured to require it; do not generalize it to other providers.
A PDF file contains an error page
Inspect status and Content-Type before saving. Log a bounded error body for non-2xx responses and verify the endpoint path and request schema.
Rank #4
- 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
Missing images, CSS or fonts
Fix the base URL or use absolute URLs, then verify that the renderer can reach protected assets. For a remote service, configure the service’s headers or cookies according to its documentation.
Layout differs from Chrome
Browser rendering and JVM renderers support different HTML, CSS and JavaScript subsets. Simplify unsupported markup, use print CSS, or select an engine whose documented scope matches your templates. Test page breaks and fonts rather than relying on a single short sample.
Request times out
Measure HTML retrieval, asset loading and rendering separately. Increase the request timeout only after checking for blocked resources, redirect loops and pages waiting indefinitely for JavaScript. For long jobs, use the provider’s asynchronous API if offered.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Or skip the browser setup
If your actual need is a clean PDF or screenshot of a public web page rather than server-side template rendering, ScreenshotNeo provides a website capture API and MCP server. It accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups and chat widgets; each cleanup step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and the response identifies the page verdict and billing status in X-Page-Verdict and X-Billed headers.
Its API can return PNG, JPEG, WebP or PDF. The documented one-call request is:
Best Value
- 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.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo API documentation for PDF output and capture options. The same service includes an MCP server with take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients. It also supports full-page capture with lazy images loaded, CSS-selector element capture, device and viewport controls, dark mode, retina scale, custom CSS or JavaScript, click and wait actions, request blocking, headers, cookies, user agents, authorization, timezone and geolocation, resizing, caching, signed links, asynchronous jobs, webhooks, bulk capture and a usage API.
There is a free allowance of 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account to try it.
Frequently Asked Questions
Can Java HttpClient render JavaScript before creating a PDF?
No. HttpClient transports HTTP. JavaScript execution depends on the renderer or service you choose; verify that engine’s documented browser and scripting support.
Should I send a URL or the HTML string?
Send whichever form the selected converter documents. URL input is convenient but requires the converter to reach every asset; uploaded HTML gives control over content but still needs a base URL or bundled resources for relative links.
How do I prevent a failed response from becoming a corrupt PDF?
Check the HTTP status and, where appropriate, the Content-Type before writing the body. Log the bounded error body for non-success responses and use a PDF signature check if your application requires one.
The Bottom Line
Use HttpClient as the transport and select a renderer deliberately: OpenHTMLtoPDF or another local library for in-process conversion, or a documented service such as PDFreactor for remote conversion. Validate the renderer’s HTML/CSS scope, asset access, response status and memory behavior before deploying.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Quick Recap
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.

