Frameworks · Updated 2026-12-03
Generate PDFs in Java and Spring Boot
This guide renders PDFs from Java with one HTTP call. You send a template id and your data as JSON, and you get back a link or the file itself. There is no PDF library to learn and no browser to run, so the same code works on a laptop, in a container or on any JVM host.
You need Java 17 or later (for java.net.http.HttpClient and records), Jackson for JSON, and a DevilPDF API key. The free plan includes 500 documents a month.
#1. Set up
Sign up, open API keys in the dashboard and create a key. It starts with dp_live_. Keep it in an environment variable, never in code you commit:
export DEVILPDF_API_KEY="dp_live_..."Add Jackson if your project does not have it already. Spring Boot includes it.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.2</version>
</dependency>#2. Render an invoice and get a link
Every account can use seven starter templates: invoice, quote, receipt, statement, report, packing-slip and certificate. This renders the invoice starter, building the JSON from a Map:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
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.List;
import java.util.Map;
public class Render {
public static void main(String[] args) throws Exception {
ObjectMapper json = new ObjectMapper();
Map<String, Object> body = Map.of(
"template", "invoice",
"data", Map.of(
"number", "INV-1001",
"issue_date", "2026-12-03",
"due_date", "2027-01-02",
"company", Map.of("name", "Northwind Studio", "address", "410 Bay Street\nToronto, ON M5H 2Y4"),
"customer", Map.of("name", "Acme Robotics Inc.", "address", "2200 Mission Street\nSan Francisco, CA 94110"),
"items", List.of(
Map.of("name", "Brand identity system", "quantity", 1, "unit_price", 4800),
Map.of("name", "Front-end development", "description", "Billed hourly", "quantity", 46, "unit_price", 135)
),
"tax_rate", 13,
"tax_label", "HST"
),
"filename", "INV-1001"
);
HttpRequest request = HttpRequest.newBuilder(URI.create("https://devilpdf.com/v1/render"))
.header("Authorization", "Bearer " + System.getenv("DEVILPDF_API_KEY"))
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(60))
.POST(HttpRequest.BodyPublishers.ofString(json.writeValueAsString(body)))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
JsonNode doc = json.readTree(response.body());
if (response.statusCode() / 100 != 2) {
JsonNode error = doc.path("error");
throw new IllegalStateException(error.path("type").asText() + ": " + error.path("message").asText());
}
System.out.println(doc.path("url").asText() + " " + doc.path("pages").asInt());
}
}The response is a document object with an id, the page count in pages, and a signed download link in url. The invoice template adds up the line items, tax and total itself, so you never send totals.
To see every field a starter accepts, fetch it and read sample_data:
curl https://devilpdf.com/v1/templates/invoice \
-H "Authorization: Bearer $DEVILPDF_API_KEY"#3. Get the PDF bytes and save them
Add "output": "file" and the response body is the PDF itself. Nothing is stored on DevilPDF's side. Put the call in a small class you can reuse:
import com.fasterxml.jackson.databind.JsonNode;
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.HashMap;
import java.util.Map;
public class DevilPdf {
private static final URI RENDER = URI.create("https://devilpdf.com/v1/render");
private final HttpClient http = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build();
private final ObjectMapper json = new ObjectMapper();
private final String apiKey = System.getenv("DEVILPDF_API_KEY");
public byte[] renderPdf(Map<String, Object> body) throws IOException, InterruptedException {
Map<String, Object> payload = new HashMap<>(body);
payload.put("output", "file");
HttpRequest request = HttpRequest.newBuilder(RENDER)
.header("Authorization", "Bearer " + apiKey)
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(60))
.POST(HttpRequest.BodyPublishers.ofByteArray(json.writeValueAsBytes(payload)))
.build();
HttpResponse<byte[]> response = http.send(request, HttpResponse.BodyHandlers.ofByteArray());
if (response.statusCode() / 100 != 2) {
JsonNode error = json.readTree(response.body()).path("error");
throw new IOException(error.path("type").asText() + ": " + error.path("message").asText());
}
return response.body();
}
}HttpClient is thread-safe and keeps connections open, so create one and reuse it. Errors still come back as JSON with an error object, so check the status before you treat the body as a file. The devilpdf-document-id and devilpdf-pages response headers identify the document in your log: read them with response.headers().firstValue("devilpdf-document-id").
The data can be records instead of maps. Jackson 2.12 and later writes records as JSON objects. Use @JsonProperty where the template's field name is in snake case:
import com.fasterxml.jackson.annotation.JsonProperty;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
public class SaveReceipt {
record Party(String name) {}
record Payment(String method, String last4) {}
record LineItem(String name, int quantity, @JsonProperty("unit_price") double unitPrice) {}
record Receipt(
String number,
@JsonProperty("paid_at") String paidAt,
Party company,
Party customer,
Payment payment,
List<LineItem> items
) {}
public static void main(String[] args) throws Exception {
Receipt receipt = new Receipt(
"R-10482",
"2026-12-03",
new Party("Lumen Cycle Works"),
new Party("Jordan Alvarez"),
new Payment("Visa", "4242"),
List.of(new LineItem("Full tune-up", 1, 129))
);
byte[] pdf = new DevilPdf().renderPdf(Map.of("template", "receipt", "data", receipt));
Files.write(Path.of("receipt.pdf"), pdf);
System.out.println("Saved receipt.pdf (" + pdf.length + " bytes)");
}
}BigDecimal amounts work too. Jackson writes them as JSON numbers.
#4. Serve it from Spring Boot
A controller that returns the PDF to the browser. The API key stays on the server. Mark DevilPdf from step 3 with @Service (or declare it as a @Bean) so Spring can inject it.
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
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;
@RestController
public class InvoiceController {
private final DevilPdf devilPdf;
public InvoiceController(DevilPdf devilPdf) {
this.devilPdf = devilPdf;
}
@GetMapping("/invoices/{number}.pdf")
public ResponseEntity<byte[]> invoicePdf(@PathVariable String number) throws InterruptedException {
Map<String, Object> order = loadOrder(number);
if (order == null) {
return ResponseEntity.notFound().build();
}
byte[] pdf;
try {
pdf = devilPdf.renderPdf(Map.of(
"template", "invoice",
"data", order,
"filename", "invoice-" + number
));
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.BAD_GATEWAY).build();
}
ContentDisposition disposition = ContentDisposition.inline()
.filename("invoice-" + number + ".pdf")
.build();
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_PDF)
.header(HttpHeaders.CONTENT_DISPOSITION, disposition.toString())
.body(pdf);
}
// Replace with your database lookup.
private Map<String, Object> loadOrder(String number) {
return Map.of(
"number", number,
"customer", Map.of("name", "Acme Robotics Inc."),
"items", List.of(Map.of("name", "Consulting", "quantity", 3, "unit_price", 150))
);
}
}inline opens the PDF in the browser tab. Use ContentDisposition.attachment() to make the browser download it instead. A render normally takes well under a second, so calling it inside a request is fine.
#With Spring's RestClient
On Spring Boot 3.2 or later you can make the same call with RestClient and let Spring's Jackson converter write the body:
RestClient devilpdf = RestClient.builder()
.baseUrl("https://devilpdf.com")
.defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + System.getenv("DEVILPDF_API_KEY"))
.build();
byte[] pdf = devilpdf.post()
.uri("/v1/render")
.contentType(MediaType.APPLICATION_JSON)
.body(Map.of("template", "invoice", "data", order, "output", "file"))
.retrieve()
.body(byte[].class);On a 4xx or 5xx status, retrieve() throws a RestClientResponseException. Its getResponseBodyAsString() holds the JSON error object with type and message. Branch on type, as described in errors.
#5. Any language, same code
Add locale and the starter's labels, dates and money switch language. Arabic, Hebrew, Persian and Urdu also flip the page right to left. Fonts for every script are loaded for you.
byte[] pdf = devilPdf.renderPdf(Map.of(
"template", "invoice",
"locale", "ar",
"data", Map.of(
"number", "INV-1002",
"currency", "SAR",
"customer", Map.of("name", "شركة الأفق للتجارة"),
"items", List.of(Map.of("name", "استشارات", "quantity", 3, "unit_price", 1250))
)
));See languages and locales for the full list.
#Many documents at once
For hundreds of PDFs, do not loop over /v1/render and wait on each one, even from a thread pool. Send them to POST /v1/render/batch in one request, with what the documents share at the top level and what differs in items. You get a webhook as each document finishes and a batch.completed event at the end. Batch documents are always stored and returned as links. See async and batch for the request shape and batch sizes per plan.
#Next steps
- Quickstart: the same request in curl, Node, Python, PHP, Go and Ruby.
- Templates: copy a starter and make it yours.
- Render reference: page size, margins, fonts, passwords and every other option.
- Generate PDFs in Node.js and in Python.
- Get a free API key