Merging and Splitting PDF Files in PHP Using FPDI and FPDF

Merging and Splitting PDF Files in PHP Using FPDI and FPDF

Introduction

Merging and splitting PDFs is essential for document management, report generation, and automation. Whether you need to combine multiple PDFs into one or extract specific pages, PHP makes this possible with FPDI and FPDF.

With this guide, you will learn how to:

Merge multiple PDF files into a single document
Split a PDF and extract specific pages
Save, download, or email processed PDFs
Handle large PDFs efficiently

By the end, you’ll have a fully functional PHP solution for merging and splitting PDFs dynamically. 🚀

1. Installing FPDI and FPDF in PHP

To handle PDFs in PHP, we need FPDF (to create PDFs) and FPDI (to manipulate existing PDFs).

Install via Composer (Recommended)

composer require setasign/fpdf
composer require setasign/fpdi

Include them in your PHP script:

require 'vendor/autoload.php';

use setasign\Fpdi\Fpdi;
use setasign\Fpdi\PdfReader;

Now, FPDI is ready for use!

2. Merging Multiple PDFs into One

To combine multiple PDF files into one, use FPDI to import pages and FPDF to generate the final document.

Example: Merge Two PDFs into One

require 'vendor/autoload.php';

use setasign\Fpdi\Fpdi;

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

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

$pdf->Output('F', 'merged.pdf');
echo "PDFs merged successfully!";

Explanation:

setSourceFile($file) – Loads a PDF file.
importPage($i) – Extracts a page.
useTemplate($tplIdx) – Places the extracted page inside the new PDF.
Output('F', 'merged.pdf') – Saves the merged PDF.

🔹 You can merge multiple PDFs by adding them to $files.

3. Splitting a PDF (Extracting Specific Pages)

To extract specific pages from a PDF, use FPDI to import only the needed pages.

Example: Extract Pages 1 and 3 from a PDF

require 'vendor/autoload.php';

use setasign\Fpdi\Fpdi;

$pdf = new Fpdi();
$file = 'document.pdf';
$pagesToExtract = [1, 3];

$pdf->setSourceFile($file);

foreach ($pagesToExtract as $page) {
    $pdf->AddPage();
    $tplIdx = $pdf->importPage($page);
    $pdf->useTemplate($tplIdx);
}

$pdf->Output('F', 'extracted_pages.pdf');
echo "Pages extracted successfully!";

Explanation:

Extracts only pages 1 and 3 from document.pdf.
Creates a new PDF (extracted_pages.pdf) with only the selected pages.

🔹 Modify $pagesToExtract to extract different pages.

4. Splitting a PDF into Separate Files (One Page per File)

For cases where you need to split a multi-page PDF into individual files, process each page separately.

Example: Split Each Page into a Separate PDF File

require 'vendor/autoload.php';

use setasign\Fpdi\Fpdi;

$file = 'document.pdf';
$pdf = new Fpdi();
$pageCount = $pdf->setSourceFile($file);

for ($i = 1; $i <= $pageCount; $i++) {
    $newPdf = new Fpdi();
    $newPdf->AddPage();
    $tplIdx = $newPdf->importPage($i);
    $newPdf->useTemplate($tplIdx);

    $newFileName = "split_page_$i.pdf";
    $newPdf->Output('F', $newFileName);
    echo "Created: $newFileName <br>";
}

Explanation:

Processes each page separately and saves it as split_page_X.pdf.
Handles large PDFs by breaking them into smaller files.

5. Merging PDFs with Dynamic Content (Adding Headers or Watermarks)

If you need to add a header, footer, or watermark while merging PDFs, modify the newly created pages before saving them.

Example: Add Header to Merged PDFs

class CustomPDF extends Fpdi {
    function Header() {
        $this->SetFont('Arial', 'B', 12);
        $this->Cell(0, 10, 'Confidential Document', 0, 1, 'C');
    }
}

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

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

$pdf->Output('F', 'merged_with_header.pdf');
echo "PDFs merged with a header!";

This adds "Confidential Document" as a header on every page.

6. Saving and Downloading Merged/Split PDFs

After processing PDFs, you may need to:

Save the PDF on the Server

$pdf->Output('F', 'output.pdf'); // Saves file on the server

Force Download the PDF

$pdf->Output('D', 'download.pdf'); // Forces browser to download

Email the Merged PDF as an Attachment

use PHPMailer\PHPMailer\PHPMailer;

$mail = new PHPMailer();
$mail->addAttachment('output.pdf');
$mail->send();

Automate merging, saving, and emailing PDF files dynamically.

7. Handling Large PDF Files Efficiently

When merging or splitting large PDFs, follow these optimizations:

Increase PHP Memory Limit

ini_set('memory_limit', '256M');

Use File Streaming (Avoid Loading Entire PDF at Once)

$pdf->setSourceFile(fopen('large.pdf', 'rb'));

Optimize Output File Size

Use compression while generating PDFs:

$pdf->SetCompression(true);

Split Large PDFs Instead of Processing Everything at Once

Best Practices for Merging & Splitting PDFs in PHP

Use FPDI for existing PDFs, FPDF for new ones.
Handle large PDFs efficiently with memory management.
Extract only needed pages to improve performance.
Use custom headers/footers for branding and security.
Automate merging/splitting for bulk PDF processing.

Conclusion

With FPDI and FPDF, you can easily merge, split, and modify PDFs dynamically in PHP.

Merge multiple PDFs into one
Extract specific pages from a PDF
Split PDFs into individual files
Add headers, footers, or watermarks while merging PDFs

By implementing these best practices, you can optimize document management and build a powerful PDF processing system in PHP. 🚀

Leave a Reply