How to Extract Images from PDF Files with Java
Extract Embedded Images from a PDF in Java
When an application needs the photographs, diagrams, logos, or other assets inside a PDF, rendering whole pages adds surrounding text and layout that the asset workflow does not need. The pdfRest Extract Images API Tool retrieves the embedded image objects themselves, preserving their native formats and properties whenever possible.
That makes the output useful for digital asset management, publishing, content reuse, and visual-analysis pipelines without forcing every asset through an additional rendering or conversion process. Targeted page ranges and resource-ID input support both one-off uploads and multi-step document workflows.
For example, a Java-based publishing system can extract figures from submitted technical papers and route them to an editorial review queue. Page-aware filenames help editors trace each figure back to the document location where it first appeared, while native-format extraction preserves the image for later print or digital use.
This example uses OkHttp to upload a local PDF as multipart form data and org.json to format the response.
Java Extract Images Code Example
Add OkHttp, java-dotenv, and JSON-java to the project, then set PDFREST_API_KEY in the environment or a local .env file. Pass the PDF path as the first command-line argument or replace DEFAULT_FILE_PATH.
import io.github.cdimascio.dotenv.Dotenv;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.json.JSONObject;
public class ExtractedImages {
// 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";
private static final String PAGES = "1-last";
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", PAGES)
.addFormDataPart("output", "pdfrest_extracted_images")
.build();
Request request =
new Request.Builder()
.header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
.url(API_URL + "/extracted-images")
.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: pdfRest Extract Images multipart Java sample
If the source PDF already has a pdfRest resource ID, send a JSON payload instead of uploading it again as multipart data. See the Extract Images JSON-payload sample for Java.
Build the OkHttp Multipart Request
The sample creates a file request body with the application/pdf media type, then adds it to a MultipartBody under the file field. The pages value of 1-last tells pdfRest to inspect the complete document. To limit processing, use individual pages and ranges such as 1,2,5-10,12-last.
The output value establishes a base name for every extracted asset. pdfRest adds an image sequence and the source page number to each name, producing results such as pdfrest_extracted_images-img001-page002. Predictable naming helps downstream code associate an asset with its location in the document even when one request returns several files.
The request reads the API key through Dotenv and posts to API_URL + "/extracted-images". The default base URL uses the US Cloud API; the alternate constant shown in the code selects EU-based processing when required.
Process Results and Empty Responses
A successful extraction can return multiple output URLs and resource IDs. Parse these collections and handle each image rather than assuming a single output. Download URLs support retrieving the files, while resource IDs let another pdfRest operation use an image without an intermediate download and re-upload.
Not every PDF contains extractable image objects. When none are found, pdfRest can return 200 OK with a warning and empty outputUrl and outputId arrays. The application should distinguish this valid outcome from an error and decide whether no images is expected, reportable, or a reason to use a different operation such as rendering complete pages.
Strengthen Response Handling for Production
The example sets a 60-second read timeout and prints the status code and formatted response body. Production Java code should also verify response.isSuccessful(), parse the expected fields only after a successful status, and handle network failures separately from API validation errors. Use try-with-resources around the OkHttp Response so its body is always closed, especially in a service that processes many requests.
Keep the API key out of source control and prevent sensitive document data from entering application logs. Apply the application's input-path and file policies before constructing the request, then use the returned collections to handle varied image formats and output counts consistently.
You can generate requests in API Lab and review the current request and response schema in the Extract Images API reference.