Thursday, September 27, 2012

Adjust pdf quality with Ghostscript and Bash

Sometimes pdf files are too big to attach them to an email. Here is a simple bash script witch uses Ghostscript to adjust a pdf file quality (and size) to three different levels: low, mid and high.
To see the script usage just type ./pdf-quality.sh on the terminal. Don't forget to give it execution permissions: chmod u+x  pdf-quality.sh

 

Code

.pdf-quality.sh.tmp
  1 #/bin/bash
  2 
  3 
  4 # function to print proper usage
  5 function usage() {
  6   echo "Usage: pdf-quality.sh <quality> <input_file>"
  7   echo "Where <quality> is low, mid or high and <input_file> the pdf file to be adjusted."
  8 }
  9 
 10 
 11 # check parameter number
 12 if [[ $# != 2 ]]; then usage; exit 1; fi
 13 
 14 # set variables
 15 QUALITY="$1"
 16 INFILE="$2"
 17 OUTFILE="$(echo "$2" | sed 's/.pdf//')-$QUALITY.pdf"
 18 
 19 # perform action depending on the given parameter
 20 case "$QUALITY" in
 21   "low")
 22     gs -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/screen -
                                      sOutputFile="$OUTFILE" "$INFILE";;
 23   "mid")
 24     gs -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook -
                                      sOutputFile="$OUTFILE" "$INFILE";;
 25   "high")
 26     gs -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/printer -
                                      sOutputFile="$OUTFILE" "$INFILE";;
 27   *)  echo "$1 is not a valid option."
 28     usage
 29     exit 1;;
 30 esac
 31 
 32 echo -e "\nall done!"
 33 exit 0

1 comment:

  1. Good and informative post, working with codes is real trouble single mistake can take hours to rectify. Thank you for sharing it and keep posting

    ReplyDelete