#!/bin/bash
# Identifiziert in einem PDF Scans, auf denen zwei Seiten
# zusammengescannt wurden und schneidet dieses durch
#pdfimages $1 XPage
outputfile="$1-output.pdf"
filelist=""
for FILE in *.png ; do
width="`gm identify -format '%w \n' $FILE`"
height="`gm identify -format '%h \n' $FILE`"
if [ "$width" -gt "$height" ]; then
 echo "$FILE is landscape. Cutting in two halves..."
 let "halfwidth=$width/2"
 convert -crop "$halfwidth"x"$height"+0+0 "$FILE" "$FILE-A.ppm"
 convert -page A4 "$FILE-A.ppm" "$FILE-A.pdf"
 convert -crop "$width"x"$height"+"$halfwidth"+0 "$FILE" "$FILE-B.ppm" 
 convert -page A4 "$FILE-B.ppm" "$FILE-B.pdf"
 filelist="$filelist $FILE-A.pdf $FILE-B.pdf"
else
 echo "$FILE is portrait. Nothing to do."
 convert -page A4 "$FILE" "$FILE.pdf"
 filelist="$filelist $FILE.pdf"
fi
done;
# Neues PDF aus Einzelseiten erstellen
echo $filelist
#gs -q -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=$outputfile $filelist -c quit
gs -q -dNOPAUSE -sPAPERSIZE=a4 -dPDFFitPage -sDEVICE=pdfwrite -sOutputFile=$outputfile $filelist -c quit
# Aufräumen
rm *.png.pdf

# PDF in Teile zerlegen:
# gs -q -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=A3Pages2.pdf -dFirstPage=1 -dLastPage=2 SM_EUROPC_ALL_SCAN5.pdf -c quit

