Skip to content

Instantly share code, notes, and snippets.

@jhidding
Created May 9, 2018 08:26
Show Gist options
  • Save jhidding/0b89f4fce875398bb685f7b1b329a7d4 to your computer and use it in GitHub Desktop.
Save jhidding/0b89f4fce875398bb685f7b1b329a7d4 to your computer and use it in GitHub Desktop.
downsample a PDF file using ghostscript
#!/bin/bash
# Copyright 2018 Johan Hidding
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
usage() {
exec_name=$(basename "$0")
exec_spac=$(echo ${exec_name} | sed -e 's/./ /g')
echo "Downsample PDF file."
echo "usage: ${exec_name} [-h|--help]"
echo " | ${exec_name} <input-file>"
echo " ${exec_spac} [-dpi|--dpi <dpi>] [-q|--quiet]"
echo " ${exec_spac} [-o|--output] <output-file>"
echo
echo "-dpi|--dpi <dpi> Defaults to 150."
echo "-o|--output <output-file> Defaults to the <input-file> with a '-downsampled'"
echo " suffix, in the same folder as the input PDF."
echo "-q|--quiet Suppress output of ghostscript (-dQUIET)."
echo "-h|--help Print this help."
exit
}
if [[ $# -lt 1 || "$1" =~ -h|--help ]]; then
usage
fi
input_file="$1"
if [[ ! -f "$input_file" ]]; then
echo "File not found: ${input_file}"
usage
fi
shift
dpi=150
quiet=""
output_file="$(dirname "${input_file}")/$(basename "${input_file}" .pdf)-downsampled.pdf"
while [[ $# -gt 0 ]]; do
key="$1"
case ${key} in
-dpi|--dpi)
dpi="$2"
shift; shift
;;
-q|--quiet)
quiet="-dQUIET"
shift
;;
-o|--output)
output_file="$2"
shift; shift
;;
*)
echo "unexpected argument: ${key}"
exit
;;
esac
done
echo "Downsampling ${input_file} -> ${output_file} ... this may take a while"
stat --printf="%n: %s bytes\n" ${input_file}
gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 \
-dPDFSETTINGS=/screen -dNOPAUSE ${quiet} -dBATCH \
-dEmbedAllFonts=true \
-dSubsetFonts=true \
-dColorImageDownsampleType=/Bicubic \
-dColorImageResolution=${dpi} \
-dGrayImageDownsampleType=/Bicubic \
-dGrayImageResolution=${dpi} \
-dMonoImageResolution=${dpi} \
-sOutputFile="${output_file}" "${input_file}"
stat --printf="%n: %s bytes\n" "${output_file}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment