#!/bin/bash
name="pdf-concat"
version="1.0"
read -r -d '' help_message <<-EOF
Concatenate PDF files
Usage: pdf-concat [OPTIONS] TARGET [TARGET..]
Options:
-b BACKEND, select a PDF backend
--backend BACKEND
-d, --dump print to STDOUT
-h, --help print this message
-l, --list-backends list available PDF backends
-o OUTPUT, write to a file
--output OUTPUT
-q, --quiet suppress error messages and prompts
-v, --verbose show additional messages
-V, --version print version number and exit
EOF
source /usr/local/lib/mylib.bash
select_backend() {
if command -v pdfjam >/dev/null 2>&1; then
/usr/bin/printf "pdfjam\n"
fi
if command -v pdfunite >/dev/null 2>&1; then
/usr/bin/printf "pdfunite\n"
fi
if command -v gs >/dev/null 2>&1; then
/usr/bin/printf "gs\n"
fi
if command -v pdftk >/dev/null 2>&1; then
/usr/bin/printf "pdftk\n"
fi
}
list_backends() {
if command -v pdfjam >/dev/null 2>&1; then
msg "pdfjam Interface to the pdfpages package for LaTeX"
fi
if command -v pdfunite >/dev/null 2>&1; then
msg "pdfunite Utility built on FreeDesktop's Poppler library"
fi
if command -v gs >/dev/null 2>&1; then
msg "gs PostScript interpreter"
fi
if command -v pdftk >/dev/null 2>&1; then
msg "pdftk General-purpose PDF toolkit"
fi
}
positional=()
quiet=0
verbose=0
dump=0
backend="$(select_backend)"
outfile=""
while [[ $# -gt 0 ]]; do
case "$1" in
-b|--backend)
debug_msg "Setting backend option to ${2} (was ${backend})"
dump="$2"
shift; shift
;;
-d|--dump)
debug_msg "Setting dump option to 1 (was ${dump})"
dump=1
shift
;;
-h|--help)
help_msg
shift
;;
-l|--list-backends)
list_backends
shift
;;
-o|--output)
debug_msg "Setting outfile option to ${2} (was ${outfile})"
outfile="$2"
shift; shift
;;
-q|--quiet)
debug_msg "Setting quiet option to 1 (was ${quiet})"
quiet=1
shift
;;
-v|--verbose)
debug_msg "Setting verbose option to 1 (was ${verbose})"
verbose=1
shift
;;
-V|--version)
version_msg
;;
*)
debug_msg "Argument '${1}' added to positional array"
positional+=("$1")
shift
;;
esac
done
# sanitize infiles
infiles=()
infiles_count=0
for target in "${positional[@]}"; do
if [[ ! -f "$target" ]]; then
error_msg "No such file '${target}'"
else
infiles+=("$target")
infiles_count=1
fi
done
if [[ "$infiles_count" -eq 0 ]]; then
usage_msg
fi
infiles_string="$(/usr/bin/printf "%q " "${infiles[@]}")"
# sanitize outfile
if [[ -f "$outfile" ]]; then
if ! prompt_overwrite "$outfile"; then
error_msg "No valid output"
fi
fi
# dispatch to backend
if [[ "$backend" -eq "pdfjam" ]]; then
pdfjam -o "$outfile" $infiles_string
elif [[ "$backend" -eq "pdfunite" ]]; then
pdfunite $infiles_string "$outfile"
elif [[ "$backend" -eq "gs" ]]; then
gs -dNOPAUSE -dQUIET -dBATCH -sDEVICE=pdfwrite -sOutputFile="$outfile" $infiles_string
elif [[ "$backend" -eq "pdftk" ]]; then
pdftk $infiles_string cat output "$outfile"
else
error_msg "No valid backend"
fi