Last active
March 11, 2021 23:17
-
-
Save joostrijneveld/6783365 to your computer and use it in GitHub Desktop.
Combines PDF files and adds white pages in between to allow double-sided printing without mixing documents. Requires a blank.pdf file.
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
#! /bin/bash | |
if [ -z "$1" ]; then | |
echo "Specify which folder contains the PDFs" | |
exit 1 | |
fi | |
OUTFILE=combined_$1.pdf | |
if command -v convert >/dev/null 2>&1; then | |
convert xc:none -page A4 blank.pdf | |
elif command -v pdflatex >/dev/null 2>&1; then | |
pdflatex -jobname 'blank' "\documentclass[a4paper]{article}\usepackage{geometry}\begin{document}\null\end{document}" >/dev/null 2>&1 | |
rm -f blank.aux | |
rm -f blank.log | |
elif ! [[ -e 'blank.pdf' ]]; then | |
echo "Could not find 'convert' or 'pdflatex'; manually create an empty PDF called blank.pdf" | |
exit 1 | |
fi | |
first=true | |
i=$OUTFILE | |
o=$(mktemp) | |
for f in $1/*.pdf | |
do | |
if $first; then | |
first=false | |
args=("$f") | |
else | |
args=($i "$f") | |
fi | |
c=$(pdftk "$f" dump_data output | grep -i NumberOfPages | sed s/NumberOfPages:\ //) | |
if [ $(($c%2)) = 1 ]; then | |
args+=(blank.pdf) | |
fi | |
pdftk "${args[@]}" cat output $o | |
t=$i | |
i=$o | |
o=$t | |
done | |
if [ -f $o ]; then | |
rm $o | |
fi | |
mv $i $OUTFILE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for your contribution. It helped me to get an idea to where i need to go.
The problem here is that your script is running out of memory after a certain amount of iterations (in my case 700+ PDFs with 6 pages on average) because you concatenate each newly created pdf with each next pdf recursively instead of extending first the odd paged PDFs and then merging all at once at the end.
This can be done in a performant and elegant one-liner assuming you have a blank.pdf already available. (See: https://superuser.com/questions/1442122/supressing-duplex-for-single-pages-in-pdf)
pdftk $(for i in *.pdf; do echo $i; pdftk $i dump_data | perl -ne 'print "/path/to/blank.pdf\n" if (m/NumberOfPages: (\d+)/ && $1 % 2 == 1)'; done) cat output merged.pdf