Skip to content

Instantly share code, notes, and snippets.

@aleofreddi
Created June 21, 2019 09:15
Show Gist options
  • Save aleofreddi/ec2aeac18ca709be88fbb6ae2a43e64f to your computer and use it in GitHub Desktop.
Save aleofreddi/ec2aeac18ca709be88fbb6ae2a43e64f to your computer and use it in GitHub Desktop.
#!/bin/sh
#
# Combine two non-duplex document feeder scansions into a single duplex pdf file.
#
# The input file should be procuded passing the document in the feeder (from the
# first page forward) and then passing it again on the backside (that is from
# the last page on backward).
#
# Tue Aug 8 20:41:26 CEST 2017, Andrea Leofreddi
#
die() {
echo $@ >&2
exit 2
}
if
[ $# != 2 -o "$1" = "$2" -o ! -r "$1" -o -f "$2" ] \
|| ! echo "$1" | grep -iq '\.pdf$' \
|| ! echo "$2" | grep -iq '\.pdf$' \
; then
echo Usage: $0 input.pdf output.pdf >&2
exit 1
fi
tmp_dir=`mktemp -d`
trap "rm -rf $tmp_dir" EXIT
input="$1"
output="$2"
pages=`gs -q -dNODISPLAY -c "($input) (r) file runpdfbegin pdfpagecount = quit"` \
|| die Failed to get the total number of pages
echo Document has $pages pages, splitting each page...
gs -q -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=$tmp_dir/%d.pdf "$input" \
|| die Failed to split input file
i=1
j=$pages
files=""
while [ $i -le $pages ]; do
files="$files $tmp_dir/$i.pdf $tmp_dir/$pages.pdf"
((i=$i+1))
((pages=$pages-1))
done
echo Merging back document pages using the following order: $files
gs -q -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile="$output" $files \
|| die Failed to merge back items
echo Document reordered into "$output"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment