ItSolutionStuff.com

PHP - How to Remove Blank Pages from PDF File?

By Hardik Savani • May 14, 2024
PHP Ubuntu

This post will give you an example of how to remove blank pages from pdf in php. In this article, we will implement a pdftk to remove blank pages. this example will help you php delete blank page in pdf. you'll learn to remove all blank pages in pdf php.

A few days ago, I was looking for how to delete all blank pages from pdf using php. Then I found we can use pdfk and create shell script then we can call that shall script into php file. you can use this example with php, laravel, Codeigniter, CakePHP etc. so if you also need to remove all blank pages from pdf file then follow bellow step:

Install PDFTK:

You need to install pdftk in your system by following command:

sudo apt install pdftk

Create Shell Script:

Here, we will create simple shell script and use this script in php file:

pdftksc.sh

#!/bin/sh

IN="$1"

filename=$(basename "${IN}")

filename="${filename%.*}"

PAGES=$(pdfinfo "$IN" | grep ^Pages: | tr -dc '0-9')

non_blank() {

for i in $(seq 1 $PAGES)

do

PERCENT=$(gs -o - -dFirstPage=${i} -dLastPage=${i} -sDEVICE=inkcov "$IN" | grep CMYK | nawk 'BEGIN { sum=0; } {sum += $1 + $2 + $3 + $4;} END { printf "%.5f\n", sum } ')

if [ $(echo "$PERCENT > 0.001" | bc) -eq 1 ]

then

echo $i

#echo $i 1>&2

fi

echo -n . 1>&2

done | tee "${DIR}/$filename.tmp"

echo 1>&2

}

set +x

pdftk "${IN}" cat $(non_blank) output "${filename}_copy.pdf"

Now, you can use this shell script with command as like bellow:

bash pdftksc.sh filename.pdf

Create PHP File:

Here, we will create index.php file and use that script:

index.php

<?php

$fileName = 'itsolutionstuff_pdf_blank.pdf';

$output = shell_exec('bash pdftksc.sh '. $fileName);

print_r($output);

You will find a result as like bellow:

Original File:
Generated File:

I hope it can help you...

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Whitelist/Allow IP Address in Apache Ubuntu?

Read Now →

How to Install Laravel in Ubuntu Server?

Read Now →

How to Set Up Password Authentication with Apache in Ubuntu?

Read Now →

How to Install Apache PHP MySQL and Phpmyadmin on Ubuntu?

Read Now →

How to Change PHP Version in Ubuntu Server?

Read Now →

How to Install PHP in Ubuntu Server?

Read Now →

How to Get Month Name from Date in PHP?

Read Now →

How to Subtract Minutes from DateTime in PHP?

Read Now →

Laravel Livewire Load More OnScroll Example

Read Now →

How to Enable Rewrite Mode for Apache in Ubuntu?

Read Now →