【问题标题】:PhantomJs set header margin to 0 when rendering pdfPhantomJs 在渲染 pdf 时将页眉边距设置为 0
【发布时间】:2014-11-17 17:48:12
【问题描述】:

我正在使用 Node.js 和模块 phridge(版本 1.0.3)通过 PhantomJs 呈现 pdf。

我想在页眉和页脚中呈现没有任何边距的 pdf。目前我只发现了一个通过负左右边距来删除左右边距的技巧。

可以在此处找到打印带有页码的页眉和页脚的示例: https://github.com/ariya/phantomjs/blob/master/examples/printheaderfooter.js

// creates a new webpage internally
var page = phantom.createPage(),
    outputFile = path.join(options.destDir, options.destFile);

/*global window:false */
// page.run(fn) runs fn inside PhantomJS
page.run(html, outputFile, options.header, options.footer, options.delay,
  function (html, outputFile, header, footer, delay, resolve /*, reject*/) {
  // Here we're inside PhantomJS, so we can't reference variables in the scope.
  // 'this' is an instance of PhantomJS' WebPage as returned by require("webpage").create()
  var page = this;

  page.content = html;
  page.viewportSize = { width: 1190, height: 1684 }; // 144dpi

  page.paperSize = {
    format: 'A4',
    header: {
      // How do I set the margin to 0px? margin: 0px or border: 0px doesn't work.
      height: '80px'
      contents: phantom.callback(function (pageNum, numPages) {
        return header.contents.replace(/<%= pageNum %>/g, pageNum).replace(/<%= numPages %>/g, numPages);
      })
    },
    footer: {
      height: '80px'
      contents: phantom.callback(function (pageNum, numPages) {
        return footer.contents.replace(/<%= pageNum %>/g, pageNum).replace(/<%= numPages %>/g, numPages);
      })
    },
  };

  // Wait until JavaScript has run
  window.setTimeout(function () {
    page.render(outputFile, { format: 'pdf', quality: '100' });
    page.close();
    page = null;
    resolve(outputFile);
  }, delay);

我使用负边距删除了左右页眉边距。为此,我使用了内联样式。 例如,当 header.contents 为:

<div style="background-color: rgb(230, 231, 232);margin:-20px;height:80px;">
  <img style="text-align:center" src="file:///C:/image.png" alt="image">
</div>

在较早的尝试中,我在内部 CSS 样式表中添加了边距。不幸的是,似乎没有应用这种样式。在其他地方我读到这种行为的原因是使用 phantom.callback() 时只应用了内联样式。

<style type="text/css">
  @page {
    margin: 0;
  }
  * {
    margin: 0px;
    padding: 0px;
  }
  body {
    margin: 0px;
  }
</style>

如何去除页眉和页脚的上下边距?

感谢阅读!

【问题讨论】:

    标签: javascript css node.js pdf phantomjs


    【解决方案1】:

    原来由于dpi不同,不同平台(Linux、Windows)的页眉和页脚呈现方式不同。

    这是一个关于它的讨论:https://groups.google.com/forum/#!topic/phantomjs/YQIyxLWhmr0

    根据平台更改 zoomFactor 消除了白色间隙:

    page.zoomFactor = (PLATFORM === 'linux'?  0.654545: 0.9)
    

    【讨论】:

      【解决方案2】:

      为要呈现为 pdf 的 html 文件尝试以下 CSS:

      body {
          padding: 0;
          margin: 0;
      }
      

      似乎body“默认”在顶部和底部有一些填充。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-10
      • 2018-02-16
      • 2011-02-09
      • 2015-02-20
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多