Skip to content

Instantly share code, notes, and snippets.

@qguv
Last active May 23, 2025 10:03
Show Gist options
  • Save qguv/4cc1086491b15ef167fcbbaddfe63b6e to your computer and use it in GitHub Desktop.
Save qguv/4cc1086491b15ef167fcbbaddfe63b6e to your computer and use it in GitHub Desktop.
#!/bin/sh
set -e
tr=tr
if hash gtr 2> /dev/null; then
tr=gtr
fi
if [ "$1" = -2 ]; then
shift
section_length=${2:-16}
extra_opts="--nup 1x2"
else
section_length=${2:-8}
extra_opts=""
fi
papertype=a4paper
dir=".built_$($tr -dc A-Za-z0-9_ < /dev/urandom | head -c 6)"
mkdir "$dir"
docname="${1##*/}"
docname="${docname%.*}"
pages="$(pdfinfo "$1" | grep 'Pages:' | sed 's/[^0-9]//g')"
section=1
section_start=1
section_end=0
while [ $section_start -le $pages ]; do
section_end=$((section_end + section_length))
section_end=$((section_end > pages ? pages : section_end))
f="$dir/$docname.$(printf '%04d' "$section").pdf"
pdfjam --no-tidy $extra_opts "$1" "$section_start-$section_end" -o "$f" # <------------ was: no NUP
pdfbook2 "--paper=$papertype" --inner-margin=170 --outer-margin=5 "$f"
section_start=$((section_start + section_length))
section=$((section + 1))
done
pdfjam --no-tidy $dir/*-book.pdf --landscape --rotateoversize false -o "${docname}-bound.pdf"
rm -r "$dir"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment