Until now InvoiceLab has been a library: main programs that generate files in output/. But at Nebula Distribution invoices are requested by other applications: the ERP when an order is closed, the customer website when someone clicks "Download invoice", the accounts team who want to merge several PDFs into a single mailing. The natural thing is to offer generation as an HTTP service. In this lesson we'll use Spring Boot 3 to build a REST service that receives an invoice as JSON and returns the PDF, serves already issued invoices with caching headers, signs on request and merges PDFs uploaded by the user. Along the way we'll apply everything we learnt in the previous lesson about memory and concurrency, handle files that come from outside with care, measure the service and get it ready to run in a container.
Contents
- Service architecture
- Dependencies and project structure
- The request: DTO and validation
- The service: concurrency, signing and metrics
POST /invoices/pdf: returning a PDFGET /invoices/{number}/pdfand caching headers- Errors with
ProblemDetail POST /pdf/merge: untrusted uploads andStreamingResponseBody- Limits and configuration
- Integration tests with MockMvc
- Deploying in a container
Service architecture
flowchart LR
C["HTTP client<br/>(ERP, website)"] -->|"JSON"| FC["InvoiceController"]
C -->|"multipart"| UC["MergeController"]
FC -->|"DTO → Invoice"| SP["PdfService<br/>semaphore + metrics"]
SP --> GF["InvoiceGenerator<br/>(module 3)"]
SP -.->|"?sign=true"| FP["PdfSigner<br/>(module 7)"]
UC --> PM["PDFMergerUtility<br/>disk cache"]
FC -. "exceptions" .-> ME["ErrorHandler<br/>ProblemDetail"]
UC -. "exceptions" .-> ME
The golden rule: the controllers know nothing about PDFBox. They translate HTTP into model objects and back; generation stays in InvoiceGenerator, exactly the same one used by the command-line program from 03-05. We planned for this in 03-04 when we made generate return a byte[]: "the destination is none of the generator's business".
Dependencies and project structure
We start from the same Maven project, now with the Spring Boot parent (verified with 3.5.4):
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.5.4</version>
<relativePath/>
</parent>
<dependencies>
<!-- PDFBox, xmpbox, preflight, Bouncy Castle, ZXing: as before, with ${pdfbox.version} -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <!-- Spring MVC + Tomcat + Jackson -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId> <!-- Bean Validation (Hibernate Validator) -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId> <!-- /actuator/health, /actuator/metrics -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId> <!-- JUnit 5, MockMvc, AssertJ -->
<scope>test</scope>
</dependency>
</dependencies>The parent manages the versions of Spring, Jackson, JUnit and friends, but not those of PDFBox: we keep our own ${pdfbox.version} property. The new code goes in the com.invoicelab.service package:
| Class | Responsibility |
|---|---|
InvoiceLabApplication |
Spring Boot start-up |
InvoiceRequest |
DTO for the incoming JSON, with its validation rules |
PdfService |
Generate (and sign) with a concurrency limit and metrics |
InvoiceRepository |
Already issued invoices (here, in memory) |
InvoiceController |
POST /invoices/pdf and GET /invoices/{number}/pdf |
MergeController |
POST /pdf/merge |
ErrorHandler |
Exceptions → application/problem+json |
The start-up class is the usual one, with one detail:
@SpringBootApplication
public class InvoiceLabApplication {
public static void main(String[] args) {
System.setProperty("java.awt.headless", "true"); // no display: essential in containers
SpringApplication.run(InvoiceLabApplication.class, args);
}
}PDFBox uses AWT classes (BufferedImage, Color, Graphics2D when rendering or when flattening the logo in 08-01). On a server without a graphical environment, AWT must run in headless mode. Spring Boot already turns it on by default, but setting it explicitly (or with -Djava.awt.headless=true) makes the intention clear and protects you if someone starts the application another way.
The request: DTO and validation
The JSON isn't converted directly into an Invoice. We use a DTO (Data Transfer Object), a record that describes exactly what we accept, with the Bean Validation rules as annotations:
/** Incoming JSON for POST /invoices/pdf. The issuer does NOT come in the request: the server sets it. */
public record InvoiceRequest(
@NotBlank @Pattern(regexp = "F-\\d{4}-\\d{4}") String number,
@NotNull LocalDate date,
@NotNull @Valid CustomerDto customer,
@NotEmpty @Size(max = 500) List<@Valid LineDto> lines,
@Size(max = 2000) String paymentTerms) {
public record CustomerDto(
@NotBlank @Size(max = 120) String companyName,
@NotBlank @Pattern(regexp = "[A-Z0-9]{9}") String taxId,
@NotBlank @Size(max = 200) String address,
@NotBlank @Pattern(regexp = "\\d{5}") String postalCode,
@NotBlank @Size(max = 80) String city,
@Email String email) {
}
public record LineDto(
@NotBlank @Size(max = 30) String reference,
@NotBlank @Size(max = 300) String description,
@NotNull @Positive BigDecimal quantity,
@NotNull @PositiveOrZero BigDecimal unitPrice,
@NotNull @DecimalMin("0") @DecimalMax("100") BigDecimal vatRate) {
}
/** DTO → model. The business rules of Invoice and InvoiceLine still apply here. */
public Invoice toInvoice(Customer issuer) {
Customer c = new Customer(customer.companyName(), customer.taxId(), customer.address(),
customer.postalCode(), customer.city(), customer.email());
List<InvoiceLine> model = lines.stream()
.map(l -> new InvoiceLine(l.reference(), l.description(), l.quantity(), l.unitPrice(),
l.vatRate()))
.toList();
return new Invoice(number, date, issuer, c, model, paymentTerms);
}
}Why a DTO instead of annotating Invoice directly?
- Security: the issuer isn't part of the request. If the API client could send the issuer, it could issue invoices on behalf of anyone. The server sets it (
PdfService.NEBULA). - Limits:
@Size(max = 500)on the lines and@Sizeon each text field cap the amount of work a single request can ask for. Without them, someone could request an invoice with a million lines. - Independence: the API format can evolve without touching the model, and vice versa.
@Validmakes validation cascade into nested objects and into each element of the list.
There are two levels of validation and it's worth telling them apart: Bean Validation checks the shape of the data (required fields, lengths, patterns) and responds with a 400; the model constructors and InvoiceGenerator.validate check the business rules (for example, a positive total) and throw IllegalArgumentException, which we'll turn into a 422.
The service: concurrency, signing and metrics
PdfService is the only class that touches the generator and the signer:
@Service
public class PdfService {
/** Fixed issuer: the API client can't invoice on behalf of anyone else. */
static final Customer NEBULA = new Customer("Nebula Distribution Ltd.", "B00000000",
"12 Fictional Street, Unit 3", "50001", "Zaragoza", "[email protected]");
private final DocumentGenerator<Invoice> generator = new InvoiceGenerator(Theme.nebula()); // stateless: shareable
private final Semaphore permits;
private final long waitMs;
private final PdfSigner signer; // null if no certificate is configured
private final Timer duration;
private final DistributionSummary size;
public PdfService(MeterRegistry metrics,
@Value("${invoicelab.pdf.concurrency:0}") int concurrency,
@Value("${invoicelab.pdf.wait-ms:2000}") long waitMs,
@Value("${invoicelab.signature.p12:}") String p12Path) throws Exception {
int n = concurrency > 0 ? concurrency : Runtime.getRuntime().availableProcessors();
this.permits = new Semaphore(n);
this.waitMs = waitMs;
this.signer = p12Path.isBlank() ? null : new PdfSigner(KeyVault.load(Path.of(p12Path),
Secrets.chars("INVOICELAB_P12_NEBULA"), "nebula"), PdfSigner.Profile.PADES_B, null);
this.duration = Timer.builder("invoicelab.pdf.generation").description("PDF generation time")
.publishPercentiles(0.5, 0.95).register(metrics);
this.size = DistributionSummary.builder("invoicelab.pdf.size").baseUnit("bytes")
.description("Size of the generated PDFs").register(metrics);
}- One generator for all requests.
InvoiceGeneratorkeeps no state between calls: eachgeneratecreates its ownPDDocument, its ownPdfContextand its own fonts. That's why it's safe to share it between threads, even thoughPDDocumentisn't (08-03). - A semaphore limits simultaneous PDFs. Tomcat can serve dozens of requests at once, but generating a PDF is CPU work: with more simultaneous generations than cores, all we get is more memory in use and worse times for everyone (we measured this in 08-03). By default, as many permits as cores.
- Signing is optional. If the
invoicelab.signature.p12property is empty, the service starts without a signer. The password is never in the configuration:Secrets.charsreads it from theINVOICELAB_P12_NEBULAenvironment variable (07-01), and the.p12is mounted into the container from a secrets manager. - Metrics with Micrometer, which Spring Boot Actuator includes: a
Timerfor the duration (with the 50th and 95th percentiles) and aDistributionSummaryfor the size.
The working method:
public byte[] invoice(Invoice invoice, boolean sign) throws IOException, InterruptedException {
if (sign && signer == null) {
throw new SigningUnavailableException();
}
if (!permits.tryAcquire(waitMs, TimeUnit.MILLISECONDS)) {
throw new ServiceBusyException(); // a quick 503 beats an endless queue
}
try {
Timer.Sample sample = Timer.start();
byte[] pdf = generator.generate(invoice);
if (sign) {
pdf = sign(pdf, invoice);
}
sample.stop(duration);
size.record(pdf.length);
return pdf;
} finally {
permits.release(); // always, even if generation fails
}
}
private byte[] sign(byte[] pdf, Invoice invoice) throws IOException {
Path source = Files.createTempFile("invoicelab-", ".pdf");
Path target = Files.createTempFile("invoicelab-signed-", ".pdf");
try {
Files.write(source, pdf);
signer.sign(source, target, PdfSigner.SignatureData.approval(NEBULA.companyName(), "Zaragoza",
"Issue of invoice " + invoice.number()));
return Files.readAllBytes(target);
} finally {
Files.deleteIfExists(source);
Files.deleteIfExists(target);
}
}tryAcquirewith a maximum wait: if no slot frees up within 2 seconds, we respond "service busy" (503) instead of letting requests pile up until memory runs out. The client can retry.PdfSigner.signworks with paths (it usesPdfEditorand its atomic save), so we go through temporary files, which we always delete in thefinally.SigningUnavailableExceptionandServiceBusyExceptionare two custom exceptions, nested classes extendingRuntimeException.
POST /invoices/pdf: returning a PDF
@RestController
public class InvoiceController {
private final PdfService service;
private final InvoiceRepository repository;
public InvoiceController(PdfService service, InvoiceRepository repository) {
this.service = service;
this.repository = repository;
}
/** Generates the PDF for the invoice received as JSON. ?download=true → attachment; ?sign=true → signed. */
@PostMapping(path = "/invoices/pdf", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<byte[]> generate(@Valid @RequestBody InvoiceRequest request,
@RequestParam(defaultValue = "false") boolean download,
@RequestParam(defaultValue = "false") boolean sign)
throws IOException, InterruptedException {
Invoice invoice = request.toInvoice(service.issuer());
byte[] pdf = service.invoice(invoice, sign);
return ResponseEntity.ok()
.headers(pdfHeaders(invoice.number(), download))
.cacheControl(CacheControl.noStore()) // personal data: don't cache
.body(pdf);
}
static HttpHeaders pdfHeaders(String number, boolean download) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
ContentDisposition.Builder disposition = download ? ContentDisposition.attachment() : ContentDisposition.inline();
headers.setContentDisposition(disposition.filename(number + ".pdf").build());
return headers;
}@Valid @RequestBodymakes Spring convert the JSON into anInvoiceRequest(with Jackson) and validate it before calling the method. If anything fails, our code doesn't even run.Content-Type: application/pdftells the client what it's receiving.Content-Dispositiondecides what the browser does:inlineshows it in its viewer;attachmentdownloads it. In both casesfilenamesuggests the name (F-2026-0042.pdf).ContentDispositiontakes care of escaping the name correctly, including non-ASCII characters.Cache-Control: no-store: an invoice contains personal and tax data; we don't want it stored in intermediate caches or in the browser's cache.
A sample request with curl:
curl -s -X POST "http://localhost:8080/invoices/pdf?download=true" \
-H "Content-Type: application/json" \
-d @invoice-42.json -o F-2026-0042.pdf -w "%{http_code} %{content_type} %{size_download}\n"byte[] or StreamingResponseBody
ResponseEntity<byte[]> |
ResponseEntity<StreamingResponseBody> |
|
|---|---|---|
| Memory | The whole PDF in memory | Written to the response as it's generated |
Content-Length |
Known and sent | Usually not (chunked transfer) |
| If something fails | Before anything has been sent: we can respond with a clean error | With the response already started: the client receives a truncated file |
| Use in InvoiceLab | Invoices (tens of KB) | PDF merges (can be hundreds of MB) |
For invoices, byte[] is the right option: they're about 50 KB and, above all, it lets us fail before responding. We'll use StreamingResponseBody for merging PDFs, where the result can be huge.
GET /invoices/{number}/pdf and caching headers
An issued invoice doesn't change. For those that already exist we offer a stable URL, and we take advantage of HTTP to avoid regenerating them when the client already has them:
@GetMapping("/invoices/{number}/pdf")
public ResponseEntity<byte[]> issued(@PathVariable String number,
@RequestParam(defaultValue = "false") boolean download,
WebRequest request) throws IOException, InterruptedException {
Invoice invoice = repository.find(number)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Invoice " + number + " doesn't exist"));
String etag = "\"" + number + "-" + Integer.toHexString(invoice.hashCode()) + "\"";
if (request.checkNotModified(etag)) {
return null; // Spring responds with 304
}
return ResponseEntity.ok()
.headers(pdfHeaders(number, download))
.eTag(etag)
.cacheControl(CacheControl.maxAge(Duration.ofHours(1)).cachePrivate())
.body(service.invoice(invoice, false));
}- The ETag is a "fingerprint" of the resource. We compute it from the invoice's data, not from the PDF's bytes: as we saw in 08-01 and will see in 08-05, two generations of the same invoice aren't byte-for-byte identical (the
/IDchanges), and an ETag based on the bytes would change on every request. ThehashCodeof arecordcombines those of its components (String,LocalDate,BigDecimal, lists), which are deterministic. - If the client sends
If-None-Matchwith that ETag,checkNotModifiedprepares a 304 Not Modified response with no body and we generate nothing. Cache-Control: max-age=3600, private: the user's browser can reuse it for an hour, but shared caches (proxies, CDNs) mustn't store it.InvoiceRepositoryis just an in-memoryMapholdingF-2026-0001here; in production it would be a database, or directly the archived PDF (signed PDF/A, 08-01), served as is without regenerating it.
Errors with ProblemDetail
Spring 6 implements RFC 9457 (Problem Details for HTTP APIs): JSON errors in a standard format (type, title, status, detail, instance and custom properties), with the application/problem+json type. We turn it on with spring.mvc.problemdetails.enabled=true and centralise the translation of exceptions:
@RestControllerAdvice
public class ErrorHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatusCode status, WebRequest request) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Invalid invoice data");
List<String> errors = ex.getBindingResult().getFieldErrors().stream()
.map(e -> e.getField() + ": " + e.getDefaultMessage())
.sorted()
.toList();
problem.setProperty("errors", errors);
return ResponseEntity.badRequest().body(problem);
}
@ExceptionHandler(IllegalArgumentException.class) // model rules (Invoice, InvoiceLine, generator)
ProblemDetail businessRule(IllegalArgumentException e) {
return ProblemDetail.forStatusAndDetail(HttpStatus.UNPROCESSABLE_ENTITY, e.getMessage());
}
@ExceptionHandler(MergeController.InvalidPdfException.class)
ProblemDetail invalidPdf(MergeController.InvalidPdfException e) {
return ProblemDetail.forStatusAndDetail(HttpStatus.UNPROCESSABLE_ENTITY, e.getMessage());
}
@ExceptionHandler(PdfService.ServiceBusyException.class)
ResponseEntity<ProblemDetail> busy(PdfService.ServiceBusyException e) {
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).header(HttpHeaders.RETRY_AFTER, "2")
.body(ProblemDetail.forStatusAndDetail(HttpStatus.SERVICE_UNAVAILABLE, e.getMessage()));
}
@ExceptionHandler(PdfService.SigningUnavailableException.class)
ProblemDetail noSigning(PdfService.SigningUnavailableException e) {
return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_IMPLEMENTED, e.getMessage());
}
}| Situation | Exception | HTTP status |
|---|---|---|
| JSON with fields that don't satisfy the annotations | MethodArgumentNotValidException |
400 Bad Request, with the errors list |
| Business rule (zero total, malformed number in the generator) | IllegalArgumentException |
422 Unprocessable Entity |
| Uploaded file that isn't a valid PDF | InvalidPdfException |
422 |
| Non-existent invoice | ResponseStatusException |
404 Not Found |
| File too large | MaxUploadSizeExceededException (handled by the base class) |
413 Content Too Large |
| Too many simultaneous generations | ServiceBusyException |
503, with Retry-After: 2 |
| Signing requested with no certificate configured | SigningUnavailableException |
501 Not Implemented |
A real error response (formatted for readability), with a malformed number and a negative quantity:
{
"type": "about:blank",
"title": "Bad Request",
"status": 400,
"detail": "Invalid invoice data",
"instance": "/invoices/pdf",
"errors": [
"lines[0].quantity: must be greater than 0",
"number: must match \"F-\\d{4}-\\d{4}\""
]
}Validation messages come out in the language of the request: Spring takes the Locale from the Accept-Language header and, if there isn't one, from the JVM. That's why the integration test sends Accept-Language: en-GB explicitly: the expected message then doesn't depend on the locale of the machine running the tests (with es-ES, for instance, Hibernate Validator would return its Spanish message). Don't include stack traces or internal paths in detail: that's information for an attacker.
POST /pdf/merge: untrusted uploads and StreamingResponseBody
Merging PDFs is useful (for example, to send a customer several invoices in a single file, like the batch from 04-04), but here the PDFs come from outside. A PDF can be deliberately malformed to exhaust memory or CPU: cyclic structures, millions of objects, compressed streams that expand to gigabytes (so-called "decompression bombs"), or simply a file that isn't a PDF at all. The rules:
- Limit size (per file and per request), the number of files and the total pages.
- Check the
%PDF-header before handing the file to PDFBox. - Write the upload to disk, not to memory, and load it with a temporary disk cache (08-03).
- Turn any parsing error into a controlled 422, never into a 500 with the stack trace.
- Reject what we can't process (encrypted documents).
@RestController
public class MergeController {
static final int MAX_FILES = 20;
static final int MAX_PAGES = 1000;
@PostMapping(path = "/pdf/merge", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<StreamingResponseBody> merge(@RequestParam("files") List<MultipartFile> files)
throws IOException {
if (files.size() < 2 || files.size() > MAX_FILES) {
throw new InvalidPdfException("Send between 2 and " + MAX_FILES + " files");
}
List<Path> tempFiles = new ArrayList<>();
List<PDDocument> sources = new ArrayList<>();
try {
int pages = 0;
for (MultipartFile file : files) {
Path temp = Files.createTempFile("merge-", ".pdf");
tempFiles.add(temp);
file.transferTo(temp); // to disk, not to memory
checkHeader(temp, file.getOriginalFilename());
PDDocument source = load(temp, file.getOriginalFilename());
sources.add(source);
pages += source.getNumberOfPages();
if (pages > MAX_PAGES) {
throw new InvalidPdfException("The result would exceed " + MAX_PAGES + " pages");
}
}
} catch (IOException | RuntimeException e) {
close(sources, tempFiles); // nothing is left open if we fail here
throw e;
}
// From here on there can be no "client" errors: everything has been validated.
StreamingResponseBody body = output -> {
try (PDDocument target = new PDDocument(IOUtils.createTempFileOnlyStreamCache())) {
PDFMergerUtility merger = new PDFMergerUtility();
for (PDDocument source : sources) {
merger.appendDocument(target, source);
}
target.save(output); // straight into the HTTP response
} finally {
close(sources, tempFiles); // the sources, after saving (04-04)
}
};
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_PDF)
.header("Content-Disposition", ContentDisposition.attachment().filename("merged.pdf").build().toString())
.body(body);
}And the helper methods:
private static void checkHeader(Path pdf, String name) throws IOException {
try (InputStream input = Files.newInputStream(pdf)) {
String start = new String(input.readNBytes(5), StandardCharsets.ISO_8859_1);
if (!start.equals("%PDF-")) {
throw new InvalidPdfException(name + " is not a PDF");
}
}
}
private static PDDocument load(Path pdf, String name) throws IOException {
PDDocument document;
try {
document = Loader.loadPDF(pdf.toFile(), IOUtils.createTempFileOnlyStreamCache());
} catch (IOException e) {
throw new InvalidPdfException(name + " cannot be read: " + e.getMessage());
}
if (document.isEncrypted()) {
document.close();
throw new InvalidPdfException(name + " is encrypted");
}
return document;
}close(sources, tempFiles) closes each document and deletes each temporary file, ignoring individual errors so that nothing is left half done. Notice the two-phase design:
- Validate everything before responding. We open each PDF, count pages and reject anything that doesn't comply. Any exception here can still be turned into a clean 422.
- Generate as a stream. The
StreamingResponseBodyruns after Spring has sent the 200 headers. If something failed inside it, we could no longer change the status: the client would receive a truncated PDF. That's why we only do things there that don't depend on the client's data.
Some important details:
appendDocumentcopies streams without decompressing them, so a "bomb" stream doesn't expand when merging. What would decompress it is extracting text or rendering, operations we don't expose here.- The source documents stay open until the target has been saved, the rule we learnt in 04-04.
StreamingResponseBodyruns on a separate thread (Spring MVC's asynchronous processing); its maximum time is controlled byspring.mvc.async.request-timeout.- PDFBox is lenient with damaged PDFs (it tries to repair them), which is good for the user but means that "it loads" doesn't imply "it's correct". If you need guarantees, also validate with veraPDF (08-01) or reject documents with structural errors.
Limits and configuration
All the limits live in application.properties, where operations can adjust them without recompiling:
spring.application.name=invoicelab
# Uploads: per-file and per-request limits
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=50MB
# JSON body and rejected requests
server.tomcat.max-http-form-post-size=1MB
server.tomcat.max-swallow-size=2MB
# Timeouts
server.tomcat.connection-timeout=10s
spring.mvc.async.request-timeout=60s
# HTTP threads (PdfService's semaphore limits simultaneous PDFs)
server.tomcat.threads.max=50
# Errors as application/problem+json
spring.mvc.problemdetails.enabled=true
# Generation concurrency (0 = available cores)
invoicelab.pdf.concurrency=0
invoicelab.pdf.wait-ms=2000
# Optional signing: path to the .p12; the password goes in INVOICELAB_P12_NEBULA
invoicelab.signature.p12=${INVOICELAB_SIGNATURE_P12:}
management.endpoints.web.exposure.include=health,metrics| Limit | Where | Protects against |
|---|---|---|
| File and multipart request size | spring.servlet.multipart.* |
Huge uploads that fill disk or memory |
| Invoice lines (500) and text lengths | @Size in the DTO |
Requests asking for gigantic PDFs |
| Files per merge (20) and total pages (1,000) | MergeController |
Disproportionate merges |
| Simultaneous generations | PdfService semaphore |
CPU and memory saturation |
| Connection and asynchronous response timeouts | server.tomcat.connection-timeout, spring.mvc.async.request-timeout |
Slow clients holding on to threads |
server.tomcat.max-http-form-post-size only affects URL-encoded forms; to really limit the size of a JSON body, the limit is usually set further in front, in the reverse proxy or gateway (for example, nginx's maximum body size). Defence in depth: each layer limits what it's responsible for.
Observability
With Actuator, the custom metrics appear alongside those of the JVM and Tomcat. After three requests to a freshly started server (the first is the slowest: class loading and JIT):
{
"name": "invoicelab.pdf.generation",
"description": "PDF generation time",
"baseUnit": "seconds",
"measurements": [
{ "statistic": "COUNT", "value": 3.0 },
{ "statistic": "TOTAL_TIME", "value": 0.316986535 },
{ "statistic": "MAX", "value": 0.223301232 }
],
"availableTags": []
}Above all, keep an eye on the 95th percentile of the duration (if it goes up, CPU is short or there are abnormally long invoices), the average size (a jump usually points to a font or image that's no longer being shared) and the number of 503 responses (if they appear often, the service needs more instances). In production you'll export these metrics to your monitoring system (Prometheus, for example) by adding the corresponding Micrometer registry.
Integration tests with MockMvc
@SpringBootTest starts the whole application and @AutoConfigureMockMvc lets you fire simulated HTTP requests without opening a port:
@SpringBootTest
@AutoConfigureMockMvc
class InvoiceControllerTest {
static final String JSON = """
{
"number": "F-2026-0042",
"date": "2026-01-15",
"customer": { "companyName": "Example Hardware Co.", "taxId": "J00000000",
"address": "45 Test Avenue, Unit 2", "postalCode": "22001",
"city": "Huesca", "email": "[email protected]" },
"lines": [
{ "reference": "TOR-M8-40", "description": "Hex bolt M8x40 (box of 100)",
"quantity": 3, "unitPrice": 18.40, "vatRate": 21 }
],
"paymentTerms": "Bank transfer within 30 days."
}
""";
@Autowired
MockMvc mvc;
@Test
void generatesAPdf() throws Exception {
MvcResult r = mvc.perform(post("/invoices/pdf").contentType(MediaType.APPLICATION_JSON).content(JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_PDF))
.andExpect(header().string("Content-Disposition", "inline; filename=\"F-2026-0042.pdf\""))
.andExpect(header().string("Cache-Control", "no-store"))
.andReturn();
byte[] pdf = r.getResponse().getContentAsByteArray();
assertThat(new String(pdf, 0, 5, StandardCharsets.ISO_8859_1)).isEqualTo("%PDF-");
try (PDDocument document = Loader.loadPDF(pdf)) {
assertThat(document.getNumberOfPages()).isEqualTo(1);
}
}
@Test
void rejectsInvalidData() throws Exception {
String bad = JSON.replace("F-2026-0042", "42").replace("\"quantity\": 3", "\"quantity\": -3");
mvc.perform(post("/invoices/pdf").contentType(MediaType.APPLICATION_JSON).content(bad)
.header("Accept-Language", "en-GB"))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.errors.length()").value(2))
.andExpect(jsonPath("$.errors[0]").value("lines[0].quantity: must be greater than 0"));
}
@Test
void mergesTwoPdfs() throws Exception {
byte[] pdf = mvc.perform(post("/invoices/pdf").contentType(MediaType.APPLICATION_JSON).content(JSON))
.andReturn().getResponse().getContentAsByteArray();
MvcResult r = mvc.perform(multipart("/pdf/merge")
.file(new MockMultipartFile("files", "a.pdf", "application/pdf", pdf))
.file(new MockMultipartFile("files", "b.pdf", "application/pdf", pdf)))
.andExpect(request().asyncStarted()) // StreamingResponseBody is asynchronous
.andReturn();
byte[] merged = mvc.perform(asyncDispatch(r))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_PDF))
.andReturn().getResponse().getContentAsByteArray();
try (PDDocument document = Loader.loadPDF(merged)) {
assertThat(document.getNumberOfPages()).isEqualTo(2);
}
}
}- Checking that the body starts with
%PDF-is cheap and catches the most typical mistake: returning an error JSON or an HTML page with status 200 and a PDF content type. Loading it withLoader.loadPDFand counting pages confirms that it's also a readable PDF. - With
StreamingResponseBody, MockMvc first returns a started asynchronous request (asyncStarted);asyncDispatchcompletes it and lets you examine the result. - The full class has seven tests: besides the three above, downloading as an
attachment, signing not configured (501), the issued invoice with its ETag (200, then 304 withIf-None-Match, and 404 for a non-existent one) and rejecting a file that isn't a PDF (422 with"detail": "a.pdf is not a PDF"). They all pass withmvn test.
If you'd rather test against a real server on a random port, use @SpringBootTest(webEnvironment = RANDOM_PORT) with TestRestTemplate or WebTestClient; for a service like this one, MockMvc is faster and sufficient.
Deploying in a container
A minimal Dockerfile for the JAR produced by mvn package (the spring-boot-maven-plugin makes it executable):
FROM eclipse-temurin:17-jre
RUN useradd --system --uid 10001 invoicelab
WORKDIR /app
COPY target/invoicelab-1.0.jar app.jar
USER invoicelab
ENV JAVA_TOOL_OPTIONS="-Djava.awt.headless=true -XX:MaxRAMPercentage=75 -Dpdfbox.fontcache=/tmp"
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "/app/app.jar"]- Fonts from
resources, never from the system. Minimal container images ship without fonts (orfontconfig). InvoiceLab already loads DejaVu from the classpath (InvoiceLabFonts), so the PDFs are identical on the developer's laptop and in the container. If you ever use a Standard 14 font or render third-party PDFs that don't embed their fonts, PDFBox will look for system fonts to substitute them and, finding none, will fall back on the LiberationSans it bundles, with results that differ from those on your machine. - Font cache in a writable directory. If PDFBox does end up looking for system fonts, it tries to write its cache to the user's home directory (
~/.pdfbox.cache), which may not exist in a container without a home;-Dpdfbox.fontcache=/tmpmoves it somewhere writable (08-03). - Unprivileged user and memory relative to the container (
MaxRAMPercentage) instead of a fixed-Xmx. - Temporary files: merge files and the stream cache go to
java.io.tmpdir. Make sure the container has space in/tmp(or mount a volume) and that nobody else can read it. - Secrets: the
.p12and its password are injected as orchestrator secrets (INVOICELAB_SIGNATURE_P12,INVOICELAB_P12_NEBULA), never inside the image.
Common Mistakes and Tips
- Returning a
byte[]without aContent-Type(or withapplication/octet-stream): the browser won't know how to open it. Always useMediaType.APPLICATION_PDF. - Building
Content-Dispositionby concatenating strings. A name with quotes or accents breaks the header. UseContentDisposition. - Sharing a
PDDocumentor aPDFontbetween requests to "save" resources. They aren't thread-safe. Share the bytes and the stateless generator, as InvoiceLab does. - Not limiting concurrency. With 200 simultaneous requests and 8 cores you don't generate faster: you generate more slowly and with more memory. Semaphore and 503.
- Loading uploads into memory (
MultipartFile.getBytes()+Loader.loadPDF(byte[])) without limits. Write what you receive to disk and use a temporary cache. - Doing validation inside the
StreamingResponseBody. When it fails, the status will already be 200. Validate beforehand. - Returning an exception's stack trace in the error body.
ProblemDetailwith an understandabledetailand nothing more. - Relying on system fonts in the container. The PDF will change between environments. Embed your fonts from
resources. - Tip: put a gateway in front of the service that limits body size and request rate per client; the service shouldn't be the only barrier.
Exercises
Exercise 1. Add a POST /invoices/pdfa endpoint that returns the invoice as PDF/A-3b using PdfAInvoiceGenerator (08-01) with a Clock injected as a bean. Write a MockMvc test that checks that the response contains the attached XML invoice-F-2026-0042.xml.
Exercise 2. Write a test that demonstrates the concurrency limit: set invoicelab.pdf.concurrency=1 and invoicelab.pdf.wait-ms=0 with @SpringBootTest(properties = ...), fire 8 simultaneous requests for a 500-line invoice and check that at least one receives a 503 with the Retry-After header.
Exercise 3. Add a time check to MergeController: if loading a file takes more than 5 seconds, it must be rejected with a 422. Hint: ExecutorService + Future.get(timeout).
Solutions
Solution 1.
@Configuration
class Clocks {
@Bean
Clock clock() {
return Clock.system(ZoneId.of("Europe/Madrid"));
}
}
// In InvoiceController (adding Clock to the constructor):
@PostMapping(path = "/invoices/pdfa", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<byte[]> generatePdfA(@Valid @RequestBody InvoiceRequest request) throws IOException {
Invoice invoice = request.toInvoice(service.issuer());
byte[] pdf = new PdfAInvoiceGenerator(new InvoiceGenerator(Theme.nebula()), PdfALevel.PDF_A_3B, clock)
.generate(invoice);
return ResponseEntity.ok().headers(pdfHeaders(invoice.number(), false))
.cacheControl(CacheControl.noStore()).body(pdf);
}
// Test:
byte[] pdf = mvc.perform(post("/invoices/pdfa").contentType(MediaType.APPLICATION_JSON).content(JSON))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsByteArray();
try (PDDocument doc = Loader.loadPDF(pdf)) {
assertThat(doc.getDocumentCatalog().getNames().getEmbeddedFiles().getNames())
.containsKey("invoice-F-2026-0042.xml");
}To keep the example short, the endpoint doesn't go through PdfService's semaphore; in your own code, move PDF/A generation into a service method to keep the limit and the metrics. In tests you can replace the Clock bean with a fixed one to get reproducible results (08-05).
Solution 2.
@SpringBootTest(properties = { "invoicelab.pdf.concurrency=1", "invoicelab.pdf.wait-ms=0" })
@AutoConfigureMockMvc
class BusyServiceTest {
@Autowired
MockMvc mvc;
@Test
void withASinglePermitSomeRequestGets503() throws Exception {
String json = jsonWithLines(500); // builds the JSON for a 500-line invoice
ExecutorService pool = Executors.newFixedThreadPool(8);
List<Future<MvcResult>> responses = new ArrayList<>();
for (int i = 0; i < 8; i++) {
responses.add(pool.submit(() -> mvc.perform(post("/invoices/pdf")
.contentType(MediaType.APPLICATION_JSON).content(json)).andReturn()));
}
long rejected = 0;
for (Future<MvcResult> f : responses) {
MockHttpServletResponse r = f.get().getResponse();
if (r.getStatus() == 503) {
assertThat(r.getHeader("Retry-After")).isEqualTo("2");
rejected++;
}
}
pool.shutdown();
assertThat(rejected).isPositive();
}
}With a single permit and zero wait, while a 500-line invoice is being generated (tens of milliseconds), the other simultaneous requests find the semaphore taken. The exact number of 503s varies between runs, which is why the test only requires "at least one". Common mistake: using a one-line invoice, which is generated so quickly that the requests hardly ever overlap.
Solution 3.
private static final ExecutorService LOADS = Executors.newCachedThreadPool();
private static PDDocument loadWithTimeout(Path pdf, String name) throws IOException {
Future<PDDocument> loading = LOADS.submit(() -> load(pdf, name));
try {
return loading.get(5, TimeUnit.SECONDS);
} catch (TimeoutException e) {
loading.cancel(true);
throw new InvalidPdfException(name + " is taking too long to process");
} catch (ExecutionException e) {
if (e.getCause() instanceof InvalidPdfException p) {
throw p;
}
throw new IOException(e.getCause());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException(e);
}
}An important limitation: cancel(true) interrupts the thread, but PDFBox's parser doesn't check for interruption, so the work may keep consuming CPU until it finishes (and the document, if it does get loaded, should be closed). For real isolation, hostile documents are processed in a separate process or container with operating-system CPU and memory limits.
Conclusion
InvoiceLab is now a service: POST /invoices/pdf turns a validated JSON into a PDF with the right headers, GET /invoices/{number}/pdf serves issued invoices with an ETag and private caching, /pdf/merge merges PDFs of unknown origin with limits, a disk cache and StreamingResponseBody, and every error comes out as a ProblemDetail. The generator is the same as ever, shared between threads because it's stateless, protected by a semaphore and measured with Micrometer; signing is optional and its secrets come from the environment; and the container doesn't depend on any system font.
The integration tests check that the service responds with a PDF, but not that the PDF is correct: that it says what it has to say, in the right place, with embedded fonts, a valid signature and the same look as yesterday. In the next lesson we'll build that safety net: a complete strategy for automated PDF testing.
PDF Generation and Editing with Apache PDFBox
Module 1: PDF and PDFBox Fundamentals
- The PDF Format and Apache PDFBox
- Setting Up the Project with PDFBox 3
- Anatomy of a PDF: COS Objects, Pages and Resources
- Your First PDF: Creating, Saving and Loading Documents
- Debugging Tools: PDFDebugger and the Command Line
Module 2: Generating Content
- Pages and the Coordinate System
- Writing Text with PDPageContentStream and Standard Fonts
- Embedded TrueType Fonts and Unicode
- Text Layout: Measuring, Aligning and Wrapping Lines
- Vector Graphics: Lines, Shapes and Colours
- Inserting Images
Module 3: Business Documents
- Building Tables from Scratch
- Multi-Page Documents: Pagination, Headers and Footers
- Barcodes and QR Codes
- Designing a Reusable Document Generator
- Project: the Complete Invoice
Module 4: Editing Existing PDFs
- Load, Modify and Save: Full and Incremental Saves
- Adding Content to Existing Pages: Stamps and Watermarks
- Page Manipulation: Inserting, Removing, Rotating and Reordering
- Merging and Splitting Documents
- Overlays, Layers and Optional Content
- Document Metadata: Info and XMP
Module 5: AcroForm Forms
- Introduction to AcroForm Forms
- Reading and Filling In Forms
- Creating Forms Programmatically
- Form Appearances and Flattening
Module 6: Extraction and Analysis
- Extracting Text with PDFTextStripper
- Area-Based Extraction and Text Positions
- Extracting Images and Resources
- Rendering Pages to Images
- Bookmarks, Links and Annotations
Module 7: Security and Digital Signatures
- Encryption and Permissions
- Digital Signatures: Concepts and PDF Structure
- Signing Documents with PDFBox and Bouncy Castle
- Verifying Signatures and Visible Signatures
