How to generate a PDF from HTML in Java and Spring Boot
Published 2 min read
In Java, turning HTML into a PDF often means adding a rendering library, its fonts and its dependencies to your build and keeping them in step with the runtime. With an API it is one HTTP request, and the JDK has had an HTTP client since version 11. This guide shows a small client and a Spring Boot controller that returns the file, with the rustedf.cloud API.
A client on the standard HttpClient
import com.fasterxml.jackson.databind.ObjectMapper;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.time.Duration;import java.util.Map;
public final class PdfClient { private static final URI RENDER = URI.create("https://api.rustedf.com/v1/render");
private final HttpClient http = HttpClient.newHttpClient(); private final ObjectMapper json = new ObjectMapper(); private final String key;
public PdfClient(String key) { this.key = key; }
public byte[] render(String templateId, Map<String, Object> data, String locale) throws IOException, InterruptedException { String body = json.writeValueAsString( Map.of("template_id", templateId, "locale", locale, "data", data));
HttpRequest request = HttpRequest.newBuilder(RENDER) .timeout(Duration.ofSeconds(40)) .header("Authorization", "Bearer " + key) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(body)) .build();
HttpResponse<byte[]> response = http.send(request, HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() != 200) { String message = json.readTree(response.body()).path("error").path("message") .asText("Render failed (" + response.statusCode() + ")"); throw new IllegalStateException(message); } return response.body(); }}A successful response is the PDF itself, so the bytes are the file. On a failure the body is JSON
with a stable code and a message, which the client reads to build its exception.
Set the timeout above the time limit of your plan, so your request does not give up before the service does. Keep the key out of the source, in an environment variable or a secret store.
A Spring Boot controller
import java.util.Map;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.http.HttpHeaders;import org.springframework.http.MediaType;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RestController;
@RestControllerclass InvoiceController { private final PdfClient pdf; private final String templateId;
InvoiceController(PdfClient pdf, @Value("${rustedf.invoice-template}") String templateId) { this.pdf = pdf; this.templateId = templateId; }
@GetMapping("/invoices/{number}/pdf") ResponseEntity<byte[]> invoice(@PathVariable String number) throws Exception { byte[] file = pdf.render(templateId, Map.of( "number", number, "customer", Map.of("name", "Ana Souza"), "total", "2040.50"), "en-US");
return ResponseEntity.ok() .contentType(MediaType.APPLICATION_PDF) .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"invoice-" + number + ".pdf\"") .body(file); }}
@org.springframework.context.annotation.Configurationclass PdfConfig { @Bean PdfClient pdfClient(@Value("${rustedf.key}") String key) { return new PdfClient(key); }}Put rustedf.key in application.properties as rustedf.key=${RUSTEDF_KEY}, so the value
comes from the environment.
To send HTML instead of a saved template id, use an html entry in place of template_id. Pass
anything a user typed through data, not inside the HTML string: values in data are escaped, and
the HTML itself is read as a template.
Retry when the service is busy
A 429 (rate limit) or a 503 (busy) carries a Retry-After header. A failed render costs no
credit, so retrying is safe: read response.headers().firstValue("Retry-After"), sleep for that many
seconds and send the request again, a limited number of times.
Errors worth handling
| Status | code |
What to do |
|---|---|---|
| 401 | unauthorized |
The key is missing, wrong or revoked. |
| 402 | insufficient_credits |
No credits left. Nothing was rendered. |
| 422 | invalid_template |
The template or its data failed. Read message. |
| 429 | rate_limited |
Wait for Retry-After and retry. |
| 503 | busy |
The service is busy. Wait for Retry-After and retry. |
| 504 | render_timeout |
The document took longer than your plan allows. |
Run POST /v1/validate with the same body while you build the template: it lists anything the
service did not fully support, without returning the PDF or using a credit.
Read Rendering a PDF, Authentication and Errors and limits.
Keep reading
Code and integrations
Generate a PDF in ASP.NET Core: MVC, Razor Pages and minimal APIs
Turn a Razor view into a PDF in ASP.NET Core with one API call: a view renderer, a print-ready view, an MVC action, a Razor Pages handler and the traps to avoid.
3 min read
Code and integrations
Convert a web page to PDF in C# without a headless browser
Fetch a page with HttpClient and turn its HTML into a PDF with one API call in C#. Which pages this suits, which it does not, and how to check before you rely on it.
3 min read
Code and integrations
C# PDF report generator: a paged table with totals and page numbers
Build a PDF report in C# from a list of objects: a table whose header repeats on every page, a total, page numbers and the page count, with one HTTP call.
3 min read
Code and integrations
Save a PDF in C#: to disk, as a download or in blob storage
Save the PDF returned by a render call in C#: write it to disk, send it as a download from ASP.NET Core, keep a signed link or upload it, and avoid saving an error.
2 min read