From f71e05bc2e7d46107527e2f820bf2a1cf559ce9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C4=83t=C4=83lin=20Mari=C8=99?= Date: Sat, 23 Dec 2023 17:30:41 +0200 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Add=20`optimize-pdfs`=20shell=20fun?= =?UTF-8?q?ction=20for=20optimizing=20PDF=20files?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/shell/bash_functions | 72 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/src/shell/bash_functions b/src/shell/bash_functions index 1f7e786f1..1aa30c807 100755 --- a/src/shell/bash_functions +++ b/src/shell/bash_functions @@ -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