83 lines
2.1 KiB
Bash
83 lines
2.1 KiB
Bash
|
#!/bin/sh
|
||
|
# Reorganize PDF for book-alike printing
|
||
|
# -- w/o cover i.e. page 1 is the cover page --
|
||
|
#
|
||
|
# Author: Nils Freydank <holgersson@posteo.de>
|
||
|
# Copyright: 2020 by Nils Freydank
|
||
|
# License: MIT
|
||
|
# Version: 2020-11-11
|
||
|
#
|
||
|
# dependencies:
|
||
|
# - bash
|
||
|
# - coreutils (date, mkdir)
|
||
|
# - groff (for empty page generation)
|
||
|
# - poppler (pdfseperate, pdfunite)
|
||
|
|
||
|
PATH="/bin:/usr/bin"
|
||
|
|
||
|
INPUT_FILE="${1:-input.pdf}"
|
||
|
OUTPUT_FILE="${2:-printable_output.pdf}"
|
||
|
|
||
|
TMPDIR="tmp_$(date --utc +%s)"
|
||
|
mkdir -p "${TMPDIR}"
|
||
|
|
||
|
# Separate the document into single pages.
|
||
|
pdfseparate "${INPUT_FILE}" "${TMPDIR}/%d.pdf"
|
||
|
|
||
|
# Rearrange the pages:
|
||
|
# 1. Find out the highest page number.
|
||
|
# 2. If page number can't be devided by 4 (i.e. modulus operation is not zero),
|
||
|
# then align/fill with empty pages until it can.
|
||
|
# 3. Create an array with old -> new mappings.
|
||
|
# 4. Move the pages.
|
||
|
|
||
|
# -- step 1 of 4 --
|
||
|
PAGE_COUNTER="$(ls "${TMPDIR}" | wc -l)"
|
||
|
|
||
|
# -- step 2 of 4 --
|
||
|
while [[ $((${PAGE_COUNTER} % 4)) != 0 ]]
|
||
|
do
|
||
|
# Create an new empty page.
|
||
|
echo "" | groff -T pdf > ${TMPDIR}/$((${PAGE_COUNTER} + 1)).pdf
|
||
|
# Re-scan the files.
|
||
|
PAGE_COUNTER="$(ls "${TMPDIR}" | wc -l)"
|
||
|
done
|
||
|
|
||
|
# -- step 3 of 4 --
|
||
|
NEW_PAGE_LIST=()
|
||
|
ctr_down="${PAGE_COUNTER}"
|
||
|
|
||
|
# Note: Start at 1 as this is our first page.
|
||
|
ctr_up=1
|
||
|
while [[ ${ctr_up} -le $((${PAGE_COUNTER} / 2 )) ]]
|
||
|
do
|
||
|
NEW_PAGE_LIST+=( ${ctr_down} )
|
||
|
NEW_PAGE_LIST+=( ${ctr_up} )
|
||
|
ctr_down=$((${ctr_down} - 1))
|
||
|
ctr_up=$((${ctr_up} + 1))
|
||
|
NEW_PAGE_LIST+=( ${ctr_up} )
|
||
|
NEW_PAGE_LIST+=( ${ctr_down} )
|
||
|
ctr_down=$((${ctr_down} - 1))
|
||
|
ctr_up=$((${ctr_up} + 1))
|
||
|
done
|
||
|
|
||
|
# -- step 4 of 4 --
|
||
|
# Warning: Remember to start at zero as an array is accessed!
|
||
|
for ((i=0; i < ${#NEW_PAGE_LIST[*]}; i++))
|
||
|
do
|
||
|
if [[ $((i + 1)) -le 9 ]]
|
||
|
then
|
||
|
mv "${TMPDIR}/${NEW_PAGE_LIST[$i]}.pdf" "${TMPDIR}/newpage-0$((i + 1)).pdf"
|
||
|
else
|
||
|
mv "${TMPDIR}/${NEW_PAGE_LIST[$i]}.pdf" "${TMPDIR}/newpage-$((i + 1)).pdf"
|
||
|
fi
|
||
|
done
|
||
|
|
||
|
# Re-unite the sorted pages for printing.
|
||
|
pdfunite "${TMPDIR}"/newpage-* "${OUTPUT_FILE}"
|
||
|
|
||
|
# Cleanup intermediate data.
|
||
|
rm -rf "${TMPDIR}"
|
||
|
|
||
|
# vim:fileencoding=utf-8:ts=4:syntax=bash:colorcolumn=81:noexpandtab
|