Last active
September 20, 2020 17:56
-
-
Save iiiw/da2cecd399dafa5e01d0aff156f5f9de to your computer and use it in GitHub Desktop.
Optimize pdf files for screen resolution.
This file contains 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
#!/usr/bin/env bash | |
# vim: ft=sh | |
set -o errexit | |
set -o pipefail | |
shopt -s nullglob | |
usage () { | |
echo "Usage: $0 " | |
echo "Optimize pdf files for screen resolution." | |
echo "Original pdf files are taken from the current directory." | |
echo "The resulting files are written to ./out-{TIMESTAMP}" | |
echo "The output directory contains a manifest of the processed files." | |
echo "Options:" | |
echo " -h Print this help" | |
exit 0 | |
} | |
case "$1" in | |
-h|--help) usage;; | |
esac | |
command -v gs >/dev/null 2>&1 \ | |
|| { echo "Please install ghostscript (https://www.ghostscript.com)." >&2; exit 1; } | |
# Ghostscript options | |
PDFRES="/ebook" # /ebook=150dpi, /screen=72dpi | |
PAPERSIZE="a4" # a4, letter ... | |
opts=("-sDEVICE=pdfwrite") | |
opts+=("-sPAPERSIZE=$PAPERSIZE") | |
opts+=("-dPDFSETTINGS=$PDFRES") | |
opts+=("-sColorConversionStrategy=Gray") | |
opts+=("-dProcessColorModel=/DeviceGray") | |
opts+=("-dCompatibilityLevel=1.4") | |
opts+=("-dNOPAUSE" "-dBATCH") | |
# Look for pdf files in the current working directory. | |
cwd="$(pwd)" | |
files=(*.pdf) | |
(( ${#files[@]} )) \ | |
|| { echo "No pdf files found in $cwd!" >&2; exit 1; } | |
# The processed files go into $CURRENT_WORKING_DIR/out_$TIMESTAMP. | |
ts="$(date +%s)" | |
od="out_$ts" | |
mkdir -p "$cwd/$od" \ | |
&& echo "▶ Created directory $cwd/$od ..." | |
for f in "${files[@]}"; do | |
eval "gs ${opts[*]} -sOutputFile=$cwd/$od/$f $f" | |
done | |
# Check success. | |
cd "$cwd/$od" | |
new_files=(*.pdf) | |
cd "$cwd" | |
miss_files=( $(printf '%s\n' "${files[@]}" "${new_files[@]}" "${new_files[@]}" \ | |
| sort | uniq -u) ) | |
if (( ${#miss_files[@]} )); then | |
echo "❌ Some files could not be written:" >&2 | |
printf '%s\n' "${miss_files[@]}" >&2 | |
fi | |
# The processed files are listed in manifest.txt. | |
printf '%s\n' "${new_files[@]}" > "$cwd/$od/manifest.txt" \ | |
&& echo -n "▶ ${#new_files[@]} file(s) processed." \ | |
&& echo " Please check ./$od/manifest.txt for details." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment