Skip to content

Commit

Permalink
✨ Add optimize-pdfs shell function for optimizing PDF files
Browse files Browse the repository at this point in the history
  • Loading branch information
alrra committed Dec 23, 2023
1 parent 6360e76 commit cf40043
Showing 1 changed file with 72 additions and 0 deletions.
72 changes: 72 additions & 0 deletions src/shell/bash_functions
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,78 @@ h() {

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

# Optimize PDF files.
#
# Usage examples:
#
# optimize-pdfs path/to/some/directory path/to/some/file ...

optimize-pdfs() (

# Check if the pdfcpu command-line tool is installed.

if ! command -v "pdfcpu" &> /dev/null; then
printf "\n%s\n\n" "pdfcpu command-line tool is not installed!"
exit
fi

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

get-file-size() (
printf "%s" "$(wc -c < "$1")"
)

optimize-pdf() (
filePath="$(dirname "${1%/}")"
fileName="_$(printf "%s" "$(basename "$1")" | tr '[:upper:]' '[:lower:]')"

optimizedFilePath="$filePath/$fileName"

printf "* %s\n" "$1"

pdfcpu optimize "$1" "$optimizedFilePath" &> /dev/null

# If something went wrong (i.e. pdfcpu didn't create
# the optimized file or exited with a non-zero status)
# or the size of the optimized file is bigger than the
# original file, keep the original file.

if [ ! -f "$optimizedFilePath" ]; then
return
fi

# shellcheck disable=SC2181
if [ $? -ne 0 ] || \
[ "$(get-file-size "$1")" -le "$(get-file-size "$optimizedFilePath")" ];
then
rm -rf "$optimizedFilePath"
return
fi

# Otherwise, replace the original file with the optimized one.

mv -f "$optimizedFilePath" "$1" 1> /dev/null
)

# ┌─ Default to the current directory.
for filePath in "${@:-.}"; do
if [ -d "$filePath" ]; then
find "${filePath%/}" \
-depth 1 \
-name \*.pdf \
-print \
-type f \
| while read -r file; do
optimize-pdf "$file"
done
elif [ -f "$filePath" ]; then
optimize-pdf "$filePath"
fi
done
)

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

# Rename media files.
#
# Rename the specified files so the filename is the file created date
Expand Down

0 comments on commit cf40043

Please sign in to comment.