PhantomJS paperSize 属性详解


发布日期 : 2019-01-30 23:30:02 UTC

访问量: 10 次浏览

PhantomJS paperSize 属性

paperSize 属性指定需要将网页转换为pdf格式时所需的页面尺寸,即网页的尺寸。paperSize 属性包含所需的尺寸信息,以对象形式表示。如果未定义 paperSize,将使用网页的尺寸。支持的尺寸单位有’mm’、’cm’、’in’和’px’。默认为 ‘px’。

参数

paperSize 属性具有以下参数:

  • Margin- 可以作为一个对象给出,包含’top’、’left’、’bottom’、’right’的值。默认为 0。例如:margin: {top: ‘100px’,left: ’20px’,right: ’20px’,bottom: ’10px’}
  • Format- 支持的格式为 ‘A3’、’A4’、 ‘A5’、 ‘Legal’、 ‘Letter’、 ‘Tabloid’。
  • Orientation- 可选值为 ‘Portrait’ 和 ‘Landscape’。默认为 ‘Portrait’。
  • Headers and Footers- 头部和页脚可以以对象形式提供,包含 heightcontents 属性。

语法

它的语法如下:

header: {
height: "1cm",
contents: phantom.callback(function(pageNumber, nPages) {
return "<h1>Header <b>" + pageNumber + " / " + nPages + "</b></h1>";
})
}
footer: {
height: "1cm",
contents: phantom.callback(function(pageNumber, nPages) {
return "<h1>Footer <b>" + pageNumber + " / " + nPages + "</b></h1>";
})
}

关于 paperSize 的语法如下:

wpage.paperSize = {
width: '600px',
height: '1500px',

margin: {
'top':'50px',
'left':'50px',
'rigth':'50px'
},
orientation:'portrait',

header: {
height: "1cm",
contents: phantom.callback(function(pageNumber, nPages) {
return "<h5>Header <b>" + pageNumber + " / " + nPages + "</b></h5>";
})
},
footer: {
height: "1cm",
contents: phantom.callback(function(pageNumber, nPages) {
return "<h5>Footer <b>" + pageNumber + " / " + nPages + "</b></h5>";
})
}
}

示例

让我们举个示例来理解 paperSize 属性的用法。

var wpage = require('webpage').create();
var url = "http://localhost/tasks/a.html";
var output = "test.pdf";

wpage.paperSize = {
width: '600px',
height: '1500px',

margin: {
'top':'50px',
'left':'50px',
'rigth':'50px'
},
orientation:'portrait',

header: {
height: "1cm",
contents: phantom.callback(function(pageNumber, nPages) {
return "<h5>Header <b>" + pageNumber + " / " + nPages + "</b></h5>";
})
},
footer: {
height: "1cm",
contents: phantom.callback(function(pageNumber, nPages) {
return "<h5>Footer <b>" + pageNumber + " / " + nPages + "</b></h5>";
})
}
}
wpage.open(url, function (status) {
if (status !== 'success') {
console.log('Page is not opening');
phantom.exit();
} else {
wpage.render(output);
phantom.exit();
}
});

以上程序生成以下输出

test.pdf

在上面的示例中,我们打开一个URL,并为其提供页面尺寸选项。wpage.render(output)将给定的URL转换为pdf格式。pdf文件将存储在上述示例中所提到的输出中,我们已经将其设置为var output = “test.pdf”。

我们可以定义存储文件的位置。它以使用页眉和页脚的纸张尺寸维度为您提供pdf格式。您可以执行上面的代码,看看如何呈现pdf文件。