Last active
August 25, 2017 07:34
-
-
Save glegoux/1a64dd868acadc771243901c1cceef4f to your computer and use it in GitHub Desktop.
[Bash] Convert document pdf with A4 format as a booklet with A5 format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# | |
# pdf-to-booklet.bash | |
# | |
# Convert document pdf with A4 format as a booklet with A5 format. | |
# A output/ folder will be created in the current directory containing: | |
# - input.pdf : original modified pdf document (with blank pages, to have a | |
# number of pages which is a multiple of 4). | |
# - output.pdf : booklet | |
# | |
# usage: bash pdf-to-booklet.bash <pdfname> | |
get_n_pages() { | |
local pdfname="$1" | |
pdfinfo "${pdfname}" | grep Pages | sed 's/[^0-9]*//' | |
} | |
add_blank_pages() { | |
local pdfname="$1" | |
local n_pages=$2 | |
convert xc:none -page A4 blank.pdf | |
for _ in $(seq 1 $[n_pages % 4]); do | |
pdfunite "${pdfname}" blank.pdf "${pdfname}.bak" | |
mv "${pdfname}.bak" "${pdfname}" | |
done | |
} | |
get_num_pages() { | |
local n=$1 | |
local i=$2 | |
echo "$n,$i,$[$i+1],$[$n-1]," | |
} | |
get_all_num_pages() { | |
local n=$1 | |
local i=1 | |
local num_pages='' | |
while [[ $[$n - $i] -gt 1 ]]; do | |
num_pages=${num_pages}$(get_num_pages $n $i) | |
n=$[n-2] | |
i=$[i+2] | |
done | |
echo "${num_pages:0:${#num_pages}-1}" | |
} | |
if [[ ${FUNCNAME[0]} = "main" ]]; then | |
echo "Creating booklet..." | |
pdfname="$1" | |
mkdir -pv output/ | |
cp -v "${pdfname}" output/input.pdf | |
cd output/ | |
n_pages=$(get_n_pages input.pdf) | |
add_blank_pages input.pdf ${n_pages} | |
mod_4=$[${n_pages} % 4] | |
[[ ${mod_4} -eq 0 ]] && n_pages_4=${n_pages} \ | |
|| n_pages_4=$[${n_pages} + 4 - ${mod_4}] | |
num_pages=$(get_all_num_pages ${n_pages_4}) | |
pdfjam --landscape --nup 2 input.pdf "${num_pages}" -o output.pdf | |
echo "...OK" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment