Created
February 21, 2017 09:18
-
-
Save tst2005/c5ee41b57e47a2110682efb353e805c7 to your computer and use it in GitHub Desktop.
copy a pdf by keeping the N first pages
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 [ $# -ne 3 ]; then | |
echo "Usage: $0 <n> <orig.pdf> <new.pdf>" | |
exit 1 | |
fi | |
command -v pdfseparate >/dev/null || { echo >&2 "require pdfseparate"; exit 1; } | |
command -v pdfunite >/dev/null || { echo >&2 "require pdfunite" ; exit 1; } | |
TMPDIR="$(mktemp -d -- /tmp/pdfkeepn.XXXXXXXX)" || exit 1 | |
trap 'rm -rf -- "$TMPDIR"' EXIT | |
N="$1" ; shift | |
origpdf="$1" ; shift | |
finalpdf="$1" ; shift | |
if [ ! -f "$origpdf" ]; then | |
echo "No such original file $origpdf" | |
exit 1 | |
fi | |
[ -d "$finalpdf" ] && finalpdf="$finalpdf/$(basename -- "$origpdf")" | |
if [ -e "$finalpdf" ]; then | |
echo "destination $finalpdf already exists" | |
exit 1 | |
fi | |
if [ "$origpdf" = "$finalpdf" ]; then | |
echo "source and destination are the same file!" | |
exit 1 | |
fi | |
listpages() { ( cd -- "$TMPDIR" && ls -1 -- *.pdf | sort -g; ); } | |
pdfseparate -f 1 -l $N "$origpdf" "$TMPDIR/%d.pdf" || echo "pdfseparate (returns $?)" | |
listpages | |
if [ $N -eq 1 ]; then | |
mv -f -- "$TMPDIR/1.pdf" "$TMPDIR/merged.pdf" | |
else | |
( cd -- "$TMPDIR" && pdfunite $(listpages) "merged.pdf"; ) || echo "pdfunite (returns $?)" | |
fi | |
mv -f -- "$TMPDIR/merged.pdf" "$finalpdf" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment