2

I have a PDF that has some blank pages inserted. These pages are the background colour (grey in this case). I would like to remove these pages using a bash script.

It has been suggested that we can to scan for text using e.g. pdftotext, but in my case this does not find text even on the non-blank pages.

2

There does not appear to be a utility to remove blank pages from PDFs, but we can create a histogram of colours using the convert command from imagemagick. Blank slides will only have one entry which can be detected with wc. Once we have a list of non-blank pages we can feed this into pdftk.

Note that imagemagick numbers pages starting from 0, so we need to adjust for this. We can use a low value in the -density flag improve performance (though too low seems to result in imagemagick segfaulting).

If we call the following script pdf_rm_blank.sh, running pdf_rm_blank.sh A will create A.rm.pdf from A.pdf

#!/bin/sh
IN="$1"
PAGES=$(pdfinfo $IN.pdf | grep ^Pages: | tr -dc '0-9')

non_blank() {
    for i in $(seq 1 $PAGES)
    do
        if [ $(convert -density 35 "$IN.pdf[$((i-1))]" -define histogram:unique-colors=true -format %c histogram:info:- | wc -l) -ne 1 ]
        then
            echo $i
            #echo $i 1>&2
        fi
        echo -n . 1>&2
    done | tee out.tmp
    echo 1>&2
}

set +x
pdftk $IN.pdf cat $(non_blank) output $IN.rm.pdf
  • I was just goin to suggest use print as pdf from any number of tools, then make sure to unselect blank pages. However this seems nicer. – djsmiley2k - CoW Sep 8 '17 at 10:50
2

Thank you for the code, gmatht. I have modified it to check for page coverage using GhostScript and delete pages with coverage less than a threshold (0.1%).

#!/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 "$filename.tmp"
    echo 1>&2
}

set +x
pdftk "${IN}" cat $(non_blank) output "${filename}.pdf"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.