Concatenating PDF files on Linux

Justin Wernick <>
Curly Tail, Curly Braces
2023-06-08

Abstract

This article just shares a shell script I use to concatenate PDF files together into one long PDF. Under the hood, the script is using Ghostscript.

Sometimes, as an adult in this increasingly-digital world, you need to do things with PDF files.

For example, I sometimes need to stick a bunch of PDFs together into one extra long PDF. This is useful, for example, if you want to keep a digital copy of an invoice and your proof of payment together in one file. Or maybe you scanned, photographed, or screenshotted the 5 pages of a document separately and want to stick them together into one.

On Linux, this can be done on the command line using a program called Ghostscript. Ghostscript is a program for working with Postscript and PDF files.

Ghostscript is powerful, but has many options and I struggle to remember exactly how to run it correctly. That's why I wrote this little concat-pdf.sh shell script to simplify my life.

Save this as concat-pdf.sh wherever you keep your personal shell scripts (~/bin/ can be a good option) and make it executable.

#!/bin/bash

# Concatenates PDFs together
#
# Usage: concat-pdf.sh <target> <file..>
#
# Requires ghostscript to be installed and on the path.

set -e

display_usage() {
    echo "Usage: concat-pdf.sh <target> <file..>"
}

if ! command -v gs &> /dev/null
then
    echo "Ghostscript must be installed with gs on the path"
    exit 1
fi

if [ $# -lt 2 ]
then
    display_usage
    exit 1
fi

TARGET_PDF=$1;

if [ -e "$TARGET_PDF" ]
then
    display_usage
    echo "$TARGET_PDF already exists"
    exit 1
fi

gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile="$@"

Example of using the script:

concat-pdf.sh new-pdf-file.pdf pdf-part-1.pdf pdf-part-2.pdf

If you'd like to share this article on social media, please use this link: https://www.worthe-it.co.za/blog/2023-06-08-concatenating-pdf-files-on-linux.html

Copy link to clipboard

Tags: blog, linux, shell-script


Support

If you get value from these blog articles, consider supporting me on Patreon. Support via Patreon helps to cover hosting, buying computer stuff, and will allow me to spend more time writing articles and open source software.


Related Articles

The Localhost Podcast

I wanted to manage the process of syncing audiobooks from my computer to my phone better. The solution that worked well for me is to use a podcasting app and an RSS feed. This article explains why this works well for me, and how you can try it out.

Automated Syncing with Git

I wanted Dropbox-style syncing of my notes between my computers. However, rather than actually using Dropbox, I wanted to keep my notes in a Git repo so that I can manage it the same way that I manage code that I write. This article shows how I achieved this using Git Sync and Systemd.

Subscribe to my RSS feed.