Skip to content

Instantly share code, notes, and snippets.

@efaisal
Last active December 15, 2015 01:59
Show Gist options
  • Save efaisal/5184328 to your computer and use it in GitHub Desktop.
Save efaisal/5184328 to your computer and use it in GitHub Desktop.
Given a PDF file with multiple A5 size pages, all with potrait orientation where the total of pages are a multiple of four. This shell script (requires bash) will output a new PDF file suitable for printing on A4 paper with landscape orientation, arranging the source pages so that the printed A4 output can nicely turn into an A5 booklet by simpl…
#!/bin/bash
# In PDF world potrait A4 is 595ptx842pt
[ -z "$1" ] && echo "Please specify input file" && exit 1
[ ! -f "$1" ] && echo "File not found" && exit 1
# Get total number of pages
total_pages=`gs -dNODISPLAY $1 -c quit | awk '/Page/ { print NR; }' | wc -l`
echo "Total number of pages is $total_pages."
# Check if we can process PDF with $total_pages
r=$(($total_pages%4))
[ "$r" -ne "0" ] && echo "Can't process with $total_count number of pages" && exit 1
# Split the pages into separate PDF
for i in `seq $total_pages`; do
echo -n "Processing page $i"
idx[$(($i-1))]="$i"
gs -q -o $i.pdf -sDEVICE=pdfwrite -dAutoRotatePages=/None -dFirstPage=$i -dLastPage=$i -g4210x5950 -f $1
echo " [ Done ]"
done
# Arrange booklet pages
show_back_first=1
ori_len=$((${#idx[@]}))
count=0
echo -n "Arrange booklet pages"
while true; do
#echo ${idx[@]}
front=${idx[$count]}
back=${idx[$(($ori_len-$count-1))]}
pagename="page-$(($count+1)).pdf"
pages[$count]=$pagename
if [ "$show_back_first" -eq 1 ]; then
pdfnup --nup 2 -q --landscape --outfile $pagename $back.pdf $front.pdf
show_back_first=0
else
pdfnup --nup 2 -q --landscape --outfile $pagename $front.pdf $back.pdf
show_back_first=1
fi
unset idx[$count]
unset idx[$(($ori_len-$count-1))]
count=$(($count+1))
arr_len=${#idx[@]}
if [ "$arr_len" -eq 0 ]; then
break
fi
done
echo " [ Done ]"
# Generate combined pages
echo -n "Generate combine pages"
[ -f "booklet.pdf" ] && rm booklet.pdf
pdftk ${pages[@]} cat output risalah.pdf
echo " [ Done ]"
# Cleaning up
echo -n "Cleaning up"
rm -f [0-9]*.pdf
rm -f page-*.pdf
echo " [ Done ]"
exit 0
@efaisal
Copy link
Author

efaisal commented Mar 24, 2013

Embedded fonts will not be displayed correctly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment