The pdfRest PDF to Images API Tool allows developers to convert PDF documents into image files programmatically. In this tutorial, we will explore how to send an API call to the PDF to Images endpoint using PHP.
This functionality is particularly useful in scenarios where you need to display PDF content as images on a web page, extract images for archival purposes, or prepare documents for presentations where image formats are required.
require 'vendor/autoload.php'; use GuzzleHttp\Client; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Utils; $client = new Client(); $headers = [ 'Api-Key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' ]; $options = [ 'multipart' => [ [ 'name' => 'file', 'contents' => Utils::tryFopen('/path/to/file', 'r'), 'filename' => '/path/to/file', 'headers' => [ 'Content-Type' => '' ] ], [ 'name' => 'pages', 'contents' => '1-last' ], [ 'name' => 'resolution', 'contents' => '300' ], [ 'name' => 'color_model', 'contents' => 'rgb' ], [ 'name' => 'jpeg_quality', 'contents' => '75' ], [ 'name' => 'output', 'contents' => 'pdfrest_jpg' ] ] ]; $request = new Request('POST', 'https://api.pdfrest.com/jpg', $headers); $res = $client->sendAsync($request, $options)->wait(); echo $res->getBody();
Reference: PDF to Images API PHP Sample Code
The code above is a PHP script that uses the Guzzle HTTP client to make a multipart/form-data POST request to the pdfRest API. Here's a breakdown of the key parts:
require 'vendor/autoload.php';
: This line includes the Composer autoload file, which autoloads the Guzzle HTTP client library.use GuzzleHttp\Client;
: This imports the Guzzle HTTP client class into the current namespace.$headers
: This array contains the necessary headers for the request, including the 'Api-Key' used for authentication with the pdfRest API.$options
: This array specifies the multipart/form-data fields. Each field has a 'name' and 'contents' key, and some fields may include additional headers or filenames.new Request('POST', 'https://api.pdfrest.com/jpg', $headers);
: This creates a new HTTP POST request with the specified URL and headers.$client->sendAsync($request, $options)->wait();
: This sends the request asynchronously and waits for the response.echo $res->getBody();
: This line outputs the response body, which should contain the converted image data.In this tutorial, we've demonstrated how to call the pdfRest PDF to Images API using PHP. By sending a multipart/form-data request, we've instructed the API to convert a PDF file into images, with options to specify pages, resolution, color model, JPEG quality, and output file name. To explore all of the pdfRest API Tools, you can visit the API Lab and refer to the API Reference documentation for more details.
Note: This is an example of a multipart API call. Code samples using JSON payloads can be found at JSON Payload PHP Sample Code.
Create your FREE API Key to start processing PDFs in seconds, only possible with pdfRest.