Raven - Blog
June 30, 2024

Compress your PDF in 2 clicks on Ubuntu

Posted on June 30, 2024  •  4 minutes  • 761 words  • Other languages:  Français

In my family, there are several PCs running Linux/Ubuntu. I needed to make PDF compression easily accessible on one of them. Indeed, it’s common to have to upload documents to online platforms, and the size of the documents is often limited. I’m used to the command line, but I wanted a function that anyone could use.

Rather than looking for a particular piece of software, I set out to find a “script” that I could integrate into Nautilus, the default file manager in Ubuntu (Gnome). And good news, I’ve found one that I’d like to introduce to you!

Nautilus file manager scripts

Nautilus “scripts” are small programs that users can add to the file manager to automate or facilitate repetitive tasks on documents.

These scripts are then easily accessible, via the contextual menu (right-click) of files and folders.

Nautilus script

To use a Nautilus script, simply place your script in the directory ~/.local/share/nautilus/scripts and apply the execute right chmod +x. Scripts can be written in various programming languages such as Bash, Python… Once a script has been added, it becomes accessible via the “Scripts “ context menu in Nautilus.

When a script is run, it receives parameters, such as selected files or folders, and can perform specific actions based on these inputs. For example, a script can resize images, batch rename files, or convert file formats. Here, we’re going to compress PDFs.

The PDF compression script

I create my ~/.local/share/nautilus/scripts/CompressPDF file and add execution with chmod +x.

WARNING: The script used has dependencies for compression in particular, so please install: sudo apt install ghostscript.

Nautilus script NOTE: Multiple files can be selected to compress an entire batch!

Nautilus script

Compression script :

#! /bin/bash

# AUTHOR: (c) Ricardo Ferreira
# NAME: Compress PDF 1.4
# DESCRIPTION: A nice Nautilus script with a GUI to compress and optimize PDF files
# REQUIRES: ghostscript, poppler-utils, zenity
# LICENSE: GNU GPL v3 (http://www.gnu.org/licenses/gpl.html)
# WEBSITE: https://launchpad.net/compress-pdf

# Messages
  # English (en-US)
  error_nofiles="No file selected."
  error_noquality="No optimization level selected."
  error_ghostscript="PDF Compress requires the ghostscript package, which is not installed. Please install it and try again."
  error_nopdf="The selected file is not a valid PDF archive."
  label_filename="Save PDF as..."
  label_level="Please choose an optimization level below."
  optimization_level="Optimization Level"
  level_default="Default"
  level_screen="Screen-view only"
  level_low="Low Quality"
  level_high="High Quality"
  level_color="High Quality (Color Preserving)"
  job_done="has been successfully compressed"
  filename_postpend="-optimized"

case $LANG in

 fr*)
  # French (fr-FR) by Astromb
  error_nofiles="Aucun fichier sélectionné"
  error_noquality="Aucun niveau d'optimisation sélectionné"
  error_ghostscript="PDF Compress a besoin du paquet ghostscript, mais il n'est pas installé. Merci de l'installer et d'essayer à nouveau."
  error_nopdf="Le fichier que vous avez sélectionné n'est pas un PDF valide."
  label_filename="Sauvegarder le PDF sous..."
  label_level="Merci de choisir, ci-dessous, un niveau d'optimisation."
  optimization_level="Niveau d'optimisation"
  level_default="Défaut"
  level_screen="Affichage à l'écran"
  level_low="Basse qualité"
  level_high="Haute qualité"
  level_color="Haute qualité (Couleurs préservées)"
  filename_postpend="-optimisé";;

esac

VERSION="1.4.1"
ZENITY=$(which zenity)

# Check if Ghostscript is installed
GS="/usr/bin/ghostscript"
if [ ! -x $GS ]; then
        $ZENITY --error --title="Compress PDF "$VERSION"" --text="$error_ghostscript"
        exit 0;
fi

# Check if the user has selected any files
if [ $# -eq 0 ]; then
        $ZENITY --error --title="Compress PDF "$VERSION"" --text="$error_nofiles"
        exit 0;
fi

# Ask the user to select a compressing format
selected_level=$($ZENITY --list --title="Compress PDF "$VERSION"" --text "$label_level" --radiolist --column "" --column "$optimization_level" TRUE "$level_default" FALSE "$level_screen" FALSE "$level_low" FALSE "$level_high" FALSE "$level_color")
if [ -z "$selected_level" ]; then
        $ZENITY --error --title="Compress PDF "$VERSION"" --text="$error_noquality"
        exit 0;
fi

# Select the optimization level to use
case $selected_level in
        "$level_default")
                COMP_COMMAND="/default"
        ;;
        "$level_screen")
                COMP_COMMAND="/screen"
        ;;
        "$level_low")
                COMP_COMMAND="/ebook"
        ;;
        "$level_high")
                COMP_COMMAND="/printer"
        ;;
        "$level_color")
                COMP_COMMAND="/prepress"
        ;;
esac

# Choose output file name
temp_filename=.temp-mytmppdf.pdf

if [ $# -eq 1 ] ; then
 pdf_file=$(basename "$1")
 suggested_filename=${pdf_file%.*}${filename_postpend}.${pdf_file##*.}
 output_filename=$($ZENITY --file-selection --save --confirm-overwrite --filename="$suggested_filename" --title="$label_filename")
 if [ "$?" = 1 ] ; then
         exit 0;
 fi
fi

for arg in "$@"
do
 if [ $# -ne 1 ] ; then
  pdf_file=$(basename "$arg")
  output_filename=${pdf_file%.*}${filename_postpend}.${pdf_file##*.}
 fi

 # Check if the selected file is a PDF
 mimetype=$(file -b -i "$arg")
 if [ -z "`echo $mimetype | grep -i 'pdf' `" ]; then
  $ZENITY --error --title="Compress PDF "$VERSION"" --text="$error_nopdf"
     exit 0;
 fi

 # Extract metadata from the original PDF
 pdfinfo "$arg" | sed -e 's/^ *//;s/ *$//;s/ \{1,\}/ /g' -e 's/^/ \//' -e '/CreationDate/,$d' -e 's/$/)/' -e 's/: / (/' > .pdfmarks
 sed -i '1s/^ /[/' .pdfmarks
 sed -i '/:)$/d' .pdfmarks
 echo " /DOCINFO pdfmark" >> .pdfmarks

 # Execute ghostscript while showing a progress bar
 (echo "0" ;
  gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=$COMP_COMMAND -dNOPAUSE -dQUIET -dBATCH -sOutputFile="$temp_filename" "$arg" .pdfmarks
  rm .pdfmarks
  echo "100") | (if `$ZENITY --progress --pulsate --auto-close --title="Compress PDF "$VERSION""`;
                  then
                      mv -f "$temp_filename" "$output_filename" &
                      notify-send "Compress PDF" "$pdf_file $job_done"
                  else
                      killall gs
                      rm "$temp_filename"
                      exit
                  fi)
done
Follow me

Subscribe to my RSS feed !