To parse invoices and bank statements in Java, POST the PDF to https://api.parserkit.com/v1/parse with HttpClient. It costs $0.02 a page with 50 pages free, and our 1-page test statement passed 6 of 6 checks.
Parse invoices and bank statements in Java
The single-file program below runs on Java 21 with Jackson 2.22. It uploads a PDF, waits for the job (a bank statement takes under 15 seconds), prints the verification result, saves the Excel and CSV files and checks the signature on each webhook event.
Updated
What you need
You need Java 21 and the three Jackson 2.22 jars (jackson-databind, jackson-core and jackson-annotations from Maven group com.fasterxml.jackson.core) in a lib folder. There is no build step: java -cp "lib/*" ParserkitExample.java runs the source file directly. Sign in with Google for $1 of free credit, create a key under API keys in the dashboard and set it in PARSERKIT_API_KEY. Set PARSERKIT_WEBHOOK_URL to get a webhook for each job, and PARSERKIT_WEBHOOK_SECRET for the receiver.
The program
Run java -cp "lib/*" ParserkitExample.java parse <file> [preset] to upload a document, or java -cp "lib/*" ParserkitExample.java serve <port> to start the webhook receiver. Java's HttpClient has no built-in multipart encoder, so the program builds the body by hand: one part per form field, then the file bytes, between boundary lines. It posts that to https://api.parserkit.com/v1/parse?wait=25 with Authorization: Bearer <key>. For invoices, pass invoice as the preset or leave it out; for bank statements, pass bank_statement.
// Parse a document with the parserkit API, save its Excel and CSV files, and check webhook signatures.
// java -cp "lib/*" ParserkitExample.java parse statement.pdf bank_statement
// java -cp "lib/*" ParserkitExample.java serve 8000
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.HttpServer;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.time.Duration;
import java.util.HashMap;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executors;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class ParserkitExample {
static final String API = "https://api.parserkit.com";
static final int MAX_ATTEMPTS = 5;
static final int MAX_WAIT_S = 60;
static final int MAX_BODY_BYTES = 10 * 1024 * 1024;
static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
static final ObjectMapper JSON = new ObjectMapper();
static class ParserkitException extends Exception {
ParserkitException(String message) {
super(message);
}
}
static int retryAfter(HttpResponse<?> response, int fallback) {
String value = response.headers().firstValue("Retry-After").orElse("");
return value.matches("\\d{1,6}") ? Integer.parseInt(value) : fallback;
}
// Sends one request, waiting out 429 and 503 answers for as long as Retry-After asks
static HttpResponse<byte[]> send(HttpRequest request) throws Exception {
for (int attempt = 1; ; attempt++) {
HttpResponse<byte[]> response;
try {
response = HTTP.send(request, HttpResponse.BodyHandlers.ofByteArray());
} catch (IOException error) {
if (attempt == MAX_ATTEMPTS) throw error;
System.out.println("network error (" + error.getClass().getSimpleName() + "), retrying in 2 s");
Thread.sleep(2000);
continue;
}
if (response.statusCode() < 400) return response;
boolean isJson = response.headers().firstValue("Content-Type").orElse("").startsWith("application/json");
JsonNode body = isJson ? JSON.readTree(response.body()) : JSON.createObjectNode();
int waitS = retryAfter(response, 0);
boolean retryable = (response.statusCode() == 429 || response.statusCode() == 503) && !body.path("job").isObject();
if (retryable && waitS > 0 && waitS <= MAX_WAIT_S && attempt < MAX_ATTEMPTS) {
System.out.println(response.statusCode() + " " + body.path("error").path("code").asText() + ", retrying in " + waitS + " s");
Thread.sleep(waitS * 1000L);
continue;
}
JsonNode error = body.path("error");
String requestId = error.path("request_id").asText(response.headers().firstValue("Request-Id").orElse(null));
throw new ParserkitException(response.statusCode() + " " + error.path("code").asText() + ": " + error.path("message").asText()
+ " (request_id " + requestId + ", job " + body.path("job").path("id").asText(null) + ")");
}
}
// The multipart body, built by hand: one part per field, then the file
static byte[] multipart(String boundary, Map<String, String> fields, String fileName, byte[] file) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
for (Map.Entry<String, String> field : fields.entrySet()) {
out.writeBytes(("--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"" + field.getKey() + "\"\r\n\r\n"
+ field.getValue() + "\r\n").getBytes(StandardCharsets.UTF_8));
}
out.writeBytes(("--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName.replaceAll("[\"\\r\\n]", "_") + "\"\r\n"
+ "Content-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8));
out.writeBytes(file);
out.writeBytes(("\r\n--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8));
return out.toByteArray();
}
static JsonNode parse(Path path, String preset) throws Exception {
String auth = "Bearer " + System.getenv("PARSERKIT_API_KEY");
Map<String, String> fields = new LinkedHashMap<>();
fields.put("preset", preset);
String webhookUrl = System.getenv("PARSERKIT_WEBHOOK_URL");
if (webhookUrl != null) fields.put("webhook_url", webhookUrl);
// One key for this upload, sent again on every retry, so the API never starts a second job
String boundary = "parserkit-" + UUID.randomUUID();
byte[] body = multipart(boundary, fields, path.getFileName().toString(), Files.readAllBytes(path));
HttpRequest post = HttpRequest.newBuilder(URI.create(API + "/v1/parse?wait=25"))
.timeout(Duration.ofSeconds(90))
.header("Authorization", auth)
.header("Idempotency-Key", UUID.randomUUID().toString())
.header("Content-Type", "multipart/form-data; boundary=" + boundary)
.POST(HttpRequest.BodyPublishers.ofByteArray(body))
.build();
HttpResponse<byte[]> response = send(post);
// 202 means the job is still running. GET holds each call up to 25 s and answers 200 whatever the status, so we watch the status
JsonNode job = JSON.readTree(response.body());
int waitS = retryAfter(response, 2);
while (Set.of("queued", "running").contains(job.get("status").asText())) {
System.out.println(response.statusCode() + " " + job.get("id").asText() + " is " + job.get("status").asText() + ", checking again in " + waitS + " s");
Thread.sleep(waitS * 1000L);
response = send(HttpRequest.newBuilder(URI.create(API + "/v1/jobs/" + job.get("id").asText() + "?wait=25"))
.timeout(Duration.ofSeconds(90))
.header("Authorization", auth)
.build());
job = JSON.readTree(response.body());
waitS = 2;
}
if (job.get("status").asText().equals("failed")) {
throw new ParserkitException("failed " + job.path("error").path("code").asText() + ": " + job.path("error").path("message").asText()
+ " (request_id " + response.headers().firstValue("Request-Id").orElse(null) + ", job " + job.get("id").asText() + ")");
}
return job;
}
static void report(JsonNode job) {
System.out.println(job.get("id").asText() + ": " + job.get("status").asText() + ", " + job.get("pages").asInt() + " page(s), $" + job.get("cost_usd").asText());
if (job.path("data_omitted").asBoolean()) {
System.out.println("verification: " + job.path("verification_status").asText() + ", the full result is at data_url");
return;
}
JsonNode verification = job.get("verification");
JsonNode coverage = verification.get("coverage");
int passed = 0;
for (JsonNode check : verification.get("checks")) {
if (check.get("status").asText().equals("pass")) passed++;
}
System.out.println("verification: " + verification.get("status").asText() + ", " + coverage.get("checked").asInt() + " of " + coverage.get("values").asInt() + " values checked");
System.out.println("checks: " + passed + " of " + verification.get("checks").size() + " pass");
for (JsonNode check : verification.get("checks")) {
if (check.get("status").asText().equals("pass")) continue;
System.out.println(" " + check.get("status").asText() + " " + check.get("kind").asText() + " " + check.get("path").asText() + ": " + check.get("message").asText());
}
JsonNode data = job.get("data");
if (job.get("preset").asText().equals("bank_statement")) {
System.out.println(data.path("bank").path("name").asText() + ", " + data.path("period_start").asText() + " to " + data.path("period_end").asText()
+ ": " + data.path("transactions").size() + " transactions, opening " + data.path("opening_balance").asText()
+ ", closing " + data.path("closing_balance").asText() + " " + data.path("currency").asText());
} else {
System.out.println("invoice " + data.path("invoice_number").asText() + " from " + data.path("vendor").path("name").asText() + ", " + data.path("issue_date").asText()
+ ": " + data.path("line_items").size() + " lines, total " + data.path("grand_total").asText() + " " + data.path("currency").asText());
}
for (JsonNode warning : job.get("warnings")) {
System.out.println("warning " + warning.get("code").asText() + ": " + warning.get("message").asText());
}
}
static void download(JsonNode job) throws Exception {
for (JsonNode output : job.get("outputs")) {
String name = output.get("name").asText();
if (!List.of("output.xlsx", "output.csv").contains(name)) continue;
// Signed links need no API key; keep them out of your logs
HttpRequest get = HttpRequest.newBuilder(URI.create(output.get("url").asText())).timeout(Duration.ofSeconds(90)).build();
byte[] content = send(get).body();
Path target = Path.of(job.get("id").asText() + "-" + name);
Files.write(target, content);
System.out.println("saved " + target + " (" + content.length + " bytes)");
}
}
static boolean verifySignature(String secret, byte[] rawBody, String header, long toleranceS) throws GeneralSecurityException {
Map<String, String> parts = new HashMap<>();
for (String part : header.split(",")) {
int equals = part.indexOf('=');
if (equals > 0) parts.put(part.substring(0, equals), part.substring(equals + 1));
}
long t;
try {
t = Long.parseLong(parts.getOrDefault("t", ""));
} catch (NumberFormatException error) {
return false;
}
if (Math.abs(System.currentTimeMillis() / 1000 - t) > toleranceS) return false;
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
mac.update((t + ".").getBytes(StandardCharsets.UTF_8));
byte[] expected = HexFormat.of().formatHex(mac.doFinal(rawBody)).getBytes(StandardCharsets.UTF_8);
return MessageDigest.isEqual(expected, parts.getOrDefault("v1", "").getBytes(StandardCharsets.UTF_8));
}
static void serve(int port) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
// Each delivery gets its own virtual thread, so one slow client can't hold up the rest
server.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
server.createContext("/", exchange -> {
byte[] rawBody = exchange.getRequestBody().readNBytes(MAX_BODY_BYTES + 1);
if (rawBody.length > MAX_BODY_BYTES) {
System.out.println("oversized body, answered 413");
exchange.sendResponseHeaders(413, -1);
exchange.close();
return;
}
String header = exchange.getRequestHeaders().getFirst("Parserkit-Signature");
boolean valid;
try {
valid = verifySignature(System.getenv("PARSERKIT_WEBHOOK_SECRET"), rawBody, header == null ? "" : header, 300);
} catch (GeneralSecurityException error) {
valid = false;
}
if (!valid) {
System.out.println("signature check failed, answered 401");
exchange.sendResponseHeaders(401, -1);
exchange.close();
return;
}
JsonNode event = JSON.readTree(rawBody);
System.out.println("signature ok: " + event.get("type").asText() + " " + event.path("data").path("id").asText()
+ " (" + exchange.getRequestHeaders().getFirst("Idempotency-Key") + ", attempt " + exchange.getRequestHeaders().getFirst("Parserkit-Attempt") + ")");
exchange.sendResponseHeaders(200, -1);
exchange.close();
});
server.start();
System.out.println("listening on port " + port);
}
public static void main(String[] args) throws Exception {
if (args.length >= 2 && args[0].equals("parse")) {
try {
JsonNode job = parse(Path.of(args[1]), args.length > 2 ? args[2] : "invoice");
report(job);
download(job);
} catch (ParserkitException error) {
System.err.println("parserkit error " + error.getMessage());
System.exit(1);
}
} else if (args.length == 2 && args[0].equals("serve")) {
serve(Integer.parseInt(args[1]));
} else {
System.err.println("usage: java -cp \"lib/*\" ParserkitExample.java parse <file> [preset] | serve <port>");
System.exit(2);
}
}
}Run it
On a one-page bank statement with the bank_statement preset, the job succeeds in under 15 seconds for $0.02. The verification status comes back verified when every check passes: the closing balance (two ways), the total credits, the total debits, the running balance on every row and the routing number checksum. The program prints the bank, the statement period, the number of transactions and the opening and closing balances.
$ java -cp "lib/*" ParserkitExample.java parse statement-coldwater-2026-09.pdf bank_statement job_kindfywmlp3koav4k4rg: succeeded, 1 page(s), $0.02 verification: verified, 68 of 68 values checked checks: 6 of 6 pass Coldwater Valley Credit Union, 2026-09-01 to 2026-09-30: 14 transactions, opening 2213.64, closing 4835.47 USD saved job_kindfywmlp3koav4k4rg-output.xlsx (9674 bytes) saved job_kindfywmlp3koav4k4rg-output.csv (888 bytes)
| Field | What it holds | Our run |
|---|---|---|
status | queued, running, succeeded or failed | succeeded |
verification.status | verified, partial, unverified or discrepancy | verified |
verification.coverage | Values read and values with a check | 68 and 68 |
verification.checks | One entry per check, with kind, path, status and message | 6, all pass |
data | The fields read from the document | 14 transactions, closing balance 4835.47 USD |
outputs | Signed links to the files | 5 files |
warnings | Anything the parser flagged | none |
cost_usd | What the job cost | 0.02 |
{
"id": "job_kindfywmlp3koav4k4rg",
"status": "succeeded",
...
"cost_usd": 0.02,
"verification_status": "verified",
...
"verification": {
"status": "verified",
"math_balanced": true,
"coverage": {
"values": 68,
"checked": 68
},
"checks": [
{
"kind": "balance",
"path": "closing_balance",
"fields": [
"opening_balance",
"total_credits",
"total_debits",
"closing_balance"
],
"status": "pass",
"expected": 4835.47,
"actual": 4835.47,
"difference": 0,
"page": 1,
"message": "opening balance + total credits - total debits"
},
...
{
"kind": "running_balance",
"path": "transactions[].balance",
"fields": [
"transactions[].balance",
"transactions[].amount"
],
"status": "pass",
"expected": null,
"actual": null,
"difference": null,
"page": null,
"message": "14 of 14 printed balances follow from the one before (in printed order)"
},
...
],
"repairs": [],
"barcodes": []
},
...
"warnings": []
}Trimmed with ...: the other job fields and the other checks.
The wait parameter can be 0 to 60 seconds (default 60). Our job took 12 seconds, so the first POST answered 200 with the finished job. When a job takes longer than wait, the POST answers 202 with Location and Retry-After: 2, and the program polls GET /v1/jobs/{id}?wait=25. That call holds up to 25 seconds and answers 200 with the job whatever its status, so the program repeats it while the status is queued or running and stops with the error code if the status is failed.
Excel and CSV files
Once the job succeeds, the program downloads output.xlsx and output.csv from the signed links in outputs; the list also has output.json, quickbooks.csv and xero.csv. The CSV has one row per transaction with date, description, amount, balance and page. The signed links don't need your API key and last at least an hour, so keep them out of your logs. If a result is very large, data_omitted is true and the job gives a data_url link instead of inline data; the program then prints the verification status and stops.
[
...
{
"name": "output.xlsx",
"bytes": 9674,
"url": "https://files.parserkit.com/f/7d/acct_.../job_kindfywmlp3koav4k4rg/out/output.xlsx?exp=1794051600&sig=...",
"expires_at": "2026-11-07T11:40:00.000Z"
},
{
"name": "output.csv",
"bytes": 888,
"url": "https://files.parserkit.com/f/7d/acct_.../job_kindfywmlp3koav4k4rg/out/output.csv?exp=1794051600&sig=...",
"expires_at": "2026-11-07T11:40:00.000Z"
},
...
]Trimmed to the two files the program saves. The signature in each link and the account id are replaced with ...
date,description,amount,balance,page 2026-09-01,"Rent payment, Birch Lane Properties",-1185.00,1028.64,1 2026-09-11,"Card purchase, Sawtooth Fuel",-50.08,978.56,1 2026-09-11,"Card purchase, Riverbend Grocery",-66.93,911.63,1 2026-09-12,"Payroll deposit, Branch County Schools",1962.48,2874.11,1 2026-09-14,"Card purchase, Lantern Hill Pharmacy",-17.18,2856.93,1 2026-09-15,"Electric bill, Lakeshore Power",-97.42,2759.51,1 2026-09-22,"Card purchase, Sawtooth Fuel",-44.60,2714.91,1 2026-09-26,"Payroll deposit, Branch County Schools",1962.48,4677.39,1 2026-09-26,"Card purchase, Sawtooth Fuel",-55.66,4621.73,1 2026-09-27,"Card purchase, Millrace Hardware",-18.31,4603.42,1 2026-09-28,"Phone bill, Northway Mobile",-54.99,4548.43,1 2026-09-28,Mobile check deposit,161.00,4709.43,1 2026-09-29,Mobile check deposit,125.00,4834.43,1 2026-09-30,Dividend paid,1.04,4835.47,1
As saved by the run, without the UTF-8 byte order mark at the start of the file.
Errors and retries
When we sent 4096 random bytes instead of a PDF, the API answered 415 with error.code set to UNSUPPORTED_FORMAT, a request id (also in the Request-Id header), and no job. Errors and limits lists the other codes.
$ java -cp "lib/*" ParserkitExample.java parse random.bin parserkit error 415 UNSUPPORTED_FORMAT: this file type is not supported (request_id a56bb5b0bfe6dc76, job null)
Rate limits and temporary faults answer 429 (RATE_LIMITED, BUSY, CONTENT_REFUSALS) or 503 (CONTAINER_UNAVAILABLE) with a Retry-After header. The program waits that many seconds and tries again, up to 5 attempts, as long as Retry-After is 60 seconds or less; a longer wait stops it with the error. It sends one Idempotency-Key (a random UUID) per upload and repeats it on every retry, so the same key and request return the same job for 24 hours instead of starting a second one, and a changed request with the same key answers 409 IDEMPOTENCY_CONFLICT.
Webhook signatures
If you pass webhook_url, parserkit POSTs an event like job.succeeded or job.failed to your HTTPS URL with Parserkit-Signature, Idempotency-Key (the event id, the same on all of up to 5 attempts, 15 seconds each), Parserkit-Attempt, Parserkit-Event and Parserkit-Job-Id. The receiver runs the JDK's com.sun.net.httpserver.HttpServer on virtual threads and refuses bodies over 10 MB. It checks that t in Parserkit-Signature (t=<unix seconds>,v1=<hex>) is within 300 seconds of the clock, computes the HmacSHA256 of "<t>.<raw body>" with your whsec_ signing secret from Webhooks before parsing JSON, and compares with MessageDigest.isEqual. In production, store the event id and skip repeats. See Webhooks for details.
$ java -cp "lib/*" ParserkitExample.java serve 8003 listening on port 8003 ... signature ok: job.succeeded job_kindfywmlp3koav4k4rg (evt_qxizacymenc8zdhjyxgy, attempt 1) signature check failed, answered 401
Our receiver ran on port 8003 behind a tunnel. The first request is the real delivery; the second is the same delivery with the first digit of closing_balance changed. Lines from earlier local tests are cut at ...
We pointed webhook_url at the receiver through a tunnel during our run. The live delivery evt_qxizacymenc8zdhjyxgy got 200, a copy with one digit of closing_balance changed got 401, and in a local test a delivery with a timestamp more than 300 seconds old also got 401.
Questions
What are the file size and page limits?
A multipart upload can be up to 25 MB, or up to 100 MB with file_url or /v1/uploads, with up to 250 pages a job. Results and files are kept 7 days, or 90 days on Pro.
Do failed jobs or duplicate uploads cost money?
No, failed jobs and exact duplicates cost nothing. Successful jobs cost $0.02 a page (see pricing).
What do the verification statuses mean?
verified means every required value has a check and none fail, partial means some value has no check, and unverified means there are no checks. discrepancy means a check still fails after repair; each check in verification.checks has its kind, path, status and message, and verification.coverage has the counts.
What happens if I upload the same statement twice?
With the same Idempotency-Key within 24 hours you get the same job back. With a new key you get a new job; if the file, preset and schema match an earlier job, it copies that result and costs nothing.
Your first $1 is free, 50 pages with every check and export.