Created
April 18, 2018 19:14
-
-
Save hmemcpy/549ba897c8720a2b8def4b43309583a5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# Shrinks the PDF by compressing images to JPEG using highest quality | |
# Original code from http://www.alfredklomp.com/programming/shrinkpdf/ | |
# Modified with command taken from https://stackoverflow.com/questions/40849325/ghostscript-pdfwrite-specify-jpeg-quality | |
shrink () | |
{ | |
echo "Converting $IFILE > $OFILE" | |
gs \ | |
-sOutputFile="$2" \ | |
-q -dNOPAUSE -dBATCH -dSAFER \ | |
-sDEVICE=pdfwrite \ | |
-dPDFSETTINGS=/prepress \ | |
-c ".setpdfwrite << /ColorACSImageDict << /VSamples [ 1 1 1 1 ] /HSamples [ 1 1 1 1 ] /QFactor 0.08 /Blend 1 >> /ColorImageDownsampleType /Bicubic /ColorConversionStrategy /LeaveColorUnchanged >> setdistillerparams" \ | |
-f "$1" | |
} | |
check_smaller () | |
{ | |
# If $1 and $2 are regular files, we can compare file sizes to | |
# see if we succeeded in shrinking. If not, we copy $1 over $2: | |
if [ ! -f "$1" -o ! -f "$2" ]; then | |
return 0; | |
fi | |
ISIZE="$(echo $(wc -c "$1") | cut -f1 -d\ )" | |
OSIZE="$(echo $(wc -c "$2") | cut -f1 -d\ )" | |
if [ "$ISIZE" -lt "$OSIZE" ]; then | |
echo "Input smaller than output, doing straight copy" >&2 | |
cp "$1" "$2" | |
fi | |
} | |
usage () | |
{ | |
echo "Reduces PDF filesize by lossy recompressing with Ghostscript." | |
echo "Not guaranteed to succeed, but usually works." | |
echo " Usage: $1 infile" | |
} | |
IFILE="$1" | |
# Need an input file: | |
if [ -z "$IFILE" ]; then | |
usage "$0" | |
exit 1 | |
fi | |
# Output filename defaults to "-" (stdout) unless given: | |
if [ ! -z "$2" ]; then | |
OFILE="$2" | |
else | |
OFILE="${IFILE%.pdf}-fixed.pdf" | |
fi | |
shrink "$IFILE" "$OFILE" || exit $? | |
check_smaller "$IFILE" "$OFILE" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment