[SalesForce] Add CSS classes and repeating header to Visualforce PDF

I have a Visualforce page that renders as a PDF. It displays a table of data and an image on the header on each page:

<apex:page renderAs="pdf">
  <head>
  <style type="text/css" media="print">
    @page {
      @top-center {
        content: element(header);
      }
    }

    div.header {
      position: running(header);
    }

    .sectionTitle {
      font-weight: bold;
    }
  </style>
  </head>

  <div class="header">
    <img src="{!$Resource.logo}" width="25%"/>
  </div>

  <div class="content">
    <table>
      <tr>
        <td class="sectionTitle">test</td>
      </tr>
    </table>
  </div>
</apex:page>

My issue is that I want to apply CSS classes to my table elements; however the CSS is not applied (in this example the text should be bold but it doesn't). If I set the applyBodyTag or applyHtmlTag of apex:page to false, it does take effect the CSS classes for the table but the header breaks.

Any ideas?

Best Answer

Change your <apex:page> to this:

<apex:page renderAs="pdf" applyBodyTag="false">

According to the docs:

A Boolean value that specifies whether or not Visualforce should automatically add a <body> tag to the generated HTML output. Set to false to disable adding the <body> tag to the response, for example, when the tag is statically set in your markup. If not specified, this value defaults to the value of the applyHtmlTag attribute if it's set, or true, if applyHtmlTag isn't set.

Using the sample you provided, I was able to render the following as PDF:

enter image description here

The header (logo) appears on every page as expected using the following VF:

<apex:page renderAs="PDF" applyBodyTag="false">
  <head>
  <style type="text/css" media="print">
    @page {
      margin-top: 1.5in;
      @top-center {
        content: element(header);
      }
    }
    div.header {
      position: running(header);
    }
    .sectionTitle {
      font-weight: bold;
    }
  </style>
  </head>
  <div class="header">
    <center><img src="{!$Resource.logo}" width="25%"/></center>
  </div>
  <div class="content">
    <table>
      <tr>
        <td class="sectionTitle">test</td>
      </tr>
      <!--rest removed for brevity...-->
    </table>
  </div>
</apex:page>
Related Topic