In this guide you will learn how to convert HTML to PDF in Java using the HTML2PDF REST API. We will cover:
- Converting a URL to PDF with Java
- Converting raw HTML to PDF
- Setting page size, orientation and layout options
- Handling errors and status codes
The HTML2PDF API accepts both URLs and HTML and returns the generated PDF in the HTTP response.
You call https://api.html2pdf.co.uk/ with your license key and parameters.
Prerequisites
- Java 11 or later (for the built-in
java.net.http.HttpClient) - Basic knowledge of Maven or Gradle (optional but convenient)
- An HTML2PDF license key
1. Convert a URL to PDF in Java
The simplest way to use the API is to convert an existing URL. We send a GET request
to the endpoint with the license and url parameters and
save the PDF bytes to a file.
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Html2PdfJavaUrlExample {
private static final String ENDPOINT = "https://api.html2pdf.co.uk/";
private static final String LICENSE_KEY = "yourlicensekey";
public static void main(String[] args) throws Exception {
String sourceUrl = "https://example.com";
Path output = Path.of("example-java.pdf");
convertUrlToPdf(sourceUrl, output);
System.out.println("PDF created at " + output.toAbsolutePath());
}
private static void convertUrlToPdf(String sourceUrl, Path outputPath) throws IOException, InterruptedException {
HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.build();
String query = "license=" + urlEncode(LICENSE_KEY) +
"&url=" + urlEncode(sourceUrl);
URI uri = URI.create(ENDPOINT + "?" + query);
HttpRequest request = HttpRequest.newBuilder()
.uri(uri)
.GET()
.build();
HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
int statusCode = response.statusCode();
if (statusCode != 200) {
throw new RuntimeException("HTML2PDF API error: HTTP " + statusCode);
}
try (InputStream in = response.body();
OutputStream out = Files.newOutputStream(outputPath)) {
in.transferTo(out);
}
}
private static String urlEncode(String value) {
return URLEncoder.encode(value, StandardCharsets.UTF_8);
}
}
This will download the generated PDF and save it as example-java.pdf in your
working directory.
2. Convert raw HTML to PDF in Java
If your HTML is generated inside your application or not publicly accessible, you can send
the HTML directly to the API with a POST request using the html parameter.
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Html2PdfJavaHtmlExample {
private static final String ENDPOINT = "https://api.html2pdf.co.uk/";
private static final String LICENSE_KEY = "yourlicensekey";
public static void main(String[] args) throws Exception {
String html = "<html><body><h1>Hello from Java</h1><p>Converted with HTML2PDF.</p></body></html>";
Path output = Path.of("java-html.pdf");
convertHtmlToPdf(html, output);
System.out.println("PDF created from HTML at " + output.toAbsolutePath());
}
private static void convertHtmlToPdf(String html, Path outputPath) throws IOException, InterruptedException {
HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.build();
String form = "license=" + urlEncode(LICENSE_KEY) +
"&html=" + urlEncode(html);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(ENDPOINT))
.header("Content-Type", "application/x-www-form-urlencoded")
.POST(HttpRequest.BodyPublishers.ofString(form))
.build();
HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
int statusCode = response.statusCode();
if (statusCode != 200) {
throw new RuntimeException("HTML2PDF API error: HTTP " + statusCode);
}
try (InputStream in = response.body();
OutputStream out = Files.newOutputStream(outputPath)) {
in.transferTo(out);
}
}
private static String urlEncode(String value) {
return URLEncoder.encode(value, StandardCharsets.UTF_8);
}
}
Using this approach you do not need to expose internal pages as public URLs.
3. Setting conversion options
You can pass additional parameters to control the PDF output. Common options include:
page_size(for exampleA4orLetter)orientation(portraitorlandscape)css_media_type(screenorprint)lazy_loadandwait_timefor JavaScript-heavy pages
private static void convertUrlToPdfWithOptions(String sourceUrl, Path outputPath) throws IOException, InterruptedException {
HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.build();
String query = "license=" + urlEncode(LICENSE_KEY) +
"&url=" + urlEncode(sourceUrl) +
"&page_size=A4" +
"&orientation=landscape" +
"&css_media_type=print" +
"&lazy_load=true" +
"&wait_time=3000";
URI uri = URI.create(ENDPOINT + "?" + query);
HttpRequest request = HttpRequest.newBuilder()
.uri(uri)
.GET()
.build();
HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
if (response.statusCode() != 200) {
throw new RuntimeException("HTML2PDF API error: HTTP " + response.statusCode());
}
try (InputStream in = response.body();
OutputStream out = Files.newOutputStream(outputPath)) {
in.transferTo(out);
}
}
For a full list of options, including headers, footers and watermarks, see the HTML2PDF API documentation.
4. Handling Errors
When the API cannot generate a PDF it returns an HTTP status code instead. The most important codes are:
| Code | Description |
|---|---|
| 200 OK | Conversion succeeded and the response body contains the PDF |
| 400 Bad Request | No URL or HTML was provided |
| 401 Authorization required | Missing or invalid license key |
| 429 Too Many Requests | You exceeded the limits of your plan |
| 504 / 599 | Timeout or connectivity problems when fetching the URL |
In Java you can branch on response.statusCode() and either
log the issue, show a friendly error message or retry if it was a temporary timeout.
5. Next Steps
You now have the basics for converting HTML to PDF in Java using the HTML2PDF API. Next you can:
- Explore all parameters in the full API documentation
- Add a Click to PDF link on your site for one-click downloads
- Compare plans on the pricing page