Free tools Windows power users keep installed
One-click scans. No signup required.
Yes. With iText pdfHTML, put the CSS text inside a <style> element in the HTML string, then call HtmlConverter.convertToPdf. Use the overload that accepts ConverterProperties and set a base URI whenever the HTML refers to relative stylesheets, images, or fonts.
The shortest working solution
For a self-contained document, no temporary CSS file is required. Build one HTML string, insert the stylesheet in the document head, and write the PDF to an output stream:
String css = "body { font-family: sans-serif; color: #222; }"
+ ".invoice { width: 100%; }";
String html = "<html><head><style>" + css + "</style></head>"
+ "<body><div class='invoice'>Invoice</div></body></html>";
try (OutputStream out = Files.newOutputStream(Path.of("out.pdf"))) {
HtmlConverter.convertToPdf(html, out);
}
The convertToPdf(String, OutputStream) overload is intended for exactly this case: it converts a Java String containing HTML into PDF bytes in the supplied stream.
Prepare the Java project
Add iText’s com.itextpdf:html2pdf Maven artifact (the official iText installation documentation lists the current dependency coordinates), then import the converter classes and standard Java I/O types:
#1 Best Overall
- 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.
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.ConverterProperties;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
Choose the library version approved for your application rather than copying an unpinned version from an old example. Review iText’s licensing terms before release: AGPL licensing applies to non-commercial use, while commercial use requires a commercial license. Your deployment model, not just the fact that the code is internal, determines which terms apply.
Insert dynamic CSS into the HTML string
When CSS is generated at runtime, keep the HTML structure explicit and place the stylesheet in <head>. A StringBuilder is convenient when several rules or optional blocks are assembled:
StringBuilder html = new StringBuilder();
html.append("<!doctype html>")
.append("<html><head><meta charset='UTF-8'>")
.append("<style>")
.append("body { margin: 0; font-family: sans-serif; }")
.append(".total { font-weight: 700; text-align: right; }")
.append("</style></head>")
.append("<body><p class='total'>€123.45</p></body></html>");
try (OutputStream out = Files.newOutputStream(Path.of("invoice.pdf"))) {
HtmlConverter.convertToPdf(html.toString(), out);
}
Keep CSS and markup separate in your application code until the final assembly. That makes escaping, testing, and template review easier. The resulting value still reaches pdfHTML as one HTML string; no CSS file has to be created.
Use a base URI for relative assets
Inline CSS solves the stylesheet problem, but it does not tell the renderer where a relative image, font, or linked resource lives. For markup such as <img src='images/logo.png'> or a font URL relative to the template directory, configure ConverterProperties.setBaseUri:
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 minuteRank #2
- 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.
ConverterProperties properties = new ConverterProperties()
.setBaseUri(Path.of("/srv/app/templates").toUri().toString());
String html = "<html><head>"
+ "<style>body { font-family: 'InvoiceFont'; }</style>"
+ "</head><body>"
+ "<img src='images/logo.png' alt='Company logo'>"
+ "</body></html>";
try (OutputStream out = Files.newOutputStream(Path.of("out.pdf"))) {
HtmlConverter.convertToPdf(html, out, properties);
}
The base URI is the directory against which relative references are resolved. A relative URL cannot be interpreted reliably when the converter receives only an in-memory string, because the string has no filesystem location of its own. Set the URI to the directory that actually contains the referenced files, and verify that the Java process has permission to read them.
When to inline and when to reference
- Inline small, generated rules in
<style>when the document is self-contained. - Use a base URI for shared images, font files, or other assets maintained beside a template.
- Use stable, resolvable URLs for every resource; a browser resolving an asset on your workstation does not prove the server-side converter can resolve it.
Complete example with an external image and output file
This example combines generated CSS, a relative image, a base URI, and a try-with-resources output stream:
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
public class InvoicePdf {
public static void main(String[] args) throws Exception {
String css = "body { font-family: sans-serif; color: #222; }"
+ ".invoice { width: 100%; padding: 24px; }"
+ ".total { text-align: right; font-weight: bold; }";
String html = "<!doctype html><html><head>"
+ "<meta charset='UTF-8'><style>" + css + "</style>"
+ "</head><body>"
+ "<section class='invoice'>"
+ "<img src='images/logo.png' alt='Company logo'>"
+ "<h1>Invoice 1042</h1>"
+ "<p class='total'>$250.00</p>"
+ "</section></body></html>";
ConverterProperties properties = new ConverterProperties()
.setBaseUri(Path.of("/srv/app/templates").toUri().toString());
try (OutputStream out = Files.newOutputStream(Path.of("invoice-1042.pdf"))) {
HtmlConverter.convertToPdf(html, out, properties);
}
}
}
The output file is complete when the method returns and the stream closes. For an HTTP endpoint, replace the file stream with the response’s output stream and set the response content type to application/pdf.
Understand pdfHTML’s CSS boundary
iText pdfHTML is an HTML/CSS renderer, not a full browser. Its feature matrix documents support for many common tags and paged-media rules, while identifying browser-oriented areas that are unsupported or partial, including scripts, CSS animations and transitions, CSS custom properties, and several modern layout features.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallCrashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteRank #3
- 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.
Design templates for predictable output
- Prefer conventional block and table layouts for invoices, reports, and forms.
- Use print-oriented rules that the feature matrix lists as supported rather than relying on browser-only behavior.
- Replace JavaScript-driven layout with server-side HTML generation.
- Test every font, image, and page-break rule in the exact library version used in production.
A page that looks correct in Chrome can therefore differ in the PDF. Treat the feature matrix as the compatibility checklist for your actual selectors and properties, not as a guarantee that arbitrary web pages will render identically.
iText pdfHTML or OpenHTMLToPDF?
OpenHTMLToPDF is a credible pure-Java alternative. Its project describes a renderer for well-formed XML/XHTML and some HTML5 using CSS 2.1 and later, producing PDF or images. It also cautions that modern HTML5 should be specially crafted for its engine. Compare the engines against your template and deployment requirements:
| Decision axis | iText pdfHTML | OpenHTMLToPDF |
|---|---|---|
| Input model | Accepts an HTML String directly, with optional ConverterProperties. |
Pure-Java renderer centered on well-formed XML/XHTML and a reasonable subset of HTML5. |
| CSS/HTML coverage | Documented feature matrix; browser-only modules such as scripts, animations, transitions, and custom properties can be unsupported or partial. | CSS 2.1 and later within its supported subset; modern HTML5 may need special authoring. |
| Resource resolution | Set a base URI for relative stylesheets, images, and fonts. | Validate the equivalent resource-resolution configuration for the version you deploy. |
| Output engine | iText Core and pdfHTML. | PDFBox-based output engine. |
| Accessibility and PDF/A | Evaluate the capabilities and configuration required by your conformance target. | Evaluate the capabilities and configuration required by your conformance target. |
| License | AGPL for non-commercial use; commercial deployments require a commercial license. | Review the project’s license and your obligations for the chosen release. |
Choose based on the features your template actually uses, the PDF/A or accessibility requirements you must meet, dependency footprint, and licensing—not on how closely a browser preview resembles the source.
Troubleshoot missing styles and broken PDFs
The PDF has no styling
Cause: the CSS was never inserted into the HTML, the <style> tag was placed outside <head>, or the generated string is malformed. Fix: log the final HTML string, confirm the CSS appears between <style> and </style>, and validate the markup before conversion.
Recommended Free Tools
Rank #4
- 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
Images, fonts, or linked files are missing
Cause: relative URLs have no usable origin. Fix: set ConverterProperties.setBaseUri to the containing directory, check the path spelling and process permissions, and test the resource from the same runtime environment as the converter.
A browser layout does not match the PDF
Cause: the template uses a CSS module or HTML behavior that pdfHTML supports only partially or not at all. Fix: consult the feature matrix, simplify the affected layout, and replace scripts, animations, transitions, custom properties, or unsupported modern layout rules with static, print-oriented markup.
Conversion fails while reading an asset
Cause: a referenced resource is unavailable, unreadable, or points to the wrong base directory. Fix: remove references one at a time to identify the failing asset, then correct the URI or package the asset with the application.
The application builds but cannot be released
Cause: dependency and license review was postponed. Fix: pin the approved html2pdf version, record transitive dependencies, and obtain the appropriate AGPL or commercial authorization before deployment.
Best Value
- 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.
Reliability and performance considerations
- Generate the final HTML once and write directly to the destination stream; this avoids an unnecessary temporary PDF buffer.
- Keep templates and their asset directory together so the configured base URI is deterministic across development, CI, and production.
- Include representative long tables, page breaks, fonts, and images in automated PDF checks. A successful method call alone does not prove visual correctness.
- Expect asset loading to affect conversion time when resources are outside the process. Prefer locally packaged resources when repeatability matters.
- Capture conversion exceptions with the document identifier and resolved asset paths, but avoid logging sensitive invoice or customer data.
Practical checklist
- Assemble valid HTML with a single
<style>block containing the CSS string. - Call
HtmlConverter.convertToPdf(html, outputStream)for a self-contained document. - For relative resources, create
ConverterPropertiesand set a base URI to the correct template directory. - Check the pdfHTML feature matrix for every nontrivial CSS rule.
- Test the generated PDF for fonts, images, page breaks, accessibility, and required PDF/A conformance.
- Complete dependency and licensing review before shipping.
Or skip the browser setup
If your real requirement is a clean screenshot or PDF of a web page rather than server-side Java HTML rendering, ScreenshotNeo provides a single-request API. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; those cleanup steps can be disabled individually. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and each response reports the result in X-Page-Verdict and X-Billed headers. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.
For a one-call capture, see the ScreenshotNeo API documentation:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
The free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 screenshots; every feature is available on every plan. Create a free ScreenshotNeo account to try it.
Frequently Asked Questions
How can I verify that a relative URL uses the intended base directory?
Print the base URI at startup and inspect the final HTML for each relative reference. Then run the converter in the same working directory and under the same operating-system account used in production; a path that exists only on a developer workstation is not a valid deployment test.
Should the CSS be kept in a separate template file?
It can be, provided your application reads the template and stylesheet and assembles one final HTML string before conversion. The converter needs the resulting HTML string; keeping source files separate is an application-organization choice.
What is the safest way to handle a browser-only CSS feature?
Do not assume that a browser preview proves support. Check the pdfHTML feature matrix for the exact property or selector, create a small fixture demonstrating the desired result, and replace the rule with a static print-oriented equivalent if support is partial or absent.
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.

