Skip to content

Instantly share code, notes, and snippets.

@tmhpfnr
Created March 21, 2015 23:12
Show Gist options
  • Save tmhpfnr/3b3f7f5e65570e8aef7a to your computer and use it in GitHub Desktop.
Save tmhpfnr/3b3f7f5e65570e8aef7a to your computer and use it in GitHub Desktop.
Shrink PDF file size with simple postscript conversion
#!/bin/bash
LC_NUMERIC=C LC_COLLATE=C
start_time=`date +%s`
err ()
{
echo $1
exit $code
}
is_pdf()
{
file=$1
if [ $(head -c 4 "$file") = "%PDF" ]; then
return 1
fi
return 0
}
nice_size()
{
file=$1
ls -lah $file | awk -F " " {'print $5'}
}
display_info()
{
taken="$(expr `date +%s` - $start_time)"
((sec=taken%60, taken/=60, min=taken%60, hrs=taken/60))
timestamp=$(printf "%02d:%02d:%02d" $hrs $min $sec)
echo "$1 t+$timestamp"
}
esacpe_fname()
{
echo $(printf '%q' "$1")
}
orgfile=$2
if is_pdf "$orgfile"; then
err "Not a pdf $orgfile"
fi
newfile="$orgfile.min"
psfile="$orgfile.ps"
pdf2ps "$orgfile" "$psfile"
ps2pdf "$psfile" "$newfile"
echo "Conversion done"
if is_pdf "$newfile"; then
err "Invalid new pdf"
fi
orgsize="$(echo $(wc -c "$orgfile") | cut -f1 -d\ )"
newsize="$(echo $(wc -c "$newfile") | cut -f1 -d\ )"
if [ "$orgsize" -lt "$newsize" ]; then
# original size lower new size
# remove temp file
rm "$newfile"
# rm postscript file
rm "$psfile"
display_info "Clean up"
err "Failed: New file bigger original"
else
# remove original
mv "$orgfile" "org.$orgfile"
# rename temp file
mv "$newfile" "$orgfile"
# rm postscript file
rm "$psfile"
reduced=$(printf %.2f $(echo "(1-$newsize/$orgsize)*100" | bc -l))
display_info "Successfully shrinked about $reduced%"
exit 0
fi
# TODO
#http://www.cyberciti.biz/tips/handling-filenames-with-spaces-in-bash.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment