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

新手上路,请多包涵

我想打印 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>

我尝试了一切:

  • 位置:相对(不变)、绝对(仅在第一页页脚)、固定(仅在最后一页)
  • 将 html、body、每个 div 高度设置为 100%。不知道我为什么要这样做。没有改变任何东西

也许有一种方法可以强制我的浏览器 (FF) 将 div 粘贴到页面底部

原文由 peku33 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 595
2 个回答

终于找到了答案:

  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>

原文由 peku33 发布,翻译遵循 CC BY-SA 3.0 许可协议

更新 我对上面的代码进行了一些尝试,这可能比我最初想象的更容易。 (请注意,页脚有可能与前一个 div 的内容重叠,这可以通过向内容 div 添加一个 margin-bottom 属性来解决,该属性等于您自定义的页脚设置的高度 - 此外,如果您的页面内容分页之间的时间太长,这仍然有几个场景需要参加)。综上所述,我在本地进行了测试,结果如您所愿。

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>

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>


原始答案

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

您最好的选择是将您想要的信息放在 <head><title>YOUR COMMON CONTENT</title></head> 它不会是最漂亮的。这取决于您的要求。

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

原文由 Arthur Weborg 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题