Skip to content

Instantly share code, notes, and snippets.

@Cybso
Created April 3, 2017 14:40
Show Gist options
  • Save Cybso/f620b9882457546c8eed31b114b3cc87 to your computer and use it in GitHub Desktop.
Save Cybso/f620b9882457546c8eed31b114b3cc87 to your computer and use it in GitHub Desktop.
Put a stamp on the last page of a PDF document using PDFTK
#!/bin/bash
if [ "$1" == "" -o "$2" == "" -o "$3" == "" -o "$4" != "" -o "$1" == "-h" -o "$1" == "--help" ]; then
echo "Puts a stamp (as PDF file) onto the last page of the input" >&2
echo "file using PDFTK". >&2
echo "" >&2
echo "Usage: $0 INPUT.pdf STAMP.pdf OUTPUT.pdf" >&2
exit 1
fi
tmpfile1="$(mktemp --suffix=.pdf)"
tmpfile2="$(mktemp --suffix=.pdf)"
cleanup() {
test -e "$tmpfile1" && rm "$tmpfile1"
test -e "$tmpfile2" && rm "$tmpfile2"
}
die() {
echo "$@" >&2
cleanup
kill $$
exit 1
}
addStamp() {
pdftk "$1" stamp "$2" output "$3" || die "Failed to add stamp"
}
case "$(pdftk "$1" dump_data | grep -oP '(?<=NumberOfPages: ).*')" in
0)
die "Cannot handle empty document"
;;
1)
addStamp "$1" "$2" "$3"
;;
*)
# Extract last page and put stamp on it
pdftk "$1" cat end output "$tmpfile1" || die "Failed to extract last page"
addStamp "$tmpfile1" "$2" "$tmpfile2"
# Extract all but last page
pdftk "$1" cat 1-r2 output "$tmpfile1" || die "Failed to extract page range"
# Merge both
pdftk "$tmpfile1" "$tmpfile2" cat output "$3" || die "Failed to merge pages"
;;
esac
cleanup
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment