2014-11-16 30 views
1

我試圖將標題添加到使用node-webshot生成的PDF中,但沒有顯示出來。將標題添加到Node生成的PDF Webshot

我使用這個代碼:

webshot('https://www.google.com', 'google.pdf', options, function (err) { 
    if(err) throw err; 
    console.log('Saved to PDF'); 
}); 

隨着選項對象是這樣的:

var options = { 
     "paperSize": { 
      "format": "A4", 
      "orientation": "portrait", 
      "border": "0.25cm", 
      "header": { 
       "height": "2cm", 
       "contents": function() { 
        return phantom.callback(function(pageNum, numPages) { 
         return '<h1>' + pageNum + '/' + numPages + '</h1>'; 
        }); 
       } 
      } 
     } 
    }; 

我試着做內容的功能它是如何表現的PhantomJS documentation但它不工作,因爲幻像沒有定義。我找不到任何如何使用webshot添加頁眉/頁腳的例子。

PDF生成正確,但標題爲空,沒有寫入任何內容。

我該如何解決這個問題?

+0

我的回答有幫助嗎?有什麼問題嗎?你可以[接受](http://meta.stackexchange.com/a/5235)一個答案,如果它解決了你的問題(只是你知道)。 –

回答

0

由於選項作爲對象傳遞到webshot並且「回調」是直接的,所以沒有辦法繞過修改webshot。

因此改變從here到線(文件節點webshot/LIB/webshot.phantom.js):

optUtils.phantomPage.forEach(function(key) { 
    if (toOverwrite[key]) page[key] = toOverwrite[key]; 
    if (key === "paperSize" && page[key] && page[key].header && page[key].header.contents) { 
    page[key].header.contents = eval(page[key].header.contents); 
    } 
    if (key === "paperSize" && page[key] && page[key].footer && page[key].footer.contents) { 
    page[key].footer.contents = eval(page[key].footer.contents); 
    } 
}); 

前提是你撰寫的標題內容的功能這樣的字符串:

"contents": "phantom.callback(function(pageNum, numPages) { return '<h1>' + pageNum + '/' + numPages + '</h1>'; })"; 

它不能作爲函數傳遞,因爲沿着選項對象被字符串化的方式刪除所有函數。

0

我知道這個問題已經超過一年了,但對於與上面相同的問題的其他人,eval()並不適用於我。我落得這樣做是將在同一地點如下代碼:

if (key === "paperSize" && page[key] && page[key].header && page[key].header.contents) { 
    var header = { 
     "height": page[key].header.height, 
     "contents": phantom.callback(function() {return options.paperSize.header.contents;}) 
    } 
    page.paperSize.header = header; 
    } 
    if (key === "paperSize" && page[key] && page[key].footer && page[key].footer.contents) { 
    var footer = { 
     "height": page[key].footer.height, 
     "contents": phantom.callback(function() {return options.paperSize.footer.contents;}) 
    } 
    page[key].footer = footer 
    } 
    if (key === "paperSize") { 
    page.paperSize = { 
     "format": options.paperSize.format, 
     "orientation": options.paperSize.orientation, 
     "margin": options.paperSize.margin, 
     "header": header, 
     "footer": footer 
    } 
    } 

這樣做的原因是webshot stringifies在選項中的所有數據對象,所以phantom.callback呈現頁眉和頁腳與phantomjs沒有按要求沒有正確的字符串。相反,你需要在你的選項對象中添加你將要用在頁眉/頁腳中的html,然後將它插入到上面代碼中的phantom.callback中。這種方法唯一的問題是你不能在回調中使用numPages和pageNum參數。

相關問題