WickedPDF different margin settings for first page?

2.6k Views Asked by At

Using:

wkhtmltopdf-binary 0.9.9.1
wicked_pdf         0.10.2
rails              4.1.7
ruby               2.1.3
OS X               10.10.1 (64-bit)

I have a header that takes a bit of space, so I had to use :margin => { :top => 40 } (along with header spacing) in my WickedPDF options. However, I don't want this for my first page, because the header is only used on page 2 and above. How do I achieve this?

Attempts

  1. For contents in the first page, via CSS I tried:

    position: absolute;
    top: -20;
    

    Which results in the content being "clipped" by the margin region. It seems that applying :margin => {:top=>40} creates a blocking white rectangle between the header fragment and the PDF contents.

  2. I tried using the :cover option for the first page. Unfortunately, the margin setting is also applied to the cover template. Also, there seems to be a syntax difference in wkhtmltopdf 0.12 so it breaks

Some solutions I can think of:

  1. Create 2 separate PDF and join them together. Need to find PDF merging gems, etc.
  2. Generate persistent header via Javascript. This is quite tricky to be honest; especially when there are table breaks (table height is more than one page). Also, the header is different for every content sections. I currently have this working via wkhtmltopdf javascript helpers (frompage, topage, page, section, etc.)

Any help would be gladly appreciated.

1

There are 1 best solutions below

1
On

Add a script with the --header-html set to the following:

<!DOCTYPE html>
<html>
<head>
    <script>
        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]);}

          if(vars['page'] == 1) { // If page is 1, do not show the header
              document.getElementById("doc-header").style.display = 'none';
          }
       }
   </script>
</head>
<body onload="subst()">
    <div id="doc-header">
       ... your content here ...
    </div>
</body>
</html>

This should work with the latest wkhtmltopdf stable release (0.12.1) -- this sample was taken from a crash which was fixed in this release.