【问题标题】:Print variable inside the footer of PDF creation在 PDF 创建的页脚内打印变量
【发布时间】:2019-04-10 17:01:00
【问题描述】:

我需要在页面的页脚内打印一个对象字段。目前我有:

async function createPdf(obj, res) {
        //other code
        const pdf = await page.pdf({ 
        format: 'A4', 
            printBackground: true, 
            displayHeaderFooter : true,
            headerTemplate : "",
        footerTemplate : "<style>.footer{width: 100%; font-size:12px; text-align:right; color:white; background:#161719; -webkit-print-color-adjust:exact; margin-bottom:-15px;}</style><div class='footer'><span>page </span><span class='pageNumber'></span>/<span class='totalPages'></span></div>",
            //margin top 0 removes header
            margin: {top: "00", bottom: "18"}
        });
        //other code
}

我需要在页脚内打印一些obj 过滤器,但我尝试过的所有方法都将obj 打印为字符串而不是内容。是否有可能实现我的目标?

【问题讨论】:

    标签: javascript node.js pdf-generation google-chrome-devtools puppeteer


    【解决方案1】:

    为了在使用 page.pdf() 创建 PDF 时在页脚内打印变量,您可以使用将 footerTemplate HTML 放在 template literal (``) 内并将变量插入占位符内(${})。

    请看下面的例子:

    const example = 'Hello, world!';
    
    const pdf = await page.pdf({
      format: 'A4',
      printBackground: true,
      displayHeaderFooter: true,
      headerTemplate: '',
      footerTemplate: `<style>
                       .footer {
                         background: #161719;
                         color: #fff;
                         -webkit-print-color-adjust: exact;
                         color-adjust: exact;
                         font-size: 12px;
                         margin-bottom: -15px;
                         text-align: right;
                         width: 100%;
                       }
                       </style>
                       <div class="footer">
                         <span>${example}</span> <!-- Variable Inside Footer -->
                         <span>page</span>
                         <span class="pageNumber"></span>/<span class="totalPages"></span>
                       </div>`,
      //margin top 0 removes header
      margin: {
        top: 0,
        bottom: 18,
      },
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-30
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      • 2012-05-22
      • 2015-01-01
      • 1970-01-01
      • 2018-12-17
      相关资源
      最近更新 更多