Skip to content

Instantly share code, notes, and snippets.

@DrAltay
Created April 17, 2020 14:58
Show Gist options
  • Save DrAltay/858e504ffd64f9318df2a7c15a22e879 to your computer and use it in GitHub Desktop.
Save DrAltay/858e504ffd64f9318df2a7c15a22e879 to your computer and use it in GitHub Desktop.
Unlock and edit a PDF with a text editor
INPUT_FILE=$1
# Check if target file is set
if [ -z "$2" ]
then
# Ask confirmation before overwriting the existing file
read -p "Overwrite the existing ${INPUT_FILE} (y/N)? "
if [[ $REPLY =~ ^[Yy]$ ]]
then
TARGET_FILE=$INPUT_FILE
else
echo "Abort."
exit 1
fi
else
TARGET_FILE="$2"
fi
# Temporary folder to use
TMP_DIR=./.tmp
mkdir -p $TMP_DIR
# Decrypt the PDF using ghostscript
UNENCRYPTED_PDF=$TMP_DIR/unencrypted.pdf
gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile="${UNENCRYPTED_PDF}" -f "${INPUT_FILE}"
echo "PDF decrypted !"
# Uncompress the PDF with pdftk
UNCOMPRESSED_PDF=$TMP_DIR/uncompressed.pdf
pdftk "${UNENCRYPTED_PDF}" output "${UNCOMPRESSED_PDF}" uncompress
echo "PDF uncompressed".
# Edit the file
$EDITOR $UNCOMPRESSED_PDF
COMPRESSED_PDF=$TMP_DIR/compressed.pdf
# Compress the PDF file
pdftk "${UNCOMPRESSED_PDF}" output "${COMPRESSED_PDF}" compress
echo "New PDF compressed."
# Clean up obsolete temp files
rm "${UNENCRYPTED_PDF}"
rm "${UNCOMPRESSED_PDF}"
# Move new file to target
mv "${COMPRESSED_PDF}" "${TARGET_FILE}"
# Clean up temp folder
rmdir "${TMP_DIR}"
echo "Done. Saved in ${TARGET_FILE}."
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment