Merge PDF PHP

May 8, 2025 12 min read

Merging PDF files is a common requirement in PHP applications, especially when dealing with document management, reporting, or archiving. Developers often need to combine multiple PDF documents into a single, cohesive file. This process can range from simple concatenation to more complex operations involving page reordering or selective inclusion of pages. However, merging PDFs programmatically in PHP can present several challenges, including memory management, handling different PDF versions, and dealing with password-protected files.

Simplify PDF Merging with BreezePDF

Merge PDFs effortlessly and securely without server load – try BreezePDF today!

Create Fillable PDF for Free →

Traditional methods often involve using PHP libraries that can be resource-intensive and complex to implement. These libraries might also struggle with large PDF files or documents with intricate layouts. Fortunately, BreezePDF offers a streamlined and robust solution for merging PDFs directly within your PHP applications. With BreezePDF, you can efficiently and reliably merge PDF files without the common pitfalls of traditional server-side methods.

Why Merge PDFs in PHP?

The ability to merge PDFs is crucial in numerous PHP application scenarios. Consider the case of generating invoices; you might need to combine several individual invoices for different services or products into a single, comprehensive invoice for a client. This simplifies record-keeping and provides a consolidated view of all transactions. In a similar vein, PDF merging is essential when generating reports from various data sources, where individual reports need to be combined into a unified document for analysis and distribution.

Preparing document packages is another common use case. For instance, when submitting a proposal, you might need to combine a cover letter, project description, budget details, and team member resumes into a single PDF. By merging these separate documents into a single file, you ensure that all necessary information is readily available and easily accessible. This functionality streamlines workflows and enhances the user experience.

Prerequisites

Before diving into the code, there are a few prerequisites to consider. Ensure your PHP environment meets the minimum version requirements, typically PHP 5.6 or higher, with support for PHP 7+ and 8+ for optimal performance and compatibility. For managing project dependencies, you will need Composer, a popular PHP dependency management tool. Composer simplifies the installation and updating of external libraries, ensuring your project remains organized and maintainable.

A solid grasp of basic PHP programming is essential for understanding and implementing the code examples provided. Familiarity with object-oriented programming (OOP) concepts will be beneficial, especially when working with PDF libraries. Lastly, if you choose to use libraries like FPDI, ensure that the Zlib extension is enabled in your PHP environment. The Zlib extension provides the necessary functionality for decompressing PDF content, enabling you to read and manipulate PDF files effectively.

Traditional Methods for Merging PDFs in PHP

Several traditional PHP libraries facilitate PDF merging, each with its own set of features and complexities. Understanding these methods can help you appreciate the simplicity and power of modern alternatives like BreezePDF. One popular approach involves using the combination of FPDI and FPDF libraries. FPDI (Free PDF Document Importer) allows you to import existing PDF pages into an FPDF document. FPDF (Free PDF) is a PHP class which allows to generate PDF files with PHP.

To get started with FPDI and FPDF, you'll need to install them via Composer. Open your terminal and navigate to your project directory. Use the following Composer command: composer require setasign/fpdf:1.8.* setasign/fpdi:^2.0. This command will download and install the necessary files in your project's vendor directory. To create and generate a basic PDF, you will use FPDF. FPDI will allow you to import PDFs to merge.

Code Examples using FPDI and FPDF

Here are some code examples illustrating how to merge PDFs using FPDI and FPDF. These examples demonstrate the basic principles and highlight potential error handling techniques.

// Example of merging two PDFs
require_once('vendor/autoload.php');

use setasign\Fpdi\Fpdi;

$pdf = new Fpdi();

$files = ['file1.pdf', 'file2.pdf'];

foreach ($files as $file) {
    $pageCount = $pdf->setSourceFile($file);
    for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
        $templateId = $pdf->importPage($pageNo);
        $pdf->AddPage();
        $pdf->useTemplate($templateId);
    }
}

$pdf->Output('merged.pdf', 'D');
// Example of merging multiple PDFs with error handling
require_once('vendor/autoload.php');

use setasign\Fpdi\Fpdi;

$pdf = new Fpdi();
$files = ['file1.pdf', 'file2.pdf', 'file3.pdf'];

