Remove Blank Pages from PDF Files in PHP using FPDI Library

To remove blank pages from a PDF file in PHP, you can use the FPDF FPDI libraries. The FPDF the library allows you to create PDF documents, while the FPDI library extends FPDF to import existing PDF documents and manipulate them. Here’s a step-by-step guide to achieving this:

Step 1: Install the required libraries.
You can use Composer to install the necessary libraries. Create a composer.json file with the following content:

    "require": {
        "setasign/fpdf": "1.8.1",
        "setasign/fpdi": "2.3.0"

Run the following command in the terminal to install the libraries:

composer install

Step 2: Create a PHP script to remove blank pages.
Create a PHP file (e.g., remove_blank_pages.php) with the following code:

require 'vendor/autoload.php';

use setasign\Fpdi\Fpdi;

// Define the path to the original PDF file and the path to the modified PDF file
$originalPdfFile = 'path/to/original.pdf';
$modifiedPdfFile = 'path/to/modified.pdf';

// Create a new FPDI instance
$pdf = new Fpdi();

// Get the total number of pages in the original PDF file
$pageCount = $pdf->setSourceFile($originalPdfFile);
$totalPages = $pdf->getTemplateSize($pageCount);

// Loop through each page in the original PDF
for ($pageNumber = 1; $pageNumber <= $totalPages; $pageNumber++) {
    // Add the page to the new PDF

    // Import the page from the original PDF
    $templateId = $pdf->importPage($pageNumber);

    // Get the size of the imported page
    $size = $pdf->getTemplateSize($templateId);
    $width = $size['width'];
    $height = $size['height'];

    // If the page is not blank (i.e., it has content), then add it to the new PDF
    if ($width > 0 || $height > 0) {

// Output the modified PDF to a file
$pdf->Output($modifiedPdfFile, 'F');

echo "Blank pages removed and new PDF created successfully!";

Step 3: Run the PHP script.
Replace 'path/to/original.pdf' with the path to your original PDF file that you want to remove blank pages from. Replace 'path/to/modified.pdf' with the desired path and filename for the modified PDF file.

Save the PHP script and run it in your terminal or execute it in a web server environment. The script will process the original PDF file, remove blank pages, and save the modified PDF to the specified output file.

Note: The FPDI library may not work correctly with some PDF files that have complex structures or unusual encoding. In such cases, you may need to explore other PDF processing libraries or tools to achieve the desired results.

Always make sure to have a backup of your original PDF file before running any script that modifies it.