Sunday, April 10, 2011

Some PDF tricks on Visualforce: Landscape, A4, page number and more

The beauty of Visualforce is simplicity. Remember the shock you received when you were told the entire page renders as PDF if you just add renderAs=PDF to the Page tag.

For those who thought I spoke alien language right now, here is the trick, to render a page as PDF, we add a simple attribute to the <apex: page> tag

<apex: page renderAs='pdf'>
This will render the entire page as PDF.

Now, say we need to add some extra features to the PDF. Like a page number in the footer or we need to render the page in landscape mode. Faced with this problem, I put on my Indiana Jones hat and went hunting for it in the vast hay-sack of the internet (read: googled extensively). Imagine my happiness when i found a big big page with many big big examples to solve the problem. The document I am referring to is from W3C, paged Box media.

Long story short, I now possess the ultimate secret of rendering the page in any format I want. So here are few tricks I learned from the page. To perform this tricks simply add the following code to your visualforce PDF page and see it bend to your command.

1. Rendering page as landscape

@page {
/* Landscape orientation */
size:landscape;
}

2. Rending page in different size

@page {
  size: 8.5in 11in;/* width height */
}

3. Rendering page in landscape A4

@page {
  size: A4 landscape;
}
4. Adding stuff in footer of the page

@bottom-right {
content: Some content;
}

5. Adding page number to the page

@page {
  size: 8.5in 11in;
  margin: 10%;

  @top-left {
    content: "Hamlet";
  }
  @top-right {
    content: "Page " counter(page);
  }
}


The other variations in box-model are top-left, top-center, top-right, bottom-left, bottom-right, bottom-center.

Hope this helps creating those awesome looking PDFs in visualforce. More information on many more tricks in a lot of detail can be collected from the mother ship itself.

Some more information is also given by the Quinton Wall on force.com blog.

Toodles for now,
Hope it helps,
Sid

P.s. Those who could early book into DF11, I envy you.