foreach ($files as $file) {
    try {
        $pageCount = $pdf->setSourceFile($file);
        for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
            $templateId = $pdf->importPage($pageNo);
            $pdf->AddPage();
            $pdf->useTemplate($templateId, 0, 0, null, null, true);
        }
    } catch (\Exception $e) {
        echo "Error processing file: " . $file . " - " . $e->getMessage() . "\n";
    }
}

$pdf->Output('merged.pdf', 'D');

These examples iterate through an array of PDF file paths, importing each page from each file into a new merged PDF. Error handling is included to catch any exceptions that may occur during file processing, such as file readability issues or PDF parsing errors. Remember that these libraries can be resource-intensive, especially with large files.

TCPDF and TCPDI

Another set of libraries for PDF manipulation in PHP includes TCPDF and TCPDI. TCPDF is a widely used open-source library for generating PDF documents, offering a broad range of features, including support for various font formats, image handling, and document encryption. TCPDI, standing for TCPDF Document Importer, is a companion library that allows you to import existing PDF pages into a TCPDF document, similar to FPDI's functionality with FPDF.

These libraries are another viable solution for generating and merging PDFs. By using TCPDF class, you can merge documents by iterating through them and adding the source document.

jurosh/php-pdf-merge

The jurosh/php-pdf-merge library offers a convenient way to merge PDF files, including the ability to handle portrait and landscape orientations effectively. This library simplifies the merging process, providing a more intuitive interface compared to some of the lower-level libraries. This package makes it easier to merge PDFs that have portrait and landscape pages.

To install this library, use Composer: composer require jurosh/pdf-merge. After installation, you can use the library to merge PDFs with just a few lines of code. For instance, you can specify an array of PDF file paths and then call the merge() method to combine them into a single PDF file. For detailed usage examples and advanced features, refer to the library's documentation on Packagist.

karriere/pdf-merge

The karriere/pdf-merge library is a wrapper for the TCPDF class, providing a more streamlined and user-friendly interface for merging PDF files. This library simplifies common tasks such as setting headers and footers, making it easier to customize the appearance of the merged document. This wrapper makes the usage of TCPDF much more pleasant.

To install this library, use Composer: composer require karriere/pdf-merge. Usage example:

$pdf = new PDFMerger();
$pdf->addPDF('sample1.pdf', 'all')
    ->addPDF('sample2.pdf', '1,3,4')
    ->merge('browser', 'sample-out.pdf');

Memory Management for Large PDF Merges

When merging large PDF files, memory exhaustion can become a significant issue, especially in PHP environments with limited resources. PHP scripts, by default, have a memory limit, and processing large files can easily exceed this limit, leading to script termination. To address this, you can increase the PHP memory limit by modifying the php.ini file or using the ini_set() function within your script: ini_set('memory_limit', '256M');. Adjust the memory limit based on the size and complexity of the PDFs you are merging.

Setting an execution time limit is another crucial step. PHP scripts have a maximum execution time, and merging large PDFs might take longer than this limit, causing the script to time out. You can adjust the execution time limit using the set_time_limit() function: set_time_limit(300);. Additionally, releasing resources as soon as they are no longer needed can help reduce memory consumption. Use the unset() function to free up memory and call gc_collect_cycles() to trigger the garbage collector: unset($pdf); gc_collect_cycles();. This practice can prevent memory leaks and improve overall performance.

Limitations of Traditional PHP PDF Merging Libraries

While traditional PHP PDF merging libraries like FPDI and TCPDF are valuable tools, they come with certain limitations. These libraries can impose a significant load on the server, particularly when dealing with large PDF files or high volumes of merge requests. This increased server load can impact performance and potentially lead to slowdowns or crashes. Furthermore, memory constraints can be a persistent issue, as these libraries often require substantial memory to process PDF files, especially those with complex layouts or embedded images.

Handling password-protected PDFs can also pose challenges, as many libraries may not natively support decryption or require additional configuration to handle encrypted files. Dealing with complex layouts and dynamic content can further complicate matters, as these libraries may struggle to accurately render or merge documents with intricate formatting or interactive elements. Finally, complications can arise when dealing with various document formats, as these libraries are primarily designed for PDF files and may not seamlessly handle other file types.

Introducing BreezePDF: A Modern Solution

