Skip to content

Adding page numbers to PDFs on Linux

The follow Bash function takes an input PDF and adds page numbers in the lower right corner.

numberpdf() {
unset IFS                                                                       
OLD_IFS=$IFS && IFS=$'\n'                                                       
directory=$(pwd)     
outputFileName="/$(basename "$1" .pdf)"-with-page-numbers.pdf""
completeOutputFilePath="$directory$outputFileName"
remind "The output file is $completeOutputFilePath"
gs -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile=$completeOutputFilePath -c 'globaldict /MyPageCount 1 put << /EndPage {exch pop 0 eq dup {/Helvetica 12 selectfont MyPageCount =string cvs dup stringwidth pop currentpagedevice /PageSize get 0 get exch sub 20 sub 20 moveto show globaldict /MyPageCount MyPageCount 1 add put } if } bind >> setpagedevice' -f $1
IFS=$OLD_IFS     
}