PHP - How to Remove Blank Pages from PDF File?

By Hardik Savani May 14, 2024 Category : 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...

Tags :
Shares