LaTeX PDFmerge

Hey there,

since merging several pdf files is a task that needs to be done pretty often, I decided to write a little TeX file for that.
The initial version assumes that all pdf files have the same name pattern and end with a number:

\documentclass[a4paper,landscape]{article}
\usepackage{pdfpages}
\usepackage{forloop}
 
\begin{document}
 
\newcounter{ct}
\forloop{ct}{1}{\value{ct} < 8}%
{%
    \includepdf[pages=-]{FILENAME\arabic{ct}.pdf}
}
 
\end{document}

About one usage after that, I wrote a perl-script that scans a given directory for pdf files and merges them by creating a TeX-script:

#!/usr/bin/perl
 
use Getopt::Std;
use Switch;
 
$texfile = "/tmp/merge.tex";
$getoptstr = 'p:f:';
$path = '';
$format = 'portrait';
 
sub usage() {
	print <<"EOF";
Usage: $0 -p  [-f ]
	-p: path where the pdf's to merge reside
	-f: page format (defaults to p):
		l: landscape
		p: portrait
EOF
	exit(1);
}
 
@ARGV < 2 and usage();
 
getopts($getoptstr, \%args) or usage();
 
while (($key,$value) = each %args) {
	switch ($key) {
		case 'p' { $path = $value; }
		case 'f' { $format = $value eq "l" ? "landscape" : "portrait"; }
	}
}
 
unless (-e $path) {
	die("Directory \"$path\" doesn't exist!");
}
 
open(TEXFILE, ">" . $texfile)
	or die("Couldn't open TeX-File");
 
print TEXFILE <<"EOF";
\\documentclass[a4paper,$format]{article}
\\usepackage{pdfpages}
\\usepackage{forloop}
\\begin{document}
EOF
 
foreach $file (<$path/*.pdf>) {
	print TEXFILE '\includepdf[pages=-]{'.$file.'}'."\n";
}
print TEXFILE '\end{document}'."\n";
close(TEXFILE);
 
print `pdflatex $texfile`;
 
`rm $texfile` and die("Couldn't delete $texfile");
 
exit(0);

Posted

in

by

Tags: