木偶页眉和页脚未显示在首页上

nve*_*veo 1 google-chrome header footer puppeteer

我使用的是Puppeteer v1.6.0,使用displayHeaderFooter:true选项创建PDF时,首页上没有显示页眉和页脚,如何启用此功能?

Gra*_*ler 8

根据木偶文件

page.pdf(选项)

  • options< 对象 >选项对象,可能具有以下属性:
    • displayHeaderFooter< 布尔值 >显示页眉和页脚。默认为false
    • headerTemplate< 字符串 >用于打印标题的HTML模板。应该是有效的HTML标记,其中包含以下用于向其中注入打印值的类:
      • date 格式化的打印日期
      • title 文件名
      • url 文件位置
      • pageNumber 当前页码
      • totalPages 文档中的总页数
    • footerTemplate< 字符串 >打印页脚的HTML模板。应该使用与相同的格式headerTemplate
    • margin< 对象 >纸张边距,默认为无。
      • top< 字符串 >上边距,接受标有单位的值。
      • right< 字符串 >右边距,接受标有单位的值。
      • bottom< 字符串 >底边距,接受标有单位的值。
      • left< 字符串 >左边距,接受标有单位的值。
  • 返回:< Promise < 缓冲区 >>使用PDF缓冲区解析的Promise。

注意目前仅在Chrome headless中支持生成pdf。


注意 headerTemplatefooterTemplate标记具有以下限制:

  1. 模板内的脚本标签不进行评估。
  2. 页面样式在模板内不可见。

因此,请确保您使用的displayHeaderFooterheaderTemplate以及footerTemplate选择适当地允许适当的PDF生成。

另外,请确保通过CSS设置页眉和页脚的字体大小(可能需要使用内联CSS),并设置margin网页的选项,以确保网页的内容不会覆盖页眉和页脚。

例:

await page.pdf({
  path: 'example.pdf',
  displayHeaderFooter: true,
  headerTemplate: '<div id="header-template" style="font-size:10px !important; color:#808080; padding-left:10px"><span class="date"></span><span class="title"></span><span class="url"></span><span class="pageNumber"></span><span class="totalPages"></span></div>',
  footerTemplate: '<div id="footer-template" style="font-size:10px !important; color:#808080; padding-left:10px"><span class="date"></span><span class="title"></span><span class="url"></span><span class="pageNumber"></span><span class="totalPages"></span></div>',
  margin: {
    top: '100px',
    bottom: '200px',
    right: '30px',
    left: '30px',
  },
});
Run Code Online (Sandbox Code Playgroud)

  • 我必须添加 -webkit-print-color-调整:精确;在页脚和页眉上也可以使颜色发挥作用。 (2认同)