Skip to content

Instantly share code, notes, and snippets.

@sandipb
Last active April 20, 2025 15:23
Show Gist options
  • Save sandipb/c548d6406f3b1150df8f5a06f0fd5474 to your computer and use it in GitHub Desktop.
Save sandipb/c548d6406f3b1150df8f5a06f0fd5474 to your computer and use it in GitHub Desktop.
Script to decrypt PDFs using qpdf. Will ask for password only if needed.
#!/bin/bash
set -e -o pipefail
usage() {
cat <<HELP
USAGE: $0 PDF_FILE [OUTPUT_DIR|OUTPUT_FILE]
Decrypts given pdf file usingh qpdf by prompting for a password.
Examples:
- $0 /path/to/example.pdf
Will create /path/to/example_decrypted.pdf
- $0 /path/to/example.pdf output.pdf
Will create output.pdf
- $0 /path/to/example.pdf /output_dir/
Will create /output_dir/example_decrypted.pdf
- $0 /path/to/example.pdf /output_dir/output.pdf
Will create /output_dir/output.pdf
Password can be provided using the PDF_PASSWORD environment variable.
HELP
}
if [[ $# -eq 0 ]];then
usage
exit 0
fi
PATH=$PATH:/opt/homebrew/bin
PDF="`realpath \"$1\"`"
PDF_NAME="`basename "$PDF"`"
OUT_NAME="${PDF_NAME/.PDF/.pdf}"
OUT_NAME="${OUT_NAME/.pdf/_decrypted.pdf}"
PDF_DIR="$(cd "$(dirname "$1")" && pwd)"
OUT_DIR="$PDF_DIR"
if [[ -n "$2" ]];then
if [[ -d "$2" ]];then
OUT_DIR="$(cd "$2" && pwd)"
elif [[ -d `dirname "$2"` ]];then
OUT_NAME="$(basename "$2")"
OUT_DIR="$(cd `dirname "$2"` && pwd)"
else
echo "Bad output \"$2\""
exit 1
fi
fi
echo "Decrypting '${PDF_DIR}/${PDF_NAME}' => '${OUT_DIR}/${OUT_NAME}'"
OPTIONS=""
if qpdf --requires-password "${PDF_DIR}/${PDF_NAME}";then
if [[ -z $PDF_PASSWORD ]];then
read -s -p "Password: " PASS
echo
PDF_PASSWORD=$PASS
fi
OPTIONS="--verbose --decrypt --password=$PDF_PASSWORD"
fi
# echo qpdf "${PDF_DIR}/${PDF_NAME}" $OPTIONS "${OUT_DIR}/${OUT_NAME}"
qpdf "${PDF_DIR}/${PDF_NAME}" $OPTIONS "${OUT_DIR}/${OUT_NAME}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment