Generate PDFs in Spring Boot with Api2Pdf: Thymeleaf Templates, RestClient and @Async Email
Summary. Java teams usually reach for one of three PDF stacks: iText (powerful, but AGPL or a commercial license), Flying Saucer and OpenHTMLtoPDF (HTML in, but CSS 2.1-era layout with no flexbox or grid), or Playwright for Java, which means a full Chromium in every container and a memory profile you now have to babysit. This guide keeps the part Spring developers already like, Thymeleaf templates, and hands the rendering to the Api2Pdf Headless Chrome endpoint. You will try the official Java client in five lines, then build a production client on Spring's RestClient with timeouts, retries and a typed exception, stream invoices from a controller as ResponseEntity<byte[]>, email them from an @Async method on virtual threads, assemble a merged, password-protected statement packet, and test the client with MockRestServiceServer.
Using another stack? There are companion posts for Ruby on Rails, Laravel, FastAPI and Next.js App Router.
The architecture in one paragraph
The API key lives in configuration (an environment variable or your secrets manager), never in the browser. A service renders a Thymeleaf template to an HTML string and calls POST https://v2.api2pdf.com/chrome/pdf/html with the raw API key in the Authorization header (no Bearer prefix). With ?outputBinary=true the response body is the PDF itself, which a controller returns as application/pdf or a mailer attaches to an email. Without it you get JSON with a FileUrl that Api2Pdf hosts for 24 hours, plus a ResponseId; that form is what you chain into other endpoints such as merge and password protection. Chrome never runs inside your JVM or your container, so your images stay small and your heap graphs stay flat.
Step 1: dependencies and the API key
Create an account and API key at portal.api2pdf.com. The code in this post targets Spring Boot 4.1 on Java 21 and was compiled and tested against it. It also runs unchanged on Spring Boot 3.5 if you swap spring-boot-starter-webmvc for spring-boot-starter-web. Add the web, Thymeleaf and mail starters:
<!-- pom.xml -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Bind the settings to a record with @ConfigurationProperties. The key comes from the API2PDF_API_KEY environment variable, and the application refuses to start without it, which is much better than discovering a missing key on the first invoice of the month:
api2pdf:
api-key: ${API2PDF_API_KEY}
base-url: ${API2PDF_BASE_URL:https://v2.api2pdf.com}
read-timeout: 100s
spring:
threads:
virtual:
enabled: true
// src/main/java/com/example/billing/api2pdf/Api2PdfProperties.java
package com.example.billing.api2pdf;
import java.time.Duration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.bind.DefaultValue;
@ConfigurationProperties("api2pdf")
public record Api2PdfProperties(
String apiKey,
@DefaultValue("https://v2.api2pdf.com") String baseUrl,
@DefaultValue("10s") Duration connectTimeout,
@DefaultValue("100s") Duration readTimeout,
@DefaultValue("2") int retries,
@DefaultValue("500ms") Duration retryDelay) {
public Api2PdfProperties {
if (apiKey == null || apiKey.isBlank()) {
throw new IllegalStateException("api2pdf.api-key is not set (API2PDF_API_KEY)");
}
}
}
Turn on configuration property scanning and async support on your application class:
// src/main/java/com/example/billing/BillingApplication.java
package com.example.billing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@ConfigurationPropertiesScan
@EnableAsync
public class BillingApplication {
public static void main(String[] args) {
SpringApplication.run(BillingApplication.class, args);
}
}
Step 2: a five-line smoke test with the official Java client
Api2Pdf publishes an official Java client on Maven Central (source on GitHub). It is the quickest way to confirm your key works:
<dependency>
<groupId>com.api2pdf.client</groupId>
<artifactId>api2pdf</artifactId>
<version>2.0.0</version>
</dependency>
package demo;
import com.api2pdf.client.Api2PdfClient;
import com.api2pdf.models.Api2PdfResponse;
import java.util.HashMap;
import java.util.Map;
public class QuickStart {
public static void main(String[] args) throws Exception {
Api2PdfClient a2p = new Api2PdfClient(System.getenv("API2PDF_API_KEY"));
Map<String, String> options = new HashMap<>();
options.put("landscape", "true");
Api2PdfResponse response = a2p.chromeHtmlToPdf("<h1>Hello from Java</h1>", false, "hello.pdf", options);
if (Boolean.TRUE.equals(response.getSuccess())) {
System.out.println(response.getFile()); // FileUrl, hosted for 24 hours
} else {
System.err.println(response.getError());
}
}
}
For a production Spring service, know what the client does and does not do before you wire it in:
- It returns hosted files only. Every method returns an
Api2PdfResponsewhosegetFile()is the 24 hourFileUrl; there is nooutputBinarymode, so a download endpoint has to fetch the file a second time. - It prints to standard output. Version 2.0.0 writes each request payload and response body with
System.out.println. In a container that sends stdout to your log pipeline, that means your rendered invoice HTML, with customer names and amounts, ends up in the logs. - No timeouts or retries. It is built on
HttpURLConnectionwith the JDK defaults, and a 4xx or 5xx surfaces as anIOExceptionrather than a parsed error message. - It covers the 2021 endpoint set. Chrome, wkhtmltopdf, LibreOffice, merge, bookmarks and password are there; newer endpoints such as Markdown to PDF, watermarks, extract pages and zip are not. Its options map is also
Map<String, String>, so every value is sent as a string.
None of that matters for a script or a one-off job. For an application that serves PDFs to users, the API is small enough that a purpose-built client on Spring's own HTTP stack is the better fit, and it is about 150 lines.
Step 3: a production client on RestClient
The request body for /chrome/pdf/html takes html plus the optional fileName, inline and options (the Headless Chrome options: margins, paper size, header and footer templates, delay and so on). outputBinary is a query string parameter. The JSON response carries Success, Error, FileUrl, MbOut, Seconds, Cost and ResponseId, which maps cleanly onto a record:
// src/main/java/com/example/billing/api2pdf/Api2PdfResult.java
package com.example.billing.api2pdf;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
/** The JSON response of every Api2Pdf endpoint (when outputBinary is not set). */
@JsonIgnoreProperties(ignoreUnknown = true)
public record Api2PdfResult(
@JsonProperty("Success") Boolean success,
@JsonProperty("Error") String error,
@JsonProperty("FileUrl") String fileUrl,
@JsonProperty("MbOut") Double mbOut,
@JsonProperty("Seconds") Double seconds,
@JsonProperty("Cost") Double cost,
@JsonProperty("ResponseId") String responseId) {
}
One unchecked exception type carries the HTTP status, the ResponseId for support, and whether the failure is transient (timeouts, connection resets, 429 and 5xx), which is worth retrying, or permanent, such as a bad API key or invalid input, which is not:
// src/main/java/com/example/billing/api2pdf/Api2PdfException.java
package com.example.billing.api2pdf;
/** A failed Api2Pdf call. {@link #isTransient()} is true for timeouts, 429 and 5xx. */
public class Api2PdfException extends RuntimeException {
private final int status;
private final String responseId;
private final boolean transientFailure;
public Api2PdfException(String message, int status, String responseId, boolean transientFailure, Throwable cause) {
super(message, cause);
this.status = status;
this.responseId = responseId;
this.transientFailure = transientFailure;
}
public int getStatus() { return status; }
public String getResponseId() { return responseId; }
public boolean isTransient() { return transientFailure; }
}
The client itself. It takes a RestClient.Builder rather than building its own HTTP stack, which is what makes it testable in Step 8:
// src/main/java/com/example/billing/api2pdf/Api2PdfClient.java
package com.example.billing.api2pdf;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Supplier;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClient;
public class Api2PdfClient {
private static final byte[] PDF_MAGIC = "%PDF".getBytes(StandardCharsets.US_ASCII);
private final RestClient http;
private final int retries;
private final Duration retryDelay;
public Api2PdfClient(RestClient.Builder builder, Api2PdfProperties props) {
this.http = builder
.baseUrl(props.baseUrl())
.defaultHeader("Authorization", props.apiKey()) // the raw key, no "Bearer"
.build();
this.retries = props.retries();
this.retryDelay = props.retryDelay();
}
// ---- request bodies (camelCase JSON, nulls omitted) ----
@JsonInclude(JsonInclude.Include.NON_NULL)
record HtmlRequest(String html, String fileName, boolean inline, Map<String, Object> options) {}
@JsonInclude(JsonInclude.Include.NON_NULL)
record MergeRequest(List<String> urls, String fileName, boolean inline) {}
@JsonInclude(JsonInclude.Include.NON_NULL)
record PasswordRequest(String url, String userpassword, String ownerpassword, String fileName, boolean inline) {}
/** HTML to PDF bytes, for downloads and attachments. */
public byte[] htmlToPdf(String html, String fileName, Map<String, Object> options) {
return postBinary("/chrome/pdf/html", new HtmlRequest(html, fileName, false, options));
}
/** HTML to a PDF hosted by Api2Pdf for 24 hours. Use the FileUrl to chain endpoints. */
public Api2PdfResult htmlToPdfUrl(String html, String fileName, Map<String, Object> options) {
return postJson("/chrome/pdf/html", new HtmlRequest(html, fileName, false, options));
}
/** Merge PDFs (public or pre-signed URLs) in the given order. */
public Api2PdfResult merge(List<String> urls, String fileName) {
return postJson("/pdfsharp/merge", new MergeRequest(urls, fileName, false));
}
/** Add an open (user) password and optionally an owner (permissions) password. */
public Api2PdfResult addPassword(String url, String userPassword, String ownerPassword, String fileName) {
return postJson("/pdfsharp/password", new PasswordRequest(url, userPassword, ownerPassword, fileName, false));
}
/** Delete a hosted file before its 24 hour expiry. */
public void deleteFile(String responseId) {
withRetries(() -> http.delete().uri("/file/{id}", responseId).exchange((req, res) -> {
if (!res.getStatusCode().is2xxSuccessful()) {
throw failure("Api2Pdf delete failed: HTTP " + res.getStatusCode().value(),
res.getStatusCode(), responseId);
}
return null;
}));
}
private byte[] postBinary(String path, Object body) {
return withRetries(() -> http.post()
.uri(uri -> uri.path(path).queryParam("outputBinary", "true").build())
.contentType(MediaType.APPLICATION_JSON)
.body(body)
.exchange((req, res) -> {
byte[] bytes = res.getBody().readAllBytes();
if (res.getStatusCode().is2xxSuccessful() && startsWithPdfMagic(bytes)) {
return bytes;
}
// Failures come back as JSON ({"Success":false,"Error":"..."}) even with outputBinary=true.
String text = new String(bytes, 0, Math.min(bytes.length, 500), StandardCharsets.UTF_8);
throw failure("Api2Pdf HTTP " + res.getStatusCode().value() + ": " + text,
res.getStatusCode(), null);
}));
}
private Api2PdfResult postJson(String path, Object body) {
return withRetries(() -> http.post()
.uri(path)
.contentType(MediaType.APPLICATION_JSON)
.body(body)
.exchange((req, res) -> {
Api2PdfResult result;
try {
result = res.bodyTo(Api2PdfResult.class);
} catch (Exception e) { // empty or non-JSON body, e.g. from a proxy
result = null;
}
if (res.getStatusCode().is2xxSuccessful() && result != null && Boolean.TRUE.equals(result.success())) {
return result;
}
String error = result != null && result.error() != null
? result.error() : "Api2Pdf HTTP " + res.getStatusCode().value();
throw failure(error, res.getStatusCode(), result != null ? result.responseId() : null);
}));
}
private <T> T withRetries(Supplier<T> call) {
for (int attempt = 0; ; attempt++) {
try {
return call.get();
} catch (Api2PdfException e) {
if (!e.isTransient() || attempt >= retries) throw e;
} catch (ResourceAccessException e) { // connect or read timeout, connection reset
if (attempt >= retries) {
throw new Api2PdfException("Api2Pdf request failed: " + e.getMessage(), 0, null, true, e);
}
}
sleep(attempt);
}
}
private void sleep(int attempt) {
long base = retryDelay.toMillis() << attempt; // 0.5 s, 1 s, 2 s ...
long jitter = ThreadLocalRandom.current().nextLong(retryDelay.toMillis() + 1);
try {
Thread.sleep(base + jitter);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new Api2PdfException("Interrupted while retrying", 0, null, false, e);
}
}
private static Api2PdfException failure(String message, HttpStatusCode status, String responseId) {
boolean transientFailure = status.value() == 429 || status.is5xxServerError();
return new Api2PdfException(message, status.value(), responseId, transientFailure, null);
}
private static boolean startsWithPdfMagic(byte[] bytes) {
return bytes.length >= 4 && Arrays.equals(bytes, 0, 4, PDF_MAGIC, 0, 4);
}
}
Finally, register it as a bean on the JDK's java.net.http.HttpClient with explicit connect and read timeouts:
// src/main/java/com/example/billing/api2pdf/Api2PdfConfig.java
package com.example.billing.api2pdf;
import java.net.http.HttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.JdkClientHttpRequestFactory;
import org.springframework.web.client.RestClient;
@Configuration(proxyBeanMethods = false)
public class Api2PdfConfig {
@Bean
Api2PdfClient api2PdfClient(Api2PdfProperties props) {
HttpClient jdk = HttpClient.newBuilder()
.connectTimeout(props.connectTimeout())
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
JdkClientHttpRequestFactory factory = new JdkClientHttpRequestFactory(jdk);
factory.setReadTimeout(props.readTimeout());
return new Api2PdfClient(RestClient.builder().requestFactory(factory), props);
}
}
A few details worth calling out:
- No
Bearerprefix. TheAuthorizationheader is the key itself. ABearerprefix is the most common cause of a 401. exchange()instead ofretrieve(). By defaultretrieve()throws Spring's genericHttpClientErrorExceptionon a 4xx before you can read Api2Pdf'sErrormessage.exchange()hands you the status and the body together, so every failure becomes anApi2PdfExceptionwith a useful message.- Binary responses are verified. Failures still come back as JSON even when you ask for
outputBinary=true, so the client checks for the%PDFsignature before treating the body as a document. - Retrying a POST is safe here. PDF generation has no side effects on your account beyond the usage of the attempt, so a retry after a timeout cannot create a duplicate invoice. The loop backs off exponentially with jitter and only retries transient failures.
- Timeouts. Standard requests are limited to 90 seconds of processing, so a 100 second read timeout leaves room for the network. On V2 XL (5 minute limit) raise it to around 310 seconds.
- camelCase on the wire. The request records serialize as
html,fileName,inlineandoptions;@JsonInclude(NON_NULL)drops absent fields such as an empty owner password. The records only use Jackson annotations, so the client works with both Jackson 3 (Spring Boot 4) and Jackson 2 (Spring Boot 3).
Step 4: a Thymeleaf invoice template
Keep PDF templates in their own folder, separate from your page layouts, so they do not inherit navigation, scripts and analytics. Two rules make the output match your browser: inline the CSS, and make every asset reachable from the internet. Api2Pdf renders your HTML on its own servers, so a stylesheet or logo served from localhost:8080 or a private network simply never loads.
<!-- src/main/resources/templates/pdf/invoice.html -->
<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title th:text="'Invoice ' + ${invoice.number}">Invoice</title>
<style>
@page { size: Letter; margin: 18mm 16mm 20mm; }
* { box-sizing: border-box; }
body { font: 12px/1.5 -apple-system, "Segoe UI", Helvetica, Arial, sans-serif; color: #111827; margin: 0; }
h1 { font-size: 26px; margin: 0 0 4px; }
.muted { color: #6b7280; }
.head { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 32px; }
table { width: 100%; border-collapse: collapse; }
thead { display: table-header-group; } /* repeat the header row on every page */
th { text-align: left; font-size: 11px; text-transform: uppercase; color: #6b7280;
border-bottom: 2px solid #111827; padding: 8px 6px; }
td { padding: 8px 6px; border-bottom: 1px solid #e5e7eb; }
tr { break-inside: avoid; }
.num { text-align: right; font-variant-numeric: tabular-nums; }
.total td { font-weight: 700; font-size: 14px; border-bottom: 0; }
</style>
</head>
<body>
<div class="head">
<div>
<img src="https://www.example.com/logo.png" alt="Example Inc." height="36">
<p class="muted">Example Inc.<br>100 Main Street<br>Chicago, IL 60601</p>
</div>
<div style="text-align:right">
<h1>Invoice</h1>
<div th:text="${invoice.number}">INV-1001</div>
<div class="muted">Issued <span th:text="${#temporals.format(invoice.issuedOn, 'MMM d, yyyy')}">Nov 17, 2026</span></div>
<div class="muted">Due <span th:text="${#temporals.format(invoice.dueOn, 'MMM d, yyyy')}">Dec 17, 2026</span></div>
</div>
</div>
<p><strong>Bill to</strong><br><span th:text="${invoice.customerName}">Acme Corp</span></p>
<table>
<thead>
<tr><th>Description</th><th class="num">Qty</th><th class="num">Unit price</th><th class="num">Amount</th></tr>
</thead>
<tbody>
<tr th:each="line : ${invoice.lines}">
<td th:text="${line.description}">Widget</td>
<td class="num" th:text="${line.quantity}">1</td>
<td class="num" th:text="${'$' + #numbers.formatDecimal(line.unitPrice, 1, 'COMMA', 2, 'POINT')}">$10.00</td>
<td class="num" th:text="${'$' + #numbers.formatDecimal(line.amount(), 1, 'COMMA', 2, 'POINT')}">$10.00</td>
</tr>
<tr class="total">
<td colspan="3" class="num">Total due</td>
<td class="num" th:text="${'$' + #numbers.formatDecimal(invoice.total(), 1, 'COMMA', 2, 'POINT')}">$10.00</td>
</tr>
</tbody>
</table>
</body>
</html>
The domain is plain records. InvoiceRepository stands in for your Spring Data repository:
// src/main/java/com/example/billing/invoice/Invoice.java
package com.example.billing.invoice;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
public record Invoice(long id, String number, LocalDate issuedOn, LocalDate dueOn,
String customerName, String customerEmail, List<LineItem> lines) {
public record LineItem(String description, int quantity, BigDecimal unitPrice) {
public BigDecimal amount() {
return unitPrice.multiply(BigDecimal.valueOf(quantity));
}
}
public BigDecimal total() {
return lines.stream().map(LineItem::amount).reduce(BigDecimal.ZERO, BigDecimal::add);
}
}
// src/main/java/com/example/billing/invoice/InvoiceRepository.java
package com.example.billing.invoice;
import java.util.Optional;
/** Your Spring Data repository in a real app. */
public interface InvoiceRepository {
Optional<Invoice> findById(long id);
}
A small service renders the template with Thymeleaf's ITemplateEngine (auto-configured by the starter) and sends the HTML to Api2Pdf. preferCSSPageSize lets the @page rule in the template control paper size and margins, and the footer template uses Chrome's pageNumber and totalPages classes:
// src/main/java/com/example/billing/invoice/InvoicePdfService.java
package com.example.billing.invoice;
import com.example.billing.api2pdf.Api2PdfClient;
import java.util.Map;
import org.springframework.stereotype.Service;
import org.thymeleaf.ITemplateEngine;
import org.thymeleaf.context.Context;
@Service
public class InvoicePdfService {
private static final Map<String, Object> PDF_OPTIONS = Map.of(
"preferCSSPageSize", true, // honour @page { size: Letter; margin: ... }
"printBackground", true,
"displayHeaderFooter", true,
"headerTemplate", "<span></span>",
"footerTemplate", """
<div style="font-size:9px;width:100%;text-align:center;color:#6b7280">
Page <span class="pageNumber"></span> of <span class="totalPages"></span>
</div>""");
private final ITemplateEngine templates;
private final Api2PdfClient api2pdf;
public InvoicePdfService(ITemplateEngine templates, Api2PdfClient api2pdf) {
this.templates = templates;
this.api2pdf = api2pdf;
}
public String renderHtml(Invoice invoice) {
Context ctx = new Context();
ctx.setVariable("invoice", invoice);
return templates.process("pdf/invoice", ctx); // src/main/resources/templates/pdf/invoice.html
}
public byte[] renderPdf(Invoice invoice) {
return api2pdf.htmlToPdf(renderHtml(invoice), fileName(invoice), PDF_OPTIONS);
}
public String fileName(Invoice invoice) {
return "invoice-" + invoice.number() + ".pdf";
}
}
Step 5: a controller that returns the PDF
For documents of a few pages, generating on request is simplest: the user clicks Download and gets the file a second or two later. Return the bytes as a ResponseEntity<byte[]> and let ContentDisposition build a correctly quoted header:
// src/main/java/com/example/billing/invoice/InvoiceController.java
package com.example.billing.invoice;
import org.springframework.http.ContentDisposition;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import static org.springframework.http.HttpStatus.NOT_FOUND;
@RestController
public class InvoiceController {
private final InvoiceRepository invoices;
private final InvoicePdfService pdfs;
public InvoiceController(InvoiceRepository invoices, InvoicePdfService pdfs) {
this.invoices = invoices;
this.pdfs = pdfs;
}
@GetMapping("/invoices/{id}/pdf")
public ResponseEntity<byte[]> pdf(@PathVariable long id,
@RequestParam(defaultValue = "false") boolean inline) {
Invoice invoice = invoices.findById(id)
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND));
// Authorize the current user for this invoice here (Spring Security, @PreAuthorize, ...).
byte[] pdf = pdfs.renderPdf(invoice);
ContentDisposition disposition = (inline ? ContentDisposition.inline() : ContentDisposition.attachment())
.filename(pdfs.fileName(invoice))
.build();
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_PDF)
.header(HttpHeaders.CONTENT_DISPOSITION, disposition.toString())
.header(HttpHeaders.CACHE_CONTROL, "private, no-store")
.body(pdf);
}
/** Preview the exact HTML that is sent to Api2Pdf. Keep this out of production. */
@GetMapping(value = "/invoices/{id}/pdf-preview", produces = MediaType.TEXT_HTML_VALUE)
public String preview(@PathVariable long id) {
return pdfs.renderHtml(invoices.findById(id).orElseThrow(() -> new ResponseStatusException(NOT_FOUND)));
}
}
Add ?inline=true to open the PDF in the browser's viewer instead of downloading it. The preview endpoint returns the exact HTML Api2Pdf receives, which is the fastest way to debug layout: open it in Chrome and use print preview (see test your HTML locally first).
Step 6: generate and email from an @Async method
Anything a user should not wait for, such as month-end invoice runs, statements and reports, belongs off the request thread. With @EnableAsync on the application and spring.threads.virtual.enabled=true in application.yml, Spring Boot runs @Async methods on virtual threads, so a thousand invoices waiting on the network do not tie up a thousand platform threads:
// src/main/java/com/example/billing/invoice/InvoiceMailer.java
package com.example.billing.invoice;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class InvoiceMailer {
private static final Logger log = LoggerFactory.getLogger(InvoiceMailer.class);
private final InvoiceRepository invoices;
private final InvoicePdfService pdfs;
private final JavaMailSender mail;
public InvoiceMailer(InvoiceRepository invoices, InvoicePdfService pdfs, JavaMailSender mail) {
this.invoices = invoices;
this.pdfs = pdfs;
this.mail = mail;
}
/** Runs on the async executor (a virtual thread with spring.threads.virtual.enabled=true). */
@Async
public void sendInvoice(long invoiceId) {
Invoice invoice = invoices.findById(invoiceId).orElseThrow();
byte[] pdf = pdfs.renderPdf(invoice); // Api2Pdf errors are logged by the async exception handler
try {
MimeMessage message = mail.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
helper.setTo(invoice.customerEmail());
helper.setSubject("Invoice " + invoice.number());
helper.setText("Hi " + invoice.customerName() + ",\n\nYour invoice is attached.\n");
helper.addAttachment(pdfs.fileName(invoice), new ByteArrayResource(pdf), "application/pdf");
mail.send(message);
log.info("Sent invoice {} ({} bytes)", invoice.number(), pdf.length);
} catch (MessagingException e) {
throw new IllegalStateException("Could not build invoice email", e);
}
}
}
Call invoiceMailer.sendInvoice(invoice.id()) from a controller, a @Scheduled job or an event listener. Exceptions thrown by a void @Async method go to the AsyncUncaughtExceptionHandler, which logs them by default; if you need durable retries across restarts (for example, Api2Pdf succeeded but the SMTP server was down), put the invoice id on a queue such as SQS, RabbitMQ or a database outbox and process it from a listener instead.
Step 7: a merged, password-protected statement packet
Some documents are assembled from parts: a cover letter, a statement, terms and conditions. Render each part with the JSON form so you get a hosted FileUrl, merge them in order with POST /pdfsharp/merge, then protect the result with POST /pdfsharp/password, which takes the url of the PDF, a userpassword required to open it and an optional ownerpassword that controls permissions. Intermediate files are deleted with DELETE /file/{responseId} as soon as the packet exists:
// src/main/java/com/example/billing/invoice/StatementPacketService.java
package com.example.billing.invoice;
import com.example.billing.api2pdf.Api2PdfClient;
import com.example.billing.api2pdf.Api2PdfException;
import com.example.billing.api2pdf.Api2PdfResult;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
@Service
public class StatementPacketService {
private final Api2PdfClient api2pdf;
public StatementPacketService(Api2PdfClient api2pdf) {
this.api2pdf = api2pdf;
}
/**
* Render each HTML section, merge them in order, protect the result with a password.
* Returns the final hosted PDF (valid for 24 hours); intermediate files are deleted.
*/
public Api2PdfResult build(List<String> htmlSections, String password, String fileName) {
List<String> scratch = new ArrayList<>();
try {
List<String> urls = new ArrayList<>();
for (int i = 0; i < htmlSections.size(); i++) {
Api2PdfResult part = api2pdf.htmlToPdfUrl(htmlSections.get(i), "part-" + i + ".pdf",
Map.of("preferCSSPageSize", true, "printBackground", true));
scratch.add(part.responseId());
urls.add(part.fileUrl());
}
Api2PdfResult merged = api2pdf.merge(urls, "merged.pdf");
scratch.add(merged.responseId());
return api2pdf.addPassword(merged.fileUrl(), password, null, fileName);
} finally {
for (String responseId : scratch) {
try {
api2pdf.deleteFile(responseId);
} catch (Api2PdfException ignored) {
// the file expires after 24 hours anyway
}
}
}
}
}
The final fileUrl() is valid for 24 hours. Email the link, redirect the user to it, or download it into your own storage. If the packet should go straight into your bucket, Api2Pdf can write it there for you with useCustomStorage (see batch PDF generation: zip PDFs and upload to S3). For DRAFT or CONFIDENTIAL stamps on the same pipeline, add one call to POST /pdfsharp/watermark as shown in the Laravel guide.
Step 8: test the client with MockRestServiceServer
Because the client takes a RestClient.Builder, MockRestServiceServer.bindTo(builder) can intercept every request without a Spring context or a network. These tests check the raw Authorization header, the JSON body, retries on a 503, and that a 400 is not retried:
// src/test/java/com/example/billing/api2pdf/Api2PdfClientTest.java
package com.example.billing.api2pdf;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.springframework.test.web.client.ExpectedCount.once;
import static org.springframework.test.web.client.ExpectedCount.times;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.*;
import static org.springframework.test.web.client.response.MockRestResponseCreators.*;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestClient;
class Api2PdfClientTest {
private static final String BASE = "https://v2.api2pdf.com";
private MockRestServiceServer server;
private Api2PdfClient client;
@BeforeEach
void setUp() {
RestClient.Builder builder = RestClient.builder();
server = MockRestServiceServer.bindTo(builder).build();
var props = new Api2PdfProperties("test-key", BASE, Duration.ofSeconds(1),
Duration.ofSeconds(5), 2, Duration.ofMillis(1));
client = new Api2PdfClient(builder, props);
}
@Test
void returnsPdfBytesAndSendsTheRawKey() {
server.expect(once(), requestTo(BASE + "/chrome/pdf/html?outputBinary=true"))
.andExpect(method(HttpMethod.POST))
.andExpect(header("Authorization", "test-key"))
.andExpect(jsonPath("$.html").value("<h1>Hi</h1>"))
.andExpect(jsonPath("$.fileName").value("hi.pdf"))
.andExpect(jsonPath("$.options.landscape").value(true))
.andRespond(withSuccess("%PDF-1.7 fake".getBytes(StandardCharsets.US_ASCII), MediaType.APPLICATION_PDF));
byte[] pdf = client.htmlToPdf("<h1>Hi</h1>", "hi.pdf", Map.of("landscape", true));
assertThat(new String(pdf, 0, 4, StandardCharsets.US_ASCII)).isEqualTo("%PDF");
server.verify();
}
@Test
void retriesServerErrorsThenSucceeds() {
server.expect(once(), requestTo(BASE + "/pdfsharp/merge")).andRespond(withStatus(HttpStatus.SERVICE_UNAVAILABLE));
server.expect(once(), requestTo(BASE + "/pdfsharp/merge"))
.andExpect(jsonPath("$.urls[1]").value("https://files.example.com/b.pdf"))
.andRespond(withSuccess("""
{"Success":true,"FileUrl":"https://storage.api2pdf.com/merged.pdf",
"MbOut":0.1,"Seconds":0.4,"Cost":0.0001,"ResponseId":"r-1"}""",
MediaType.APPLICATION_JSON));
Api2PdfResult result = client.merge(
List.of("https://files.example.com/a.pdf", "https://files.example.com/b.pdf"), "merged.pdf");
assertThat(result.fileUrl()).isEqualTo("https://storage.api2pdf.com/merged.pdf");
assertThat(result.responseId()).isEqualTo("r-1");
server.verify();
}
@Test
void doesNotRetryBadRequests() {
server.expect(times(1), requestTo(BASE + "/pdfsharp/password"))
.andRespond(withStatus(HttpStatus.BAD_REQUEST).contentType(MediaType.APPLICATION_JSON)
.body("{\"Success\":false,\"Error\":\"Url is required\",\"ResponseId\":\"r-2\"}"));
assertThatThrownBy(() -> client.addPassword("", "secret", null, "x.pdf"))
.isInstanceOf(Api2PdfException.class)
.hasMessage("Url is required")
.satisfies(e -> assertThat(((Api2PdfException) e).isTransient()).isFalse());
server.verify();
}
}
Run them with ./mvnw test. For controller and mailer tests, replace the client with @MockitoBean Api2PdfClient api2pdf and stub htmlToPdf to return a few bytes starting with %PDF.
Production notes
- Keep the key server-side. Never call Api2Pdf from browser JavaScript; the key in the
Authorizationheader would be visible to every visitor. Always go through a controller that authorizes the user first. - Pick the right path for each document. Stream small documents straight from the controller; move anything big, bulk or chained to
@Asyncor a queue so request threads are free for page views. - Use V2 XL for large documents. Standard requests get 2 GB of memory and 90 seconds. Long reports with hundreds of pages or heavy charts can point a second
Api2PdfClientbean athttps://v2-xl.api2pdf.com(4 CPU, 8 GB, 5 minute limit, priced at 10x the standard rate) with a longer read timeout. Use it only for those jobs rather than sending everything there. - Mind the 24 hour
FileUrl. Hosted files are deleted after 24 hours. Copy anything you need to keep into your own storage, delete sensitive files early withDELETE /file/{responseId}, or have Api2Pdf write straight into your bucket withuseCustomStorage. - Log the
ResponseId, not the HTML. The id appears in the request logs in the portal, and support can trace a specific request with it. Rendered documents usually contain personal data, so keep them out of application logs. - Cost is per use. Billing is based on compute seconds and bandwidth (each JSON response reports
Seconds,MbOutandCost), so a one-page invoice usually costs a fraction of a cent. RecordCostwith Micrometer if you want per-feature cost dashboards.
Troubleshooting
- 401 Unauthorized. The header must be the key on its own. Remove any
Bearerprefix, check for trailing whitespace or newlines in the environment variable, and make sure the deployed environment actually setsAPI2PDF_API_KEY. - Styles or images missing in the PDF. The CSS or image was linked from a host Api2Pdf cannot reach. Inline the CSS in the template and use absolute public URLs (or
data:URIs) for images. - Charts or JavaScript-rendered content is blank. The PDF was printed before the scripts finished. Add
delay(milliseconds) to the options, or wait for a specific condition withpuppeteerWaitForMethodandpuppeteerWaitForValue, as described in the Headless Chrome options. Better still, render charts as SVG on the server. Api2PdfException: Api2Pdf request failedafter a long wait. The read timeout fired. Check for slow external images or fonts first, then raiseapi2pdf.read-timeoutor send the job to V2 XL.- Tiny header or footer text, or none at all. Set
displayHeaderFootertotrue, give the template an explicitfont-size, and leave enough bottom margin in@pagefor it to fit. - Page breaks in the wrong place. Use
break-inside: avoidon rows and cards,break-before: pagefor new sections, anddisplay: table-header-groupto repeat table headers. - Thymeleaf errors at render time. Templates are parsed as HTML5; an unclosed tag shows up as a
TemplateInputExceptionwith the line number. Call the preview endpoint to see the exact output.
Wrap-up
You now have a Spring Boot PDF pipeline with no native dependencies: Thymeleaf templates you already know how to write, a RestClient-based client with timeouts, retries and a typed exception, a controller for instant downloads, an @Async mailer on virtual threads, a merged and password-protected statement packet, and tests that never touch the network. The same client covers the rest of the API: Markdown to PDF, screenshots, Office conversion through LibreOffice and file to Markdown extraction are all one more method each. Create a free account to get an API key, or browse the full request reference in the interactive API docs.



