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”。

  • 方向 − “Portrait”(縱向)和“Landscape”(橫向)。預設為“Portrait”(縱向)。

  • 頁首和頁尾 − 頁首和頁尾可以以物件的格式提供,包含高度和內容屬性。

語法

其語法如下:

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 = "https:///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(output) 將給定的URL轉換為pdf格式。pdf檔案將儲存在指定的output中,在上面的例子中我們將其指定為var output = "test.pdf"。

我們可以定義想要儲存檔案的路徑。它將提供使用頁首和頁尾的papersize尺寸的pdf格式。您可以執行上述程式碼並檢視pdf檔案的渲染方式。

phantomjs_webpage_module_properties.htm
廣告
© . All rights reserved.