Linux shell script to reduce PDF file size

Here is a handy and useful Linux and Unix shell script that reduce PDF file size using Ghostscript. No need to upload your PDF file to the shady third-party website. Just do it from the terminal. I tested it with both CentOS and Ubuntu/Debian Linux.

A sample shell script reduce the file size of a scanned PDF file under Linux. It should work with other Unix-like systems too as long as Ghostscript installed. For example macOS or FreeBSD.

Unix and Linux shell script to reduce PDF file size

#!/bin/sh
 
# http://www.alfredklomp.com/programming/shrinkpdf
# Licensed under the 3-clause BSD license:
#
# Copyright (c) 2014-2019, Alfred Klomp
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of its contributors
#    may be used to endorse or promote products derived from this software
#    without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
 
#
# Modified by Vivek Gite to suit my needs
#
shrink ()
{
	gs					\
	  -q -dNOPAUSE -dBATCH -dSAFER		\
	  -sDEVICE=pdfwrite			\
	  -dCompatibilityLevel=1.3		\
	  -dPDFSETTINGS=/screen			\
	  -dEmbedAllFonts=true			\
	  -dSubsetFonts=true			\
	  -dAutoRotatePages=/None		\
	  -dColorImageDownsampleType=/Bicubic	\
	  -dColorImageResolution=$3		\
	  -dGrayImageDownsampleType=/Bicubic	\
	  -dGrayImageResolution=$3		\
	  -dMonoImageDownsampleType=/Subsample	\
	  -dMonoImageResolution=$3		\
	  -sOutputFile="$2"			\
	  "$1"
}
 
check_smaller ()
{
	# If $1 and $2 are regular files, we can compare file sizes to
	# see if we succeeded in shrinking. If not, we copy $1 over $2:
	if [ ! -f "$1" -o ! -f "$2" ]; then
		return 0;
	fi
	ISIZE="$(echo $(wc -c "$1") | cut -f1 -d\ )"
	OSIZE="$(echo $(wc -c "$2") | cut -f1 -d\ )"
	if [ "$ISIZE" -lt "$OSIZE" ]; then
		echo "Input smaller than output, doing straight copy" >&2
		cp "$1" "$2"
	fi
}
 
usage ()
{
	echo "Reduces PDF filesize by lossy recompressing with Ghostscript."
	echo "Not guaranteed to succeed, but usually works."
	echo "  Usage: $1 infile [outfile] [resolution_in_dpi]"
}
 
IFILE="$1"
 
# Need an input file:
if [ -z "$IFILE" ]; then
	usage "$0"
	exit 1
fi
 
# Output filename defaults to "-" (stdout) unless given:
if [ ! -z "$2" ]; then
	OFILE="$2"
else
	OFILE="-"
fi
 
# Output resolution defaults to 72 unless given:
if [ ! -z "$3" ]; then
	res="$3"
else
	res="90"
fi
 
shrink "$IFILE" "$OFILE" "$res" || exit $?
 
check_smaller "$IFILE" "$OFILE"

How to Reduce PDF File Size in Linux when using bash shell

Download and install the script in your system. Set up executable permissions using the chmod command:
chmod +x ~/bin/shrinkpdf.sh
Run it as follows:
~/bin/shrinkpdf.sh input.pdf output.pdf
~/bin/shrinkpdf.sh input.pdf output.pdf 100
~/bin/shrinkpdf.sh input.pdf output.pdf 120

Use the ls to list file size:
ls -lh input.pdf
ls -lh output.pdf

Unix and Linux shell script to reduce PDF file size

Comparing original vs compressed pdf file quality

  1. input.pdf (original file [1018K])
  2. output.pdf (compressed file [217K])

Conclusion

I often use this tiny script to reduce the file size of a scanned PDF file that I need to email/upload or store it on my NAS server for future reference. Most government or third party sites put restrictions on PDF file size uploads. Hence, using this script can help you reduce the size and upload files. The source of original shell script is here

Get the latest tutorials on SysAdmin, Linux/Unix, Open Source, and DevOps topics:
CategoryList of Unix and Linux commands
File Management cat
Firewall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilities dig host ip nmap
OpenVPN CentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Manager apk apt
Processes Management bg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searching grep whereis which
User Information groups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPN CentOS 8 Debian 10 Firewall Ubuntu 20.04
6 comments… add one
  • John Sep 5, 2020 @ 10:28

    I think ISIZE="$(echo $(wc -c "$1") | cut -f1 -d\ )" and OSIZE="$(echo $(wc -c "$2") | cut -f1 -d\ )" can be replaced with ISIZE="$(du -b "$1" | cut -f1)" and OSIZE="$(du -b "$2" | cut -f1)". It’s shorter and du is more appropriate if you’re merely interested in the file size.

    This is a great script btw. Thank you!

  • MarchingBand Aug 3, 2020 @ 23:56

    Indeed very good shell script. This is why I love linux which is good for programming topics

  • Tiny@Tina Jul 30, 2020 @ 16:28

    It says gs command not found. How to solve this problem? How can I install gs command?

    • René Sep 5, 2020 @ 9:13

      Install ghostscript.

    • Wataru Noguchi Sep 5, 2020 @ 9:38

      gs command may one of the Ghostscript toolset.

      You can install Ghostscript as follows if Ubuntu 20.04.

      sudo apt install ghostscript

      • CmdNemo Sep 5, 2020 @ 10:17

        Fedora user here. I ran:

        sudo dnf update
        sudo dnf ghostscript

Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.