Skip to content

Instantly share code, notes, and snippets.

@yottatsa
Created April 20, 2020 23:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yottatsa/9c0f09b839f4eb4cbfeeab82dcaae4e8 to your computer and use it in GitHub Desktop.
Save yottatsa/9c0f09b839f4eb4cbfeeab82dcaae4e8 to your computer and use it in GitHub Desktop.
Cutting PDF pages in half
#!/bin/bash -eux
# Based on https://superuser.com/questions/235074/how-can-i-split-a-pdfs-pages-down-the-middle
sizes () {
pdfinfo -box "${1}" -f 1 -l -1 | grep MediaBox
}
biggest () {
awk '{print $4,$5,$6,$7}' $@ | sort | uniq | sort -n -k 1 -k 2 -k 3 -k 4 -t ' ' -r | head -n1
}
for f
do
T="$(mktemp -d)"
trap "rm -rf $T" ERR
sizes "$f" > "${T}/sizes"
SIZE="$(biggest "${T}/sizes")"
read _ _ WS HS <<< "${SIZE}"
HWS="$(echo "$WS * 100 / 2 / 100" | bc)"
RHS="$(echo "$HS * 100 / 100" | bc)"
echo "Size: $WS x $HS -> 2 x $HWS x $RHS"
grep "$WS" "${T}/sizes" | grep "$HS" > "${T}/pages"
FP="$(head -n1 "${T}/pages" | awk '{print $2}')"
LP="$(tail -n1 "${T}/pages" | awk '{print $2}')"
TP="$(comm --nocheck-order -13 "${T}/pages" "${T}/sizes" | awk '{print $2}')"
FTP="$(echo $(for i in $TP; do if [ $i -lt $FP ]; then echo $i; fi; done) | tr ' ' ,)"
LTP="$(echo $(for i in $TP; do if [ $i -gt $LP ]; then echo $i; fi; done ) | tr ' ' ,)"
echo "Pages: $FTP, $FP-$LP, $LTP"
gs -o "${T}/left.pdf" "-dFirstPage=$FP" "-dLastPage=$LP" -sDEVICE=pdfwrite "-g$((HWS * 10))x$((RHS * 10))" -c "<</PageOffset [0 0]>> setpagedevice" -f "$f"
gs -o "${T}/right.pdf" "-dFirstPage=$FP" "-dLastPage=$LP" -sDEVICE=pdfwrite "-g$((HWS * 10))x$((RHS * 10))" -c "<</PageOffset [-${HWS} 0]>> setpagedevice" -f "$f"
O="$(basename "${f}" .pdf)-out.pdf"
P="$(stat -c '%U:%G' "${f}")"
pdftk "L=${T}/left.pdf" "R=${T}/right.pdf" shuffle L R output "${T}/shuffled.pdf" verbose
pdftk "S=${T}/shuffled.pdf" "O=${f}" cat "O${FTP}" S "O${LTP}" output "${T}/output.pdf" verbose
chown "${P}" "${T}/output.pdf"
mv "${T}/output.pdf" "${O}"
rm -rf "${T}"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment