如何使用phantom-html2pdf在PDF页面中添加页眉和页脚

时间:2016-07-01 07:17:38

标签: express coffeescript html2pdf

我无法使用Express和Coffeescript使用phantom-html2pdf找到在pdf页面中添加页眉和页脚的方法。我的代码如下,请您查看并告诉我我缺少的内容:

    pdf = require('phantom-html2pdf')    
    exports.test_pdf = (req, res) ->
      paperSize = {
        format: 'A4',
        margin: "1cm",
        orientation: 'portrait'
        header: {
          height: "200cm",
          contents: '<h1>This is the Header</h1>'
        },
      }

      htmls = '<html><body><h2>PDF CONTENT</h2></body></html>';

      options = {
        html: htmls,
        css: "./public/stylesheets/foundation.css",
        paperSize : page.paperSize
      }
      pdf.convert options, (err, result) ->

        if !err
          result.toBuffer()
          # Using a readable stream
          result.toStream()

          # Using the temp file path */
          result.getTmpPath()

          # Using the file writer and callback */
          result.toFile("./html/pdf_file.pdf")
        else
        res.render('index', { title: 'Social Media'})

我已经做过一些研究,要添加页眉和页脚,我需要从runnings文件中导出paperSize对象。 https://github.com/bauhausjs/phantom-html2pdf/issues/30 但是添加它也无法帮助我,或者我没有正确添加它。

一点帮助将不胜感激。提前谢谢。

1 个答案:

答案 0 :(得分:2)

module.exports将解决您的问题。为header&amp;创建页面对象后页脚。您将使用module.export导出对象。

以下是示例代码

module.exports = {
    header: {
        height: '3cm', contents: function (page) {
            return '<header class="pdf-header" style=" overflow:hidden; font-size: 10px; padding: 10px; margin: 0 -15px; color: #fff; background: none repeat scroll 0 0 #00396f;"><img style="float: left;" alt="" src="../images/logo.jpg"><p> XYZ </p></header>'
        }
    },

    footer: {
        height: '3cm', contents: function (page) {
            return '<footer class="pdf-footer" style="font-size: 10px; font-weight: bold; color: #000;><p style="margin: 0">Powered by XYZ</p></footer>'
        }
    },

}

注意:您需要创建运行文件并复制&amp;将代码粘贴到其中。