summarylogtreecommitdiffstats
path: root/pdf-remove-blank-pages.sh
blob: 2e917bf98d9df7b8146e6f82af18f6c64eaa4873 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#! /bin/bash

BEGIN=1
END=0
filename=""

while getopts b:f:e:h option
do
   case "${option}" in
      b) BEGIN=${OPTARG};;
      f) filename=${OPTARG};;
      e) END=${OPTARG};;
      h) echo "Usage: pdf-remove-blank-pages [-b <FIRST_PAGE>] [-e <LAST_PAGE>] -f <PDF-file>"
                 echo "       [FIRST_PAGE LAST_PAGE] = pages-interval where to remove blank pages ; default is 1-End"
                 echo "       pdf-remove-blank-pages -h : displays that help and exit"
                 exit;;
      *) echo "invalid parameter"
         echo " "
         echo "Usage: pdf-remove-blank-pages [-b <FIRST_PAGE>] [-e <LAST_PAGE>] -f <PDF-file>"
         echo "       [FIRST_PAGE LAST_PAGE] = pages-interval where to remove blank pages ; default is 1-End"
         echo "       pdf-remove-blank-pages -h : displays that help and exit"
         exit;;
   esac
done

if [ -z "$filename" ]; then  
  echo "-f <PDF-file> is missing ; aborted"
  exit 99
fi  

if [ $END == 0 ]; then   # apply default : last page of the pdf
  END=$(pdfinfo $filename | grep Pages | awk '{print $2}')
fi  

echo "BEGIN="$BEGIN " first page"
echo "END="$END " last page"
echo "filename="$filename

  # get non-blank ranges
  ranges="$(pdftotext -f $BEGIN -l $END "$filename" - | \
    "/usr/bin/non-blank-page-ranges.py")"

  if [ -z "$ranges" ]; then
    echo "no non-blank pages found in $filename" >&2
  fi

  # rename pdf
  if [ -e "${filename}.old.pdf" ]; then
    echo "file exists: ${filename}.old.pdf" >&2
  fi

  mv -n "$filename" "${filename}.old.pdf"

  if [ -e "$filename" -o ! -e "${filename}.old.pdf" ]; then
    echo "couldn't rename file $filename" >&2
  fi

  # create new pdf with non-blank pages only
  pdftk "${filename}.old.pdf" cat $ranges output "$filename"