Search code examples
itextflying-saucer

Show footer only on last page


I'm using flyingsaucer 9.1.1 with itext 2.17 to generate pdf files.

How can I show a footer (could be a div, a table or an img element) only on the last page but not on the other ones?


Solution

  • Unfortunately, CSS defines the page:first pseudo element, but doesn't define page:last.

    You still have the possibility to take advantage of a bug of flying-saucer, that makes the footer only appear after it is declared. So if you put the footer div at the end of the HTML, it will only appear on the last page.

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
     <style type="text/css">
        .newpage{page-break-before:always}
    
        @page{@bottom-center {content: element(footer)}}
        #footer {position: running(footer);}    
    }
     </style>
    </head>
        <body>
            <div>Page 1 content</div>
            <div class="newpage">Page 2 content</div>
            <div class="newpage">Page 3 content</div>
            <div id="footer">Footer on last page</div>
        </body>
    </html>
    

    It also works if you want a footer on each page, with a different content for the last page. You just have to define the footer div twice in the HTML.

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
     <style type="text/css">
        .newpage{page-break-before:always}
    
        @page{
          @bottom-center {content: element(footer)}}
          #footer {position: running(footer);}    
        }
     </style>
    </head>
        <body>
            <div id="footer">Footer for all pages except last</div>
            <div>Page 1 content</div>
            <div class="newpage">Page 2 content</div>
            <div class="newpage">Page 3 content</div>
            <div id="footer">Footer on last page</div>
        </body>
    </html>