15 February 2012

Mixing Landscape and Portrait rendering in a Wicked PDF document

Wicked is an awesome ruby library for generating PDF documents from plain old HTML/CSS.

HTML and CSS are not just another language; they provide a model for representing a document, and if you were obliged to use something else you would eventually end up representing your documents using this model, even if your syntax layer differed from HTML (if you're really smart, you would have ended up with HAML/SASS, for example; same model, different prettiness).

This is why other libraries fail (where "fail" means "I don't like them") - they oblige you to learn a whole new model for representing documents.

Anyway, the point is that you might believe from the Wicked README that you can create a document in landscape mode, or in portrait mode, but you're out of luck if you want both in the same doc.

It turns out you're not out of luck; Wicked, as its name non-obviously suggests, ultimately relies on WebKit (via wkhtmltopdf) to render html pages. With WebKit, you have access to a whole bunch of modern CSS properties, including those that rotate your document. You don't even care that they're WebKit specific, because you don't have to care about cross-browser support: you're using a known webkit version running on your own server which you control.

Here's the CSS:

.page {
  width:            195mm
  height:           270mm
  page-break-after: always
  overflow:         hidden

.page .landscape {
  position:                  relative
  margin:                    270mm 0
  width:                     270mm
  height:                    195mm
  -webkit-transform:         rotate(-90deg)
  -webkit-transform-origin:  0mm 0mm

The .page rules simply define an A4 page (after margins), and guarantee a page-break at the end of each page, just in case your printer didn't understand. The CSS assumes that you print in portrait by default. When you want landscape, nest a <landscape> element inside your <page>. Here's an example:

  This is the first page. It gets printed in portrait mode

    This is the second page. It gets printed in landscape mode.
    You will have to twist your head to read it.

Not so bad, no? Good luck!


  1. When I tried this I get a gap down the left hand side (like the margin is about 100mm) when printing in landscape. Using 0.9.9 and also tested with 0.10... of webkit but both give the same output? Have you any idea (its nearly there but not quite?)

  2. The problems with this approach is when the page content span into multiple pages. Only first page will appear in pdf result. Also if the page contains header and footer, both will still printed with portrait layout, not get rotated.

  3. On the latest version of wkhtmltopdf I had to fiddle about with the webkit-transform-origin. I ended up using

    -webkit-transform-origin: 146mm 146mm;


Note: Only a member of this blog may post a comment.