BreezePDF offers a modern solution to overcome the limitations of traditional PHP PDF merging libraries. BreezePDF operates as a cloud-based API, providing a scalable and reliable service for merging PDFs without burdening your server resources. By leveraging the cloud, BreezePDF eliminates the need for local installations and reduces the risk of memory exhaustion or server overload. This ensures a consistent and high-performing experience, regardless of the size or complexity of the PDF files.

Using BreezePDF offers several key benefits. First, scalability and reliability are significantly enhanced. Second, BreezePDF reduces server load. Third, BreezePDF supports complex PDFs and large files. Fourth, the service handles password-protected PDFs. Finally, BreezePDF seamlessly integrates into PHP applications.

How to Merge PDFs with BreezePDF in PHP (with Code Examples)

Integrating BreezePDF's API into your PHP application is straightforward. Here's a step-by-step guide with code examples to illustrate the process. First, you'll need to sign up for a BreezePDF account and obtain your API key. Next, prepare an array containing the URLs or file paths of the PDF documents you want to merge. Then, send a merge request to the BreezePDF API endpoint, including your API key and the array of PDF files.

Here's an example PHP code snippet for sending a merge request to BreezePDF:

$apiKey = 'YOUR_API_KEY';
$pdfUrls = [
    'https://example.com/document1.pdf',
    'https://example.com/document2.pdf',
    'https://example.com/document3.pdf'
];

$data = [
    'api_key' => $apiKey,
    'files' => $pdfUrls
];

$options = [
    'http' => [
        'method'  => 'POST',
        'content' => json_encode($data),
        'header'  => "Content-Type: application/json\r\n"
                   . "Accept: application/json\r\n"
    ]
];

$context  = stream_context_create($options);
$result = file_get_contents('https://breezepdf.com/api/merge', false, $context);
$response = json_decode($result);

if ($response && $response->success) {
    $mergedPdfUrl = $response->merged_pdf_url;
    echo 'Merged PDF URL: ' . $mergedPdfUrl;
} else {
    echo 'Error: ' . $response->error;
}

This code sends a POST request to the BreezePDF API with the API key and an array of PDF file URLs. Upon a successful request, the API returns a URL for the merged PDF, which you can then use to download or embed the document. The API also provides customization options, such as specifying page ranges or the order in which the PDFs should be merged, making it highly adaptable to various use cases. BreezePDF also supports asynchronous processing. BreezePDF will notify you when the PDF is complete.

Advanced BreezePDF Features

Beyond basic PDF merging, BreezePDF offers a range of advanced features to enhance your document management capabilities. These include PDF portfolio creation, allowing you to combine multiple files into a single PDF container, and watermarking, which lets you add custom text or images to your PDFs for branding or security purposes. Compression is another valuable feature, enabling you to reduce the file size of your PDFs without sacrificing quality, making them easier to share and store.

BreezePDF also provides options for adding security and password protection to your PDFs, ensuring that sensitive information remains confidential. Annotation and form field support further expand the functionality, allowing you to add comments, highlights, and interactive form elements to your documents. By leveraging these advanced features, you can create highly customized and professional-looking PDFs that meet your specific needs.

Choosing the Right Approach: When to Use Which Method

Selecting the most appropriate method for merging PDFs in PHP depends on the specific requirements of your project. For simple, low-volume merging tasks, libraries like FPDI/FPDF might suffice. These libraries are suitable for basic concatenation and offer a degree of control over the merging process. However, they can be resource-intensive and may struggle with large files or complex layouts.

For scalable, reliable, and feature-rich merging, especially with large or complex files, BreezePDF is the preferred choice. BreezePDF's cloud-based API eliminates the limitations of traditional libraries, providing a seamless and efficient solution for merging PDFs in modern PHP applications. By offloading the merging process to the cloud, you can free up server resources, ensure consistent performance, and handle password-protected PDFs with ease.

Conclusion

Merging PDFs in PHP can be achieved through various methods, each with its own trade-offs. Traditional libraries like FPDI and TCPDF offer a local, code-driven approach, while BreezePDF provides a modern, cloud-based solution. Evaluating your project's specific needs, including scalability, file size, complexity, and security requirements, will help you determine the best approach.

For modern PHP applications that demand reliability, scalability, and advanced features, BreezePDF offers a compelling solution. Explore BreezePDF today and discover a seamless way to merge PDFs in your PHP projects!