Combining pdf with linux via the command-line

I’ve always found a need for this, and with some digging, I’ve found a couple of ways to do this.  The simplist is with ImageMagik, but I’ve found the default values leave the quality a little lacking.  However, I’ve found an article that uses GhostScript to do it, and it does a wonderful job.

gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=output.pdf input1.pdf input2.pdf

They suggest putting it in an alias, but I’ve gone a step further and just put it in a bash script in ~/bin/combinepdf

#!/bin/bash

if [ $# -le 1 ]
then
     echo "usage: combinepdf output.pdf input1.pdf ... inputN.pdf"
exit -1
fi

OUTPUT=$1

if [ -e $OUTPUT ]
then
     echo "Output file \"$OUTPUT\" exists"
exit -1
fi

fnum=2

INPUT="$2"
ARGV=( [email protected] )

while [ $fnum -lt $# ]
do
     INPUT=`echo $INPUT" "${ARGV[$fnum]}`
     let "fnum += 1"
done

gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=$OUTPUT $INPUT

Then chmod a+x ~/bin/combinepdf and then run it.

This entry was posted in Linux and tagged , , . Bookmark the permalink.
  • Kaligule

    Why didn’t you just use pdftk?

    pdftk *.pdf cat output onelargepdfile.pdf

  • At the time this was written, I was not aware of pdftk. Also, I have found that ghostscript seems to be installed on almost every system I’ve dealt with. That’s most useful when you do not have the ability to update/install new packages.