Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify existing PDF to add "Page N of NNN" footer

How can I use pdftk either from the command line (or preferably from Ruby) to add page numbers to the bottom of a pre-existing PDF?

I'm looking for this format:

  • Page 1 of 2

  • Page 2 of 2

like image 990
jrhicks Avatar asked May 21 '15 15:05

jrhicks


1 Answers

If you want to do this with the help of pdftk, you can do it using either the multistamp or the multibackground operation. But first you'll have to prepare a document (with the software of your choice) which creates the Page X of Y footers on empty pages (as PDF).

Create Page Footers

You can use LibreOffice, OpenOffice, MS Winword,... whatever you prefer to create a multi-page file which contains empty page contents, but has the pages numbered. Just make sure you'll get a PDF output, and that your page numbers are exactly how you want them.

I'll create the page footer with the help of Ghostscript here. The following commands (which can easily be put into a shell script, and you can parametrize it accordingly so to use the correct number of total). This one uses a page size of 595x842 PostScript points (a.k.a. A4 size), and the font Helvetica in 12 pt size:

total=100
gs -o 100pagenumbers.pdf    \
   -sDEVICE=pdfwrite        \
   -g5950x8420              \
   -c "/Helvetica findfont  \
       12 scalefont setfont \
       1 1  ${total} {      \
       /PageNo exch def     \
       450 20 moveto        \
       (Page ) show         \
       PageNo 3 string cvs  \
       show                 \
       ( of ${total}) show  \
       showpage             \
       } for"

This creates a 100-page PDF file, 100pagenumbers.pdf.

Use pdftk to overlay the page numbers

The next command uses pdftk with multistamp to overlay the page numbering file to an original:

pdftk original.pdf              \
  multistamp 100pagenumbers.pdf \
  output pages-numbered.pdf
like image 164
Kurt Pfeifle Avatar answered Oct 17 '22 16:10

Kurt Pfeifle