Monday, March 21, 2011

Reduce pdf file size using gs

#!/bin/bash
# From http://scriptdemo.blogspot.com
# to reduce pdf file size using gs with different optimization level
# Usage:
# pdfsmaller.sh in.pdf out.pdf [opt]
# option:
#            screen    (72dpi)
#            ebook     (150dpi)
#            printer    (300dpi)
#            prepress (color preserving, 300dpi)
# e.g.,
#            pdfsmaller.sh Big.pdf smaller.pdf ebook # save output to smaller.pdf
# or        pdfsmaller.sh Big.pdf ebook                  # overwrite original Big.pdf
# ref: http://milan.kupcevic.net/ghostscript-ps-pdf

isOverWrite=0
if [ $# -eq 1 ]; then
   inFile=$1
   outFile=smaller_$1
   opt="prepress"
   isOverWrite=1
elif [ $# -eq 2 ]; then
   inFile=$1
   nf=`echo $2 | awk -F. '{print NF}'`
   if [ ${nf} -eq 2 ]; then
      outFile=$2
      opt="prepress"
   else
      outFile=smaller_$1
      opt=$2
      isOverWrite=1
   fi
elif [ $# -eq 3 ]; then
   inFile=$1
   outFile=$2
   opt=$3
else
   sed -n '2,12p' pdfsmaller.sh
   exit
fi
if [ ! -e "${inFile}" ]; then
   echo "${inFile} not exist"
   echo "gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/${opt} -dNOPAUSE \
                  -dQUIET -dBATCH -sOutputFile=\"${outFile}\" \"${inFile}\""
   exit
else
   eval "gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/${opt} -dNOPAUSE  \
                 -dQUIET -dBATCH -sOutputFile=\"${outFile}\" \"${inFile}\""
fi
[ ${isOverWrite} -eq 1 ] && mv "${outFile}" "${inFile}"

No comments:

ShowCalendar