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 c6e66dd commit 3fcee1c
Showing 1 changed file with 67 additions and 1 deletion.
68 changes: 67 additions & 1 deletion src/shell/bash_functions
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,72 @@ 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" "$(ls -l "$1" | awk '{print $5}')"
)

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 exited with a non-zero
# status) or the optimization increased the size of the file,
# removed the optimized file.

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 f; do
optimize-pdf "$f"
done
elif [ -f "$filePath" ]; then
optimize-pdf "$f"
fi
done
)

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

# Rename media files.
#
# Rename the specified files so the filename is the file created date
Expand Down Expand Up @@ -196,7 +262,7 @@ resize-image() {

# Check if ImageMagick's convert command-line tool is installed.

if ! command -v "convert" $> /dev/null; then
if ! command -v "convert" &> /dev/null; then
printf "ImageMagick's 'convert' command-line tool is not installed!"
exit
fi
Expand Down

0 comments on commit 3fcee1c

Please sign in to comment.