【发布时间】: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