How to add page numbers to the footer of a PDF

You'll need the ghostscript and pdftk packages installed for the following to work.

Adjust the input parameters as necessary:
inputfile="input.pdf"
fontfamily="Arial"
fontcolor="12538a"
fontsize="12"
hoffset="12" # workaround for center positioning bug
voffset="30" # distance from the bottom of the page

Calculate various parameters for the script:
fontcolor="$(echo "$fontcolor" | tr 'a-z' 'A-Z')"
red="$(echo "scale=6; ibase=16; x=$(echo "$fontcolor" | cut -c1-2)/FF; if (x<1) print 0; x" | bc)"
green="$(echo "scale=6; ibase=16; x=$(echo "$fontcolor" | cut -c3-4)/FF; if (x<1) print 0; x" | bc)"
blue="$(echo "scale=6; ibase=16; x=$(echo "$fontcolor" | cut -c5-6)/FF; if (x<1) print 0; x" | bc)"
totalpages="$(pdftk "$inputfile" data_dump | sed -r "s|^NumberOfPages: (.*)|\1|;t;d")"
pdftk "$inputfile" data_dump | egrep "^PageMediaDimensions:" | read dontcare width height
center="$(echo "scale=0; $width / 2 - $hoffset" | bc)"
width10="$(echo "scale=0; 10.0 * $width / 1" | bc)"
height10="$(echo "scale=0; 10.0 * $height / 1" | bc)"

And finally generate a PDF with pagenumbers using Ghostscript and merge it with the original PDF using pdftk:
gs -q -o - -sDEVICE=pdfwrite -g${width10}x${height10} -c "/${fontfamily} findfont ${fontsize} scalefont setfont 1 1 ${totalpages} { $red $green $blue setrgbcolor /PageNo exch def PageNo 2 string cvs dup stringwidth pop 0.5 mul ${center} exch sub ${voffset} moveto show ( / ${totalpages}) show showpage } for" | \
pdftk "$inputfile" multistamp - output - | \
pdftk - cat output output.pdf

This should (if everything went well) produce an output.pdf file with page numbers:
  • horizontally centered at the bottom of every page
  • with 0x12538a color
  • Arial font
  • 12pt font size
  • 30 units vertically from the bottom of the page
The final pdftk - cat output output.pdf command in the script merely removes the "garbage" from the PDF, greatly reducing the filesize in the process.

Syndicate content