#!/bin/bash
HELP="
  Converts a bunch of image files (in any common format) into one PDF file.
  Optionally, reduces resolution and includes multiple images per page.

  Usage: pages2pdf [opt...] outputname imagefile1 imagefile2 ...
  Options:
    --paper=PAPER_NAME Change paper size (e.g., a4 or letter)
    --scale=NUM        Scale so that width and height are at most NUM pixels
    --nup=2x2          N-up (multiple images per output page)
    --landscape        Rotate paper to landscape mode.
    --slideshow        PDF file opens in full-screen single-page mode
    --fit              Vary page sizes to fit pictures
    --rotate=NUM       Rotate all images by NUM degrees clockwise
    --compress=ALG     Choose compression algorithm (LZW=lossless, JPEG=lossy)
    --quality=num      Choose compression level (0..100), if --compress=JPEG

  Written by Eran Tromer <pages2pdf-eran@tromer>, last change on 2009-02-09.
  Distributed under the GNU Genereal Public License, version 2 or later.
"
#==============================================================================
# Tweakables (most of these are overridable by command-line parameters):

#  Output page size:
PAPER=a4paper
#PAPER=letterpaper

# Options to \includepdfmerge (nup and frame mode, or fitpager):
INC_PDF_OPT=

# Options to TeX class (landscape mode):
CLASS_OPT=

# Scale option to ImageMagick
SCALE=

#  Margin around each physical page
MARGIN=1cm

# Compression type (see http://www.imagemagick.org/script/command-line-options.php#compress)
COMPRESS=LZW

# Quality (see http://www.imagemagick.org/script/command-line-options.php#quality)
QUALITY=

# Colors (see http://www.imagemagick.org/script/command-line-options.php#colors)
COLORS=

# Rotations
ROTATE=

# rotations
HYPERREF_OPT=

# Feed each page separately into pdfpages package
INCLUDE_SEPARATELY=true

#==============================================================================

set -e -E -u

function tell {
	echo "> $*" > /dev/stderr
	"$@"
}
function cleanup { 
	tell rm -fr "$TMPDIR"
	trap - 0 1 2 3 4 5 6 7 8 10 11 12 13 14 15
}
function help {
	echo "$HELP"; exit 1
}

while [[ "${1:-}" == --* ]]; do
	ARG="${1#*=}"
	case "$1" in
		(--paper=*)    
			PAPER="$ARG"paper;
		;;
		(--nup=*)    
			X="${1#--nup=}";
			INC_PDF_OPT="[nup=$X,frame=true]"
			INCLUDE_SEPARATELY=false
		;;
		(--scale=*)    
			SCALE="-resize ${ARG}x${ARG}>";
		;;
		(--landscape)
			CLASS_OPT='[landscape]'
		;;
		(--compress=*)    
			COMPRESS="$ARG";
		;;
		(--rotate=*)
			ROTATE="-rotate $ARG";
		;;
		(--quality=*)
			QUALITY="-quality $ARG";
		;;
		(--slideshow)
			HYPERREF_OPT='[pdfpagemode=FullScreen,pdfpagelayout=SinglePage]'
			;;
		(--screen)
			PAPER='paperwidth=8in,paperheight=6in'
		;;
		(--fit)
			INC_PDF_OPT="[fitpaper=true]"
			INCLUDE_SEPARATELY=true
			;;
		(*)
			echo "Unknown option: $1"
			help
		;;
	esac
	shift
done

if [ ! $# -ge 2 ]; then help; fi
OUTFILE="${1%.pdf}.pdf"
shift
FILES=( "$@" )
MERGED=merged
RFILES=( )

# Create temporary directory:
TMPDIR=`mktemp -d /tmp/pages2pdf.XXXXXX` || { echo "Can't create temporaty directory"; exit 1; }
trap "cleanup; exit 1" 0 1 2 3 4 5 6 7 8 10 11 12 13 14 15

P=0

# Convert to PDF:
for IN in "${FILES[@]}"; do 
	OUT="page$(( ++P )).pdf"; RFILES[${#RFILES[@]}]="$OUT";
	if [[ "$IN" == *.pdf ]] || [[ "$IN" == *.PDF ]]; then
		tell cp "$IN" "$TMPDIR/$OUT"
	else
		tell convert ${SCALE:-} -compress ${COMPRESS} ${ROTATE:-} ${QUALITY:-} ${COLORS:-} "$IN" "PDF:$TMPDIR/$OUT"
	fi
done

pushd $TMPDIR > /dev/null

# Create LaTeX file
cat > ${MERGED}.tex << EOF
\\documentclass${CLASS_OPT:-}{article}
\\usepackage{geometry}
\\usepackage{pdfpages}
\\usepackage${HYPERREF_OPT}{hyperref}
\\geometry{${PAPER},tmargin=${MARGIN},bmargin=${MARGIN},lmargin=${MARGIN},rmargin=${MARGIN}}
\\begin{document}
EOF

if $INCLUDE_SEPARATELY; then
	for PAGE in "${RFILES[@]}"; do 
		echo "\\includepdf${INC_PDF_OPT:-}{$PAGE}" >> ${MERGED}.tex
	done
else
	echo "\\includepdfmerge${INC_PDF_OPT:-}{" >> ${MERGED}.tex
	FIRST=true
	for PAGE in "${RFILES[@]}"; do 
		$FIRST || echo ', ' >> ${MERGED}.tex
		FIRST=false
		echo "$PAGE, -" >> ${MERGED}.tex
	done
	echo "}" >> ${MERGED}.tex
fi

echo "\end{document}" >> ${MERGED}.tex

# Process LaTeX file
tell pdflatex -halt-on-error ${MERGED}.tex 2>&1 | grep -v '^(/usr/share/texmf'

popd > /dev/null
tell cp $TMPDIR/${MERGED}.pdf "$OUTFILE"
cleanup
echo
ls -lh "$OUTFILE"
echo Done, \""$OUTFILE"\" at your service.

