How to Convert a PNG Array to PDF Format in PHP
Writing PHP code to convert between common image formats can be a pain. Thankfully, if we use a free API with readily available code examples, we don’t have to do any of that work ourselves.
Using the complementary, ready-to-run code examples below, we can take advantage of a free API to convert our PNG arrays to PDF format. We’ll end up with a PDF containing exactly one page per image included in the original PNG array.
Structuring our API call is extremely straightforward. First, to install the PHP client with Composer, let’s execute this command from the command line:
composer require cloudmersive/cloudmersive_document_convert_api_client
Next, let’s copy the below code into our file to call the function. We can include 10+ PNG file paths in our request (a minimum of 2 are required):
<?php
require_once(__DIR__ . '/vendor/autoload.php');
// Configure API key authorization: Apikey
$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('Apikey', 'YOUR_API_KEY');
$apiInstance = new Swagger\Client\Api\ConvertDocumentApi(
new GuzzleHttp\Client(),
$config
);
$input_file1 = "/path/to/inputfile"; // \SplFileObject | First input file to perform the operation on.
$input_file2 = "/path/to/inputfile"; // \SplFileObject | Second input file to perform the operation on.
$input_file3 = "/path/to/inputfile"; // \SplFileObject | Third input file to perform the operation on.
$input_file4 = "/path/to/inputfile"; // \SplFileObject | Fourth input file to perform the operation on.
$input_file5 = "/path/to/inputfile"; // \SplFileObject | Fifth input file to perform the operation on.
$input_file6 = "/path/to/inputfile"; // \SplFileObject | Sixth input file to perform the operation on.
$input_file7 = "/path/to/inputfile"; // \SplFileObject | Seventh input file to perform the operation on.
$input_file8 = "/path/to/inputfile"; // \SplFileObject | Eighth input file to perform the operation on.
$input_file9 = "/path/to/inputfile"; // \SplFileObject | Ninth input file to perform the operation on.
$input_file10 = "/path/to/inputfile"; // \SplFileObject | Tenth input file to perform the operation on.
try {
$result = $apiInstance->convertDocumentPngArrayToPdf($input_file1, $input_file2, $input_file3, $input_file4, $input_file5, $input_file6, $input_file7, $input_file8, $input_file9, $input_file10);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling ConvertDocumentApi->convertDocumentPngArrayToPdf: ', $e->getMessage(), PHP_EOL;
}
?>
To authorize our API call, we’ll need to provide a free API key in the $config snippet. Free API keys will allow up to 800 API calls per month with no commitment (our total will reset the following month once we reach it).