#!/bin/sh # # pdfcat - concatenate PDFs into one # # $Id$ add_empties=0 me=`basename "$0"` Erm() { echo $@ 1>&2; } Die() { echo fatal error: $@ 1>&2; exit 1; } DieIfMissing() { for x in "$@" do command -v "$x" >/dev/null || Die cannot find required executable $x done } while : do case "$1" in -e) add_empties=1;; -h) Erm Usage: $me [-e] [pdffile1 [pdffile2 [...]]] > all.pdf; exit 0;; -*) Die unknown option: $1, use -h for help; exit 1;; *) break;; esac shift done DieIfMissing mktemp file pdflatex pdfinfo d=`mktemp -d /tmp/$me-XXXXX` [ -n "$d" ] || exit 1 # thank you, https://unix.stackexchange.com/questions/272872/concatenate-pdfs-but-extend-pdfs-to-be-even-number-of-pages trap "rm -rf $d" INT QUIT HUP EXIT cat < $d/all.tex \documentclass{article} \usepackage{pdfpages} \begin{document} ZZ i=1 for f in "$@" do if [ application/pdf != `file -b --mime-type "$f"` ] then Erm not accessible or no PDF, skipped: $f continue fi cp -p "$f" $d/$i.pdf printf '\includepdf[pages=-]{%s}\n' $i.pdf >> $d/all.tex if [ $add_empties = 1 ] then # add an empty page if their number is odd pages=`pdfinfo $d/$i.pdf | grep -oP '^Pages:\s*\K\d+'` if [ `expr "$pages" % 2` != 0 ] then printf '%s\n' "\newpage\null" >> $d/all.tex fi fi i=`expr $i + 1` done printf '\\end{document}\n' >> $d/all.tex ( cd $d && pdflatex all >/dev/null 2>&1 && { grep -q . all.pdf && cat all.pdf; } )