How to Extract Images from PDF Files with PHP

Learn how to extract all images from PDFs with pdfRest Extract Images API tool using PHP
Share this page

Extract PDF Images with PHP and Guzzle

PDFs often package photographs, illustrations, charts, logos, and scanned content inside a larger document. When an application needs those assets independently, rendering each whole page creates extra content and may change the image properties. The pdfRest Extract Images API Tool retrieves the images embedded in the PDF without modifying the source document.

Extracted assets retain their native formats and original properties whenever possible, including common JPEG, PNG, and TIFF images. This gives PHP applications a direct way to populate a digital asset system, repurpose publication graphics, archive source images, or pass visual data into another workflow without building and maintaining a local PDF image parser.

For example, a PHP content-management portal can accept a press kit as a PDF, extract its embedded logos and photographs, and make those assets available to an editor for selection. Automating that step reduces repetitive file handling and keeps the PDF and its extracted assets connected within the same intake workflow.

The /extracted-images example uses Guzzle to send a PDF and parameters as multipart form data. The response identifies every extracted output so the application can retrieve or reuse the files.

PHP Extract Images Code Example

Install Guzzle with Composer, load Composer's autoloader, and replace the file path and API-key placeholders. The corrected example identifies the uploaded file as application/pdf and uses valid PHP array syntax.

require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Utils;

// By default, we use the US-based API service. This is the primary endpoint for global use.
$apiUrl = "https://api.pdfrest.com";

/* For GDPR compliance and enhanced performance for European users, you can switch to the EU-based service by uncommenting the URL below.
 * For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
 */
//$apiUrl = "https://eu-api.pdfrest.com";

$client = new Client();
$filePath = '/path/to/file.pdf';

$headers = [
  'Api-Key' =--> 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
];

$options = [
  'multipart' => [
    [
      'name' => 'file',
      'contents' => Utils::tryFopen($filePath, 'r'),
      'filename' => basename($filePath),
      'headers' => [
        'Content-Type' => 'application/pdf'
      ]
    ],
    [
      'name' => 'pages',
      'contents' => '1-last'
    ],
    [
      'name' => 'output',
      'contents' => 'pdfrest_extracted_images'
    ]
  ]
];

$request = new Request('POST', $apiUrl . '/extracted-images', $headers);
$response = $client->sendAsync($request, $options)->wait();

echo $response->getBody();

Source: pdfRest Extract Images multipart PHP 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 PHP.

Configure the Multipart Fields

Guzzle's multipart option accepts an array of form parts. The file part opens the local PDF as a stream, supplies a filename, and declares its media type. Streaming is more suitable than reading the complete file into a PHP string when input sizes vary.

The pages part controls which pages pdfRest examines. The sample uses 1-last for the entire document, but applications can combine individual pages and ranges, such as 1,2,5-10,12-last. The output part supplies a base name. pdfRest appends an image sequence and the page where the asset first appeared, producing names such as pdfrest_extracted_images-img001-page002.

The request posts to $apiUrl . '/extracted-images'. The sample defaults to the US Cloud API and includes the EU base URL as a configuration option. Keep both the base URL and API key in environment-specific configuration so credentials and data-residency choices do not have to be edited in application code.

Handle Every Extracted Image

An extraction request can return more than one image, so parse the output URL and resource ID collections rather than reading only the first value. Download URLs can be used to store the files in your own system. Resource IDs can be passed directly to another pdfRest API Tool, eliminating unnecessary transfer of intermediate files within a multi-step workflow.

If the PDF contains no embedded images, the endpoint can still return 200 OK with a warning and empty outputUrl and outputId arrays. Handle this as a no-results condition. If the requirement is to create an image of every complete page rather than retrieve embedded assets, use the PDF to Images tool instead.

Add Production Error Handling

The sample uses sendAsync(...)->wait() and prints the response body. In a production application, catch Guzzle request and connection exceptions, inspect the HTTP status, and validate the JSON structure before using the output fields. Set timeouts appropriate to the application's file sizes and processing expectations. Avoid echoing sensitive response content into public pages or shared logs.

Store the API key in an environment variable or secret manager, validate the source path before calling Utils::tryFopen, and close or release resources according to the surrounding application framework. Test PDFs with representative image formats, page ranges, and no-image cases before automating large batches.

Use API Lab to try the endpoint without writing code, and consult the Extract Images API reference for the current parameters and response fields.

Generate a self-service API Key now!
Create your FREE API Key to start processing PDFs in seconds, only possible with pdfRest.