How to Merge PDFs in PHP

Cloudmersive
2 min readMay 8, 2024

It’s easy to merge two PDF documents together using a low-code API solution.

All we need to do is copy from PHP code examples provided below, and we’ll be able to merge two or more PDFs together in a quick, efficient operation.

First, let’s install the PHP client. We can install with Composer by executing the below command from our command line:

composer require cloudmersive/cloudmersive_document_convert_api_client

Next, let’s quickly turn our attention to authorization. We’ll need a free Cloudmersive API key to authorize up to 800 API calls per month with zero commitments (this total will reset the following month once we reach our limit).

With our API key ready, we can copy the below code to call the function, and we can paste our key in the $config snippet:

<?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\MergeDocumentApi(


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->mergeDocumentPdfMulti($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 MergeDocumentApi->mergeDocumentPdfMulti: ', $e->getMessage(), PHP_EOL;
}
?>

We can include the file paths for each of the PDFs we’re merging in the $input_file variables.

That’s all the code we’ll need — now we can easily merge PDFs in PHP using a low-code API.

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.