Skip to content

Instantly share code, notes, and snippets.

@haji-ali
Last active October 29, 2019 13:35
Show Gist options
  • Save haji-ali/6460f0d3942cae702d6a6d1e393340fd to your computer and use it in GitHub Desktop.
Save haji-ali/6460f0d3942cae702d6a6d1e393340fd to your computer and use it in GitHub Desktop.
Concatenates a list of pdfs ensuring that blank pages are added when the number of pages are odd.
#!/bin/sh
# USAGE: ./concat-pdf.sh *.pdf output-file.pdf
ALL_FILES=""
BLANK_FILE="/tmp/blank.pdf"
for OUTPUT_FILE; do true; done
if test -f "$OUTPUT_FILE"; then
echo "$OUTPUT_FILE already exists"
exit 1
fi
echo "" | ps2pdf -sPAPERSIZE=a4 - $BLANK_FILE
for PDF_FILE in $* ;do
if [ $PDF_FILE != "$OUTPUT_FILE" ]; then
pages=$(strings < $PDF_FILE | sed -n 's|.*Count -\{0,1\}\([0-9]\{1,\}\).*|\1|p' | sort -rn | head -n 1)
ALL_FILES="$ALL_FILES $PDF_FILE"
[ $((pages%2)) -ne 0 ] && ALL_FILES="$ALL_FILES $BLANK_FILE"
fi
done
echo "pdftk $ALL_FILES cat output output.pdf"
pdftk $ALL_FILES cat output output.pdf
rm -f $BLANK_FILE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment