首页 > 解决方案 > 如何在 pdf 生成期间添加不同的页脚 (flyingsaucer/itext)

问题描述

我有一个要转换为 PDF 的 HTML 文件。我使用 freemarker 模板来描述 HTML + CSS + 自定义字体。PDF 生成后,PDF 文件包含 10 页(页数是动态的)我需要为第一页、第 4 页和第 8 页设置不同的页脚

对于第一页,我通过以下方式设置页脚:

@page: first {
   @bottom-center {
       content: element(footer);
   }
}

它有效,但如何在第 4 页和第 8 页设置不同的页脚?这里还有一个困难,不同页脚应该设置的页数可以改变

我尝试使用命名页面,例如:

@page different_section: first {
   @bottom-center {
       content: element(footer);
   }
}
#different_section {page:different_section}

但这不起作用。

也许有办法通过代码来做到这一点?

标签: javacssitextflying-saucer

解决方案


这是一个使用CSS3 命名 pages的解决方案。

包含具有特定类或 id 的元素的页面的页脚已更改。

<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);}

        @page pagewithspecialfooter {@bottom-center {content: element(specialfooter)}}
        #specialfooter{position: running(specialfooter);}
        .page4and8  {page:pagewithspecialfooter;}
    </style>
</head>
<body>
<div id="footer">Default footer</div>
<div id="specialfooter">A different footer that appear on page 4 and 8</div>

<div>Page 1 content</div>
<div class="newpage">Page 2 content</div>
<div class="newpage">Page 3 content</div>
<div class="newpage page4and8">Page 4 content</div>
<div class="newpage">Page 5 content</div>
<div class="newpage">Page 6 content</div>
<div class="newpage">Page 7 content</div>
<div class="newpage page4and8">Page 8 content</div>
<div class="newpage">Page 9 content</div>
</body>
</html>

推荐阅读