Pages

Tuesday, March 29, 2011

Perl script to concatenate PDF files

I hammered this together a few minutes ago because I find I often need something like this. It's a perl script that concatenates PDF files from the command line. It could be adapted pretty easily for web form input or a gui app if you wanted to badly enough.

The only prerequisites I know of are Perl and Ghostscript which should be found on virtually any modern unix-type system and possibly some Windows ones too.

I don't intend to offer support per se but let me know if you have any questions.

Cheers,

Stephen

Releasing under GPLv3 http://www.gnu.org/licenses/gpl.html.

#!/usr/bin/perl -w
# ^^ change path if necessary

# a script to concatenate PDF files. just give it PDF files as arguments, in the
# order you want them concatenated.
# cobbled together from the 'gs' command line example found at
# http://doeidoei.wordpress.com/2009/04/12/easy-way-to-concatenate-pdf-files-in-ubuntu-linux/

# NOTE: I have not tested this with any other papersize than letter!
# it does handle portrait/landscape without fuss however.

use strict;

my $cmdstr='gs -q -sPAPERSIZE=letter -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=output.pdf';
my $cmdargs='';

my @infiles = @ARGV;

if (scalar(@infiles)> 0){
  foreach my $file (@infiles) {
    $cmdargs .= " $file";
  }

  exec $cmdstr . $cmdargs;
} else {
  print "Syntax: $0 [input PDF file 1] ... [input PDF file n]\n";
}