PhantomJS - paperSize 属性
此属性提供网页的大小,即尺寸,需要使用该属性将网页转换为 pdf 格式。 paperSize 属性包含对象所需的尺寸。 如果未定义 paperSize,则将采用网页的尺寸。 支持的尺寸单位为"mm"、"cm"、"in"和"px"。 默认情况下为"px"。
参数
以下是 paperSize 属性的参数
边距 −它可以作为一个对象给出,其值为'top'、'left'、'bottom'、'right'。默认情况下,它将被视为 0。例如 - margin: {top: '100px',left: '20px',right: '20px'bottom: '10px'>
格式 − 支持的格式为'A3'、'A4'、'A5'、'Legal'、'Letter'、'Tabloid'。
方向 − '纵向' 和 '横向'。默认情况下为 '纵向'。
页眉和页脚 −页眉和页脚可以以具有高度和内容属性的对象格式提供。
语法
其语法如下 −
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 并为其提供 papersize 选项。wpage.render(输出)将给定的 URL 转换为 pdf 格式。pdf 文件将存储在上述输出中,在上面的例子中,我们将其指定为 var output ="test.pdf"。
我们可以定义您想要存储文件的位置。它为您提供了 pdf 格式以及与页眉和页脚一起使用的 papersize 尺寸。您可以执行上述代码并查看如何呈现 pdf 文件。
phantomjs_webpage_module_properties.html

