Modify existing PDF to add "Page N of NNN" footer
Asked Answered
T

2

10

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

Truckload answered 21/5, 2015 at 15:54 Comment(0)
R
15

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
Racecourse answered 23/5, 2015 at 19:56 Comment(1)
The installer linked to by the PDFtk site for macOS 10.12 doesn't work. See stackoverflow.com/questions/39750883 for a workaround.Vain
C
0

I repost my answer from here.

It's possible with pdfcpu:

pdfcpu stamp add -mode text -- "Pag. %p  " "scale:.4 abs, pos:br, rot:0  margins:10" in.pdf out.pdf

You can add a lot of options: look at its website.


As alternative, with GUI, there's jPDF Tweak.

Cuttlefish answered 14/3 at 17:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.