10

I have multiple pages generated using PDFKit. How can I add page numbers to the bottom?

John Topley
  • 113,588
  • 46
  • 195
  • 237
Satchel
  • 16,414
  • 23
  • 106
  • 192

4 Answers4

15
PDFKit.configure do |config|
  config.default_options = {
    header_right: "Page [page] of [toPage]"
  }
end

kit = PDFKit.new(body_html)

Read all detailed documentation here:
http://madalgo.au.dk/~jakobt/wkhtmltoxdoc/wkhtmltopdf-0.9.9-doc.html

PDFKit is just a wrap up for wkhtmltopdf application that is written in C.

rusty
  • 2,771
  • 1
  • 24
  • 23
libo meyers
  • 214
  • 2
  • 3
  • Works great, seems easier than the script option. Only thing is is should be underscored ie header_right – riley Sep 24 '12 at 18:49
  • This answer should be accepted. Please note the commented what @riley mentioned. Needs to be header_right. footer_right also works. – Hendrik Aug 15 '13 at 11:53
  • 1
    @hendrik This solution will not work if you use `footer_html` option. – abhishek77in Sep 17 '18 at 09:18
13

you need to specify a footer like this:

kit = PDFKit.new(your_html_content_for_pdf, :footer_html => "#{path_to_a_footer_html_file}")

then in the footer file have this:

<html>
  <head>
    <script type="text/javascript">
      function subst() {
        var vars={};
        var x=document.location.search.substring(1).split('&');
        for(var i in x) {var z=x[i].split('=',2);vars[z[0]] = unescape(z[1]);}
        var x=['frompage','topage','page','webpage','section','subsection','subsubsection'];
        for(var i in x) {
          var y = document.getElementsByClassName(x[i]);
          for(var j=0; j<y.length; ++j) y[j].textContent = vars[x[i]];
        }
      }
    </script>
  </head>
  <body style="margin: 0;" onload="subst();">
    Page <span class="page"></span> of <span class="topage"></span>
  </body>
</html>

elements of classes 'frompage','topage','page','webpage','section','subsection','subsubsection' will get substituted with the appropriate data

Kalendae
  • 2,256
  • 1
  • 21
  • 23
  • hthanks, i wrapped the footer in – Satchel Feb 19 '11 at 04:36
  • hello, I think I have a slight problem: I mass-merge multiple contacts of my letters into a single document...it may be a two page letter but I have 15 of them, so it shows page numbers as 1...31....can I change that? – Satchel Feb 20 '11 at 06:42
10

I did page number with PDFKit, just by adding this:

%meta{:name => 'pdfkit-footer_right', :content => "[page]"}

in my haml file, in my RoR project.

Perception
  • 79,279
  • 19
  • 185
  • 195
Anezio Campos
  • 1,555
  • 1
  • 10
  • 18
0

For some weird reason, ( perhaps because I'm using slim ) - I have to use single quotes around the content, instead of double quotes - or else it attempts to escape the brackets and raw text "[page]" shows up, so try single quotes if you run into this issue with your pages.

kikuchiyo
  • 3,391
  • 3
  • 23
  • 29