在打印时将每页上的自定义页脚粘贴到底部

pek*_*u33 14 html css

我想要打印30页,其中一些数据位于顶部,一些数据位于底部.我的代码看起来像:

<...>



<div style="page-break-after: always">
    <div>This should be on top1</div>
    <div>This should be on bottom1</div>
</div>
<div style="page-break-after: always">
    <div>This should be on top2</div>
    <div>This should be on bottom2</div>
</div>


<etc>
Run Code Online (Sandbox Code Playgroud)

我尝试了一切:

  • 位置:相对(无变化),绝对(仅限第一页页脚),固定(仅限最后一页)
  • 将html,body,每个div高度设置为100%.没有想法我为什么要这样做.没有改变什么

也许有办法强制我的浏览器(FF)将div粘贴到页面底部

pek*_*u33 16

终于找到了答案:

  1. html,身体必须有高度:100%;
  2. 应该有两种类型的div:外部(页面大小),页脚
  3. 对于两个设置显示:块;
  4. 对于外部设定高度:100%; 位置:相对;
  5. 对于内部设定位置:绝对; 底部:0px;

瞧!

这是我的完整代码:

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <style>
        html,body
        {
            height: 100%;
            margin: 0px;
        }
        body > div
        {
            height: 100%;
            display: block;
            position: relative;
        }
        body > div > div
        {
            position: absolute;
            bottom: 0px;
            left: 0px;
        }
    </style>
</head>
<body>
    <div>
        Page1
        <div>Page1Footer</div>
    </div>
    <div>
        Page2
        <div>Page2Footer</div>
    </div>
    <div>
        Page3
        <div>Page3Footer</div>
    </div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)


Art*_*org 5

更新 我使用上面的代码玩了一下,这可能比我最初的想法更容易.(注意,页脚可能会重叠前一个div的内容,这可以通过向margin-bottom内容div 添加一个等于自定义页脚设置高度的属性来解决- 另外,如果页面内容在分页符之间太长,这仍然会有一些需要参加的场景).所有这一切,我在本地测试,它按你的需要工作.

CSS

<style>
@media print{
    .footer{
       position:relative;
       top:-20px; // this sets the footer -20px from the top of the next 
                  //header/page ... 20px above the bottom of target page
                  //so make sure it is more negative than your footer's height.

       height:10px;//notice that the top position subtracts 
                   //more than the assigned height of the footer
    }
}
</style>
Run Code Online (Sandbox Code Playgroud)

HTML

<body>
   <div style="page-break-after: always">
      <div>This should be on top1</div>
   </div>
   <div style="page-break-after: always">
      <div class="footer">This should be on bottom of page1</div>
      <div>This should be on top2</div>
   </div>
   <div class="footer">This should be on bottom of page2</div>
</body>
Run Code Online (Sandbox Code Playgroud)


原始答案

不幸的是,没有简单的方法可以做到这一点.浏览器不提供创建自定义页眉和页脚以进行打印的方法.

你最好的选择是将你想要的信息放在标题标签中的每一页上,而<head><title>YOUR COMMON CONTENT</title></head>不是最漂亮的.它归结为您的要求.

另一种选择是使用@media print(CSS)和javascript来动态计算和插入空白页的分页符/间隙,同时在已知纸张大小的绝对位置插入div(您的自定义页脚和/或页眉).然后在打印事件后动态更改格式.