How to Extract Pages from PDF Files with Java
In this tutorial, we'll walk through how to extract pages from PDF files with Java using the Split PDF API Tool. The request expresses the desired pages as a Split PDF range and produces a new PDF containing only that selection. You'll see how the request is assembled and how to work with the response returned when you extract pages from PDF files.
Why Extract Pages from PDF Files with Java?
A case packet may contain many sections while a reviewer needs only the signed agreement and supporting schedule. Page-range extraction produces a smaller PDF without exposing unrelated pages.
The tutorial adapts Split PDF by sending the desired range in pages[]. Each range defines an output document, so multiple values can create several extracts in one request.
Java Code Example
import io.github.cdimascio.dotenv.Dotenv;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.*;
import org.json.JSONObject;
public class ExtractPagesFromPDF {
// By default, we use the US-based API service. This is the primary endpoint for global use.
private static final String API_URL = "https://api.pdfrest.com";
// For GDPR compliance and enhanced performance for European users, you can switch to the EU-based
// service by commenting out the URL above and uncommenting the URL below.
// For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
// private static final String API_URL = "https://eu-api.pdfrest.com";
// Specify the path to your file here, or as the first argument when running the program.
private static final String DEFAULT_FILE_PATH = "/path/to/file.pdf";
// Specify your API key here, or in the environment variable PDFREST_API_KEY.
// You can also put the environment variable in a .env file.
private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
public static void main(String[] args) {
File inputFile;
if (args.length > 0) {
inputFile = new File(args[0]);
} else {
inputFile = new File(DEFAULT_FILE_PATH);
}
final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();
final RequestBody inputFileRequestBody =
RequestBody.create(inputFile, MediaType.parse("application/pdf"));
RequestBody requestBody =
new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", inputFile.getName(), inputFileRequestBody)
.addFormDataPart("pages[]", "2-4")
.addFormDataPart("output", "pdfrest_extracted_pages")
.build();
Request request =
new Request.Builder()
.header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
.url(API_URL + "/split-pdf")
.post(requestBody)
.build();
try {
OkHttpClient client =
new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();
Response response = client.newCall(request).execute();
System.out.println("Result code " + response.code());
if (response.body() != null) {
System.out.println(prettyJson(response.body().string()));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static String prettyJson(String json) {
// https://stackoverflow.com/a/9583835/11996393
return new JSONObject(json).toString(4);
}
}
Source: Java sample on GitHub. For this tutorial, the general Java source has been tailored to the Extract Pages from PDF input or task.
Breaking Down the Code
Load the Java HTTP and JSON dependencies
import io.github.cdimascio.dotenv.Dotenv; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import okhttp3.*; import org.json.JSONObject;
The import block assigns a clear role to each library: HTTP communication, credential lookup, or JSON handling.
Choose the input and load credentials
// service by commenting out the URL above and uncommenting the URL below.
// For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
// private static final String API_URL = "https://eu-api.pdfrest.com";
// Specify the path to your file here, or as the first argument when running the program.
private static final String DEFAULT_FILE_PATH = "/path/to/file.pdf";
// Specify your API key here, or in the environment variable PDFREST_API_KEY.
// You can also put the environment variable in a .env file.
private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
public static void main(String[] args) {
File inputFile;
if (args.length > 0) {
inputFile = new File(args[0]);
} else {
inputFile = new File(DEFAULT_FILE_PATH);
}
final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();
final RequestBody inputFileRequestBody =
The constants section keeps a visible default path, accepts an override from the command line, and reads the API key through dotenv.
Build the multipart request body
final RequestBody inputFileRequestBody =
RequestBody.create(inputFile, MediaType.parse("application/pdf"));
RequestBody requestBody =
new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", inputFile.getName(), inputFileRequestBody)
.addFormDataPart("pages[]", "2-4")
.addFormDataPart("output", "pdfrest_extracted_pages")
.build();
Request request =
new Request.Builder()
.header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
.url(API_URL + "/split-pdf")
.post(requestBody)
.build();
try {
OkHttpClient client =
The tutorial adapts Split PDF by sending the desired range in pages[]. Each range defines an output document, so multiple values can create several extracts in one request. This payload builder packages fields and files together without hard-coding a Content-Type boundary.
Send the request to pdfRest
.build();
Request request =
new Request.Builder()
.header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
.url(API_URL + "/split-pdf")
.post(requestBody)
.build();
try {
OkHttpClient client =
new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();
Response response = client.newCall(request).execute();
The outbound call reads the credential through dotenv and targets the endpoint shown in the source, with the EU hostname documented beside the default US value.
Read the API response
try {
OkHttpClient client =
new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();
Response response = client.newCall(request).execute();
System.out.println("Result code " + response.code());
if (response.body() != null) {
System.out.println(prettyJson(response.body().string()));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static String prettyJson(String json) {
// https://stackoverflow.com/a/9583835/11996393
return new JSONObject(json).toString(4);
The returned-data block checks the server result before treating the body as output and exposes diagnostic JSON when the operation cannot be completed.
Beyond the Tutorial
In this tutorial, we walked through how to extract pages from PDF files with Java. With that foundation, you can use page extraction for document packets, evidence subsets, chapter exports, and customer-specific deliverables.
As you adapt this example for production, keep in mind that multiple range values can produce several output documents, which is useful when one packet must be separated by recipient or section. Validate ranges against the current page count and retain the source until every expected extract has been created successfully.
To continue exploring the Extract Pages from PDF operation, visit API Lab. For complete request fields, defaults, and limitations, refer to the Split PDF API Tool documentation.
Note: The Extract Pages from PDF example above uses multipart form data; when a prior API call returned the input ID, follow the JSON payload